From 35d6e98e98f49de24ff7e443f589fc19fd9cfd2b Mon Sep 17 00:00:00 2001 From: vvakame Date: Thu, 30 Apr 2015 13:27:07 +0900 Subject: [PATCH 01/31] type narrowing by constructor signiture of interface --- src/compiler/checker.ts | 40 +++-- ...nstanceOfByConstructorSignature.errors.txt | 111 ++++++++++++++ ...rdsWithInstanceOfByConstructorSignature.js | 137 ++++++++++++++++++ ...rdsWithInstanceOfByConstructorSignature.ts | 89 ++++++++++++ 4 files changed, 368 insertions(+), 9 deletions(-) create mode 100644 tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt create mode 100644 tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js create mode 100644 tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 469ecf80c84..36f9bbb654b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5351,17 +5351,39 @@ module ts { } // Target type is type of prototype property let prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (!prototypeProperty) { - return type; + if (prototypeProperty) { + let targetType = getTypeOfSymbol(prototypeProperty); + if (targetType !== anyType) { + // Narrow to target type if it is a subtype of current type + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + // If current type is a union type, remove all constituents that aren't subtypes of target type + if (type.flags & TypeFlags.Union) { + return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, targetType))); + } + } } - let targetType = getTypeOfSymbol(prototypeProperty); - // Narrow to target type if it is a subtype of current type - if (isTypeSubtypeOf(targetType, type)) { - return targetType; + // Target type is type of constructor signiture + let constructorSignitures: Signature[]; + if (rightType.flags & TypeFlags.Interface) { + constructorSignitures = (rightType).declaredConstructSignatures; } - // If current type is a union type, remove all constituents that aren't subtypes of target type - if (type.flags & TypeFlags.Union) { - return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, targetType))); + if (rightType.flags & TypeFlags.Anonymous) { + constructorSignitures = (rightType).constructSignatures; + } + if (constructorSignitures) { + let constructorType = getUnionType(map(constructorSignitures, constructorSignature => { + if (constructorSignature.typeParameters && constructorSignature.typeParameters.length !== 0) { + // TODO convert type parameters to any or empty object types. e.g. Sample -> Sample or Sample<{}>. + } + return constructorSignature.resolvedReturnType; + })); + // Pickup type from union types + if (type.flags & TypeFlags.Union) { + return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, constructorType))); + } + return constructorType; } return type; } diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt new file mode 100644 index 00000000000..c7146541705 --- /dev/null +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt @@ -0,0 +1,111 @@ +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(12,10): error TS2339: Property 'bar' does not exist on type 'A'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(32,10): error TS2339: Property 'foo' does not exist on type '{}'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(33,10): error TS2339: Property 'foo' does not exist on type '{}'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(34,10): error TS2339: Property 'bar' does not exist on type '{}'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(63,10): error TS2339: Property 'bar2' does not exist on type 'C1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(82,10): error TS2339: Property 'bar' does not exist on type 'D'. + + +==== tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts (6 errors) ==== + interface AConstructor { + new (): A; + } + interface A { + foo: string; + } + declare var A: AConstructor; + + var obj1: A | string; + if (obj1 instanceof A) { // narrowed to A. + obj1.foo; + obj1.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'A'. + } + + var obj2: any; + if (obj2 instanceof A) { // can't type narrowing from any. + obj2.foo; + obj2.bar; + } + + // with generics + interface BConstructor { + new (): B; + } + interface B { + foo: T; + } + declare var B: BConstructor; + + var obj3: B | A; + if (obj3 instanceof B) { // narrowed to B. + obj3.foo = "str"; + ~~~ +!!! error TS2339: Property 'foo' does not exist on type '{}'. + obj3.foo = 1; + ~~~ +!!! error TS2339: Property 'foo' does not exist on type '{}'. + obj3.bar = "str"; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type '{}'. + } + + var obj4: any; + if (obj4 instanceof B) { // can't type narrowing from any. + obj4.foo = "str"; + obj4.foo = 1; + obj4.bar = "str"; + } + + // has multiple constructor signature + interface CConstructor { + new (value: string): C1; + new (value: number): C2; + } + interface C1 { + foo: string; + bar1: number; + } + interface C2 { + foo: string; + bar2: number; + } + declare var C: CConstructor; + + var obj5: C1 | A; + if (obj5 instanceof C) { // narrowed to C1. + obj5.foo; + obj5.bar1; + obj5.bar2; + ~~~~ +!!! error TS2339: Property 'bar2' does not exist on type 'C1'. + } + + var obj6: any; + if (obj6 instanceof C) { // can't type narrowing from any. + obj6.foo; + obj6.bar1; + obj6.bar2; + } + + // with object type literal + interface D { + foo: string; + } + declare var D: { new (): D; }; + + var obj7: D | string; + if (obj7 instanceof D) { // narrowed to D. + obj7.foo; + obj7.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'D'. + } + + var obj8: any; + if (obj8 instanceof D) { // can't type narrowing from any. + obj8.foo; + obj8.bar; + } + \ No newline at end of file diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js new file mode 100644 index 00000000000..c795126b0ff --- /dev/null +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js @@ -0,0 +1,137 @@ +//// [typeGuardsWithInstanceOfByConstructorSignature.ts] +interface AConstructor { + new (): A; +} +interface A { + foo: string; +} +declare var A: AConstructor; + +var obj1: A | string; +if (obj1 instanceof A) { // narrowed to A. + obj1.foo; + obj1.bar; +} + +var obj2: any; +if (obj2 instanceof A) { // can't type narrowing from any. + obj2.foo; + obj2.bar; +} + +// with generics +interface BConstructor { + new (): B; +} +interface B { + foo: T; +} +declare var B: BConstructor; + +var obj3: B | A; +if (obj3 instanceof B) { // narrowed to B. + obj3.foo = "str"; + obj3.foo = 1; + obj3.bar = "str"; +} + +var obj4: any; +if (obj4 instanceof B) { // can't type narrowing from any. + obj4.foo = "str"; + obj4.foo = 1; + obj4.bar = "str"; +} + +// has multiple constructor signature +interface CConstructor { + new (value: string): C1; + new (value: number): C2; +} +interface C1 { + foo: string; + bar1: number; +} +interface C2 { + foo: string; + bar2: number; +} +declare var C: CConstructor; + +var obj5: C1 | A; +if (obj5 instanceof C) { // narrowed to C1. + obj5.foo; + obj5.bar1; + obj5.bar2; +} + +var obj6: any; +if (obj6 instanceof C) { // can't type narrowing from any. + obj6.foo; + obj6.bar1; + obj6.bar2; +} + +// with object type literal +interface D { + foo: string; +} +declare var D: { new (): D; }; + +var obj7: D | string; +if (obj7 instanceof D) { // narrowed to D. + obj7.foo; + obj7.bar; +} + +var obj8: any; +if (obj8 instanceof D) { // can't type narrowing from any. + obj8.foo; + obj8.bar; +} + + +//// [typeGuardsWithInstanceOfByConstructorSignature.js] +var obj1; +if (obj1 instanceof A) { + obj1.foo; + obj1.bar; +} +var obj2; +if (obj2 instanceof A) { + obj2.foo; + obj2.bar; +} +var obj3; +if (obj3 instanceof B) { + obj3.foo = "str"; + obj3.foo = 1; + obj3.bar = "str"; +} +var obj4; +if (obj4 instanceof B) { + obj4.foo = "str"; + obj4.foo = 1; + obj4.bar = "str"; +} +var obj5; +if (obj5 instanceof C) { + obj5.foo; + obj5.bar1; + obj5.bar2; +} +var obj6; +if (obj6 instanceof C) { + obj6.foo; + obj6.bar1; + obj6.bar2; +} +var obj7; +if (obj7 instanceof D) { + obj7.foo; + obj7.bar; +} +var obj8; +if (obj8 instanceof D) { + obj8.foo; + obj8.bar; +} diff --git a/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts b/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts new file mode 100644 index 00000000000..b28d92e2c8e --- /dev/null +++ b/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts @@ -0,0 +1,89 @@ +interface AConstructor { + new (): A; +} +interface A { + foo: string; +} +declare var A: AConstructor; + +var obj1: A | string; +if (obj1 instanceof A) { // narrowed to A. + obj1.foo; + obj1.bar; +} + +var obj2: any; +if (obj2 instanceof A) { // can't type narrowing from any. + obj2.foo; + obj2.bar; +} + +// with generics +interface BConstructor { + new (): B; +} +interface B { + foo: T; +} +declare var B: BConstructor; + +var obj3: B | A; +if (obj3 instanceof B) { // narrowed to B. + obj3.foo = "str"; + obj3.foo = 1; + obj3.bar = "str"; +} + +var obj4: any; +if (obj4 instanceof B) { // can't type narrowing from any. + obj4.foo = "str"; + obj4.foo = 1; + obj4.bar = "str"; +} + +// has multiple constructor signature +interface CConstructor { + new (value: string): C1; + new (value: number): C2; +} +interface C1 { + foo: string; + bar1: number; +} +interface C2 { + foo: string; + bar2: number; +} +declare var C: CConstructor; + +var obj5: C1 | A; +if (obj5 instanceof C) { // narrowed to C1. + obj5.foo; + obj5.bar1; + obj5.bar2; +} + +var obj6: any; +if (obj6 instanceof C) { // can't type narrowing from any. + obj6.foo; + obj6.bar1; + obj6.bar2; +} + +// with object type literal +interface D { + foo: string; +} +declare var D: { new (): D; }; + +var obj7: D | string; +if (obj7 instanceof D) { // narrowed to D. + obj7.foo; + obj7.bar; +} + +var obj8: any; +if (obj8 instanceof D) { // can't type narrowing from any. + obj8.foo; + obj8.bar; +} From 05f51dc7814b724acb083de3946c1d73cce4b1b8 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 1 May 2015 14:44:06 -0700 Subject: [PATCH 02/31] Error when variable is circularly referenced in type annotation --- src/compiler/checker.ts | 19 +++++++++++++------ .../diagnosticInformationMap.generated.ts | 2 +- src/compiler/diagnosticMessages.json | 8 ++++---- 3 files changed, 18 insertions(+), 11 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 40a6b2e3f72..b0da5beb4be 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -2278,12 +2278,19 @@ module ts { } } else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - let diagnostic = (symbol.valueDeclaration).type ? - Diagnostics._0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation : - Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer; - error(symbol.valueDeclaration, diagnostic, symbolToString(symbol)); + if ((symbol.valueDeclaration).type) { + // Variable has type annotation that circularly references the variable itself + links.type = unknownType; + error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, + symbolToString(symbol)); + } + else { + // Variable has initializer that circularly references the variable itself + links.type = anyType; + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, + symbolToString(symbol)); + } } } return links.type; diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index b44d9379509..a29be2ec10e 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -365,6 +365,7 @@ module ts { An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." }, A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." }, A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -516,7 +517,6 @@ module ts { Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 7021, category: DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation." }, _0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 2ab6b8358eb..15307025c6f 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1447,6 +1447,10 @@ "category": "Error", "code": 2501 }, + "'{0}' is referenced directly or indirectly in its own type annotation.": { + "category": "Error", + "code": 2502 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", @@ -2055,10 +2059,6 @@ "category": "Error", "code": 7020 }, - "'{0}' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation.": { - "category": "Error", - "code": 7021 - }, "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer.": { "category": "Error", "code": 7022 From a133684b36a8ac4e7049548a662b380f5d54bb30 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 1 May 2015 15:03:52 -0700 Subject: [PATCH 03/31] Modifying test --- .../typeQueries/recursiveTypesWithTypeof.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts b/tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts index 7852f99dd9b..b39d9dd53a8 100644 --- a/tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts +++ b/tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts @@ -1,5 +1,4 @@ -// None of these declarations should have any errors! -// Using typeof directly, these should be any +// The following are errors because of circular references var c: typeof c; var c: any; var d: typeof e; @@ -7,7 +6,6 @@ var d: any; var e: typeof d; var e: any; -// In type arguments, these should be any interface Foo { } var f: Array; var f: any; @@ -16,6 +14,7 @@ var f2: any; var f3: Foo[]; var f3: any; +// None of these declarations should have any errors! // Truly recursive types var g: { x: typeof g; }; var g: typeof g.x; @@ -48,6 +47,6 @@ var hy2 = hy2.x[0]; interface Foo2 { } -// This one should be any because the first type argument is not contained inside a type literal +// This one should be an error because the first type argument is not contained inside a type literal var hy3: Foo2; var hy3: any; \ No newline at end of file From 8600fef2bd400fe70829792d6d81c788db0b56bf Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Fri, 1 May 2015 15:05:42 -0700 Subject: [PATCH 04/31] Accepting new baselines --- ...mplicitAnyFromCircularInference.errors.txt | 12 +- .../recursiveTypesWithTypeof.errors.txt | 73 +++++++ .../reference/recursiveTypesWithTypeof.js | 35 ++- .../recursiveTypesWithTypeof.symbols | 187 ---------------- .../reference/recursiveTypesWithTypeof.types | 201 ------------------ .../typeofANonExportedType.errors.txt | 5 +- .../reference/typeofAnExportedType.errors.txt | 5 +- 7 files changed, 104 insertions(+), 414 deletions(-) create mode 100644 tests/baselines/reference/recursiveTypesWithTypeof.errors.txt delete mode 100644 tests/baselines/reference/recursiveTypesWithTypeof.symbols delete mode 100644 tests/baselines/reference/recursiveTypesWithTypeof.types diff --git a/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt b/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt index 18292c635e6..deb7fc137b2 100644 --- a/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt +++ b/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt @@ -1,6 +1,6 @@ -tests/cases/compiler/implicitAnyFromCircularInference.ts(3,5): error TS7021: 'a' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation. -tests/cases/compiler/implicitAnyFromCircularInference.ts(7,5): error TS7021: 'c' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation. -tests/cases/compiler/implicitAnyFromCircularInference.ts(10,5): error TS7021: 'd' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/implicitAnyFromCircularInference.ts(3,5): error TS2502: 'a' is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/implicitAnyFromCircularInference.ts(7,5): error TS2502: 'c' is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/implicitAnyFromCircularInference.ts(10,5): error TS2502: 'd' is referenced directly or indirectly in its own type annotation. tests/cases/compiler/implicitAnyFromCircularInference.ts(15,10): error TS7023: 'g' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. tests/cases/compiler/implicitAnyFromCircularInference.ts(18,10): error TS7024: Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. tests/cases/compiler/implicitAnyFromCircularInference.ts(23,10): error TS7024: Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. @@ -14,18 +14,18 @@ tests/cases/compiler/implicitAnyFromCircularInference.ts(46,5): error TS7023: 'x // Error expected var a: typeof a; ~ -!!! error TS7021: 'a' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation. +!!! error TS2502: 'a' is referenced directly or indirectly in its own type annotation. // Error expected on b or c var b: typeof c; var c: typeof b; ~ -!!! error TS7021: 'c' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation. +!!! error TS2502: 'c' is referenced directly or indirectly in its own type annotation. // Error expected var d: Array; ~ -!!! error TS7021: 'd' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation. +!!! error TS2502: 'd' is referenced directly or indirectly in its own type annotation. function f() { return f; } diff --git a/tests/baselines/reference/recursiveTypesWithTypeof.errors.txt b/tests/baselines/reference/recursiveTypesWithTypeof.errors.txt new file mode 100644 index 00000000000..77bb58bfe0a --- /dev/null +++ b/tests/baselines/reference/recursiveTypesWithTypeof.errors.txt @@ -0,0 +1,73 @@ +tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(2,5): error TS2502: 'c' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(6,5): error TS2502: 'e' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(10,5): error TS2502: 'f' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(12,5): error TS2502: 'f2' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(14,5): error TS2502: 'f3' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(51,5): error TS2502: 'hy3' is referenced directly or indirectly in its own type annotation. + + +==== tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts (6 errors) ==== + // The following are errors because of circular references + var c: typeof c; + ~ +!!! error TS2502: 'c' is referenced directly or indirectly in its own type annotation. + var c: any; + var d: typeof e; + var d: any; + var e: typeof d; + ~ +!!! error TS2502: 'e' is referenced directly or indirectly in its own type annotation. + var e: any; + + interface Foo { } + var f: Array; + ~ +!!! error TS2502: 'f' is referenced directly or indirectly in its own type annotation. + var f: any; + var f2: Foo; + ~~ +!!! error TS2502: 'f2' is referenced directly or indirectly in its own type annotation. + var f2: any; + var f3: Foo[]; + ~~ +!!! error TS2502: 'f3' is referenced directly or indirectly in its own type annotation. + var f3: any; + + // None of these declarations should have any errors! + // Truly recursive types + var g: { x: typeof g; }; + var g: typeof g.x; + var h: () => typeof h; + var h = h(); + var i: (x: typeof i) => typeof x; + var i = i(i); + var j: (x: T) => T; + var j = j(j); + + // Same as h, i, j with construct signatures + var h2: new () => typeof h2; + var h2 = new h2(); + var i2: new (x: typeof i2) => typeof x; + var i2 = new i2(i2); + var j2: new (x: T) => T; + var j2 = new j2(j2); + + // Indexers + var k: { [n: number]: typeof k;[s: string]: typeof k }; + var k = k[0]; + var k = k['']; + + // Hybrid - contains type literals as well as type arguments + // These two are recursive + var hy1: { x: typeof hy1 }[]; + var hy1 = hy1[0].x; + var hy2: { x: Array }; + var hy2 = hy2.x[0]; + + interface Foo2 { } + + // This one should be an error because the first type argument is not contained inside a type literal + var hy3: Foo2; + ~~~ +!!! error TS2502: 'hy3' is referenced directly or indirectly in its own type annotation. + var hy3: any; \ No newline at end of file diff --git a/tests/baselines/reference/recursiveTypesWithTypeof.js b/tests/baselines/reference/recursiveTypesWithTypeof.js index 36c13405b0b..9fffd5b2604 100644 --- a/tests/baselines/reference/recursiveTypesWithTypeof.js +++ b/tests/baselines/reference/recursiveTypesWithTypeof.js @@ -1,6 +1,5 @@ //// [recursiveTypesWithTypeof.ts] -// None of these declarations should have any errors! -// Using typeof directly, these should be any +// The following are errors because of circular references var c: typeof c; var c: any; var d: typeof e; @@ -8,7 +7,6 @@ var d: any; var e: typeof d; var e: any; -// In type arguments, these should be any interface Foo { } var f: Array; var f: any; @@ -17,6 +15,7 @@ var f2: any; var f3: Foo[]; var f3: any; +// None of these declarations should have any errors! // Truly recursive types var g: { x: typeof g; }; var g: typeof g.x; @@ -49,25 +48,25 @@ var hy2 = hy2.x[0]; interface Foo2 { } -// This one should be any because the first type argument is not contained inside a type literal +// This one should be an error because the first type argument is not contained inside a type literal var hy3: Foo2; var hy3: any; //// [recursiveTypesWithTypeof.js] +// The following are errors because of circular references +var c; +var c; +var d; +var d; +var e; +var e; +var f; +var f; +var f2; +var f2; +var f3; +var f3; // None of these declarations should have any errors! -// Using typeof directly, these should be any -var c; -var c; -var d; -var d; -var e; -var e; -var f; -var f; -var f2; -var f2; -var f3; -var f3; // Truly recursive types var g; var g; @@ -94,6 +93,6 @@ var hy1; var hy1 = hy1[0].x; var hy2; var hy2 = hy2.x[0]; -// This one should be any because the first type argument is not contained inside a type literal +// This one should be an error because the first type argument is not contained inside a type literal var hy3; var hy3; diff --git a/tests/baselines/reference/recursiveTypesWithTypeof.symbols b/tests/baselines/reference/recursiveTypesWithTypeof.symbols deleted file mode 100644 index ae1a311bdf6..00000000000 --- a/tests/baselines/reference/recursiveTypesWithTypeof.symbols +++ /dev/null @@ -1,187 +0,0 @@ -=== tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts === -// None of these declarations should have any errors! -// Using typeof directly, these should be any -var c: typeof c; ->c : Symbol(c, Decl(recursiveTypesWithTypeof.ts, 2, 3), Decl(recursiveTypesWithTypeof.ts, 3, 3)) ->c : Symbol(c, Decl(recursiveTypesWithTypeof.ts, 2, 3), Decl(recursiveTypesWithTypeof.ts, 3, 3)) - -var c: any; ->c : Symbol(c, Decl(recursiveTypesWithTypeof.ts, 2, 3), Decl(recursiveTypesWithTypeof.ts, 3, 3)) - -var d: typeof e; ->d : Symbol(d, Decl(recursiveTypesWithTypeof.ts, 4, 3), Decl(recursiveTypesWithTypeof.ts, 5, 3)) ->e : Symbol(e, Decl(recursiveTypesWithTypeof.ts, 6, 3), Decl(recursiveTypesWithTypeof.ts, 7, 3)) - -var d: any; ->d : Symbol(d, Decl(recursiveTypesWithTypeof.ts, 4, 3), Decl(recursiveTypesWithTypeof.ts, 5, 3)) - -var e: typeof d; ->e : Symbol(e, Decl(recursiveTypesWithTypeof.ts, 6, 3), Decl(recursiveTypesWithTypeof.ts, 7, 3)) ->d : Symbol(d, Decl(recursiveTypesWithTypeof.ts, 4, 3), Decl(recursiveTypesWithTypeof.ts, 5, 3)) - -var e: any; ->e : Symbol(e, Decl(recursiveTypesWithTypeof.ts, 6, 3), Decl(recursiveTypesWithTypeof.ts, 7, 3)) - -// In type arguments, these should be any -interface Foo { } ->Foo : Symbol(Foo, Decl(recursiveTypesWithTypeof.ts, 7, 11)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 10, 14)) - -var f: Array; ->f : Symbol(f, Decl(recursiveTypesWithTypeof.ts, 11, 3), Decl(recursiveTypesWithTypeof.ts, 12, 3)) ->Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) ->f : Symbol(f, Decl(recursiveTypesWithTypeof.ts, 11, 3), Decl(recursiveTypesWithTypeof.ts, 12, 3)) - -var f: any; ->f : Symbol(f, Decl(recursiveTypesWithTypeof.ts, 11, 3), Decl(recursiveTypesWithTypeof.ts, 12, 3)) - -var f2: Foo; ->f2 : Symbol(f2, Decl(recursiveTypesWithTypeof.ts, 13, 3), Decl(recursiveTypesWithTypeof.ts, 14, 3)) ->Foo : Symbol(Foo, Decl(recursiveTypesWithTypeof.ts, 7, 11)) ->f2 : Symbol(f2, Decl(recursiveTypesWithTypeof.ts, 13, 3), Decl(recursiveTypesWithTypeof.ts, 14, 3)) - -var f2: any; ->f2 : Symbol(f2, Decl(recursiveTypesWithTypeof.ts, 13, 3), Decl(recursiveTypesWithTypeof.ts, 14, 3)) - -var f3: Foo[]; ->f3 : Symbol(f3, Decl(recursiveTypesWithTypeof.ts, 15, 3), Decl(recursiveTypesWithTypeof.ts, 16, 3)) ->Foo : Symbol(Foo, Decl(recursiveTypesWithTypeof.ts, 7, 11)) ->f3 : Symbol(f3, Decl(recursiveTypesWithTypeof.ts, 15, 3), Decl(recursiveTypesWithTypeof.ts, 16, 3)) - -var f3: any; ->f3 : Symbol(f3, Decl(recursiveTypesWithTypeof.ts, 15, 3), Decl(recursiveTypesWithTypeof.ts, 16, 3)) - -// Truly recursive types -var g: { x: typeof g; }; ->g : Symbol(g, Decl(recursiveTypesWithTypeof.ts, 19, 3), Decl(recursiveTypesWithTypeof.ts, 20, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 19, 8)) ->g : Symbol(g, Decl(recursiveTypesWithTypeof.ts, 19, 3), Decl(recursiveTypesWithTypeof.ts, 20, 3)) - -var g: typeof g.x; ->g : Symbol(g, Decl(recursiveTypesWithTypeof.ts, 19, 3), Decl(recursiveTypesWithTypeof.ts, 20, 3)) ->g.x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 19, 8)) ->g : Symbol(g, Decl(recursiveTypesWithTypeof.ts, 19, 3), Decl(recursiveTypesWithTypeof.ts, 20, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 19, 8)) - -var h: () => typeof h; ->h : Symbol(h, Decl(recursiveTypesWithTypeof.ts, 21, 3), Decl(recursiveTypesWithTypeof.ts, 22, 3)) ->h : Symbol(h, Decl(recursiveTypesWithTypeof.ts, 21, 3), Decl(recursiveTypesWithTypeof.ts, 22, 3)) - -var h = h(); ->h : Symbol(h, Decl(recursiveTypesWithTypeof.ts, 21, 3), Decl(recursiveTypesWithTypeof.ts, 22, 3)) ->h : Symbol(h, Decl(recursiveTypesWithTypeof.ts, 21, 3), Decl(recursiveTypesWithTypeof.ts, 22, 3)) - -var i: (x: typeof i) => typeof x; ->i : Symbol(i, Decl(recursiveTypesWithTypeof.ts, 23, 3), Decl(recursiveTypesWithTypeof.ts, 24, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 23, 8)) ->i : Symbol(i, Decl(recursiveTypesWithTypeof.ts, 23, 3), Decl(recursiveTypesWithTypeof.ts, 24, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 23, 8)) - -var i = i(i); ->i : Symbol(i, Decl(recursiveTypesWithTypeof.ts, 23, 3), Decl(recursiveTypesWithTypeof.ts, 24, 3)) ->i : Symbol(i, Decl(recursiveTypesWithTypeof.ts, 23, 3), Decl(recursiveTypesWithTypeof.ts, 24, 3)) ->i : Symbol(i, Decl(recursiveTypesWithTypeof.ts, 23, 3), Decl(recursiveTypesWithTypeof.ts, 24, 3)) - -var j: (x: T) => T; ->j : Symbol(j, Decl(recursiveTypesWithTypeof.ts, 25, 3), Decl(recursiveTypesWithTypeof.ts, 26, 3)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 25, 8)) ->j : Symbol(j, Decl(recursiveTypesWithTypeof.ts, 25, 3), Decl(recursiveTypesWithTypeof.ts, 26, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 25, 28)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 25, 8)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 25, 8)) - -var j = j(j); ->j : Symbol(j, Decl(recursiveTypesWithTypeof.ts, 25, 3), Decl(recursiveTypesWithTypeof.ts, 26, 3)) ->j : Symbol(j, Decl(recursiveTypesWithTypeof.ts, 25, 3), Decl(recursiveTypesWithTypeof.ts, 26, 3)) ->j : Symbol(j, Decl(recursiveTypesWithTypeof.ts, 25, 3), Decl(recursiveTypesWithTypeof.ts, 26, 3)) - -// Same as h, i, j with construct signatures -var h2: new () => typeof h2; ->h2 : Symbol(h2, Decl(recursiveTypesWithTypeof.ts, 29, 3), Decl(recursiveTypesWithTypeof.ts, 30, 3)) ->h2 : Symbol(h2, Decl(recursiveTypesWithTypeof.ts, 29, 3), Decl(recursiveTypesWithTypeof.ts, 30, 3)) - -var h2 = new h2(); ->h2 : Symbol(h2, Decl(recursiveTypesWithTypeof.ts, 29, 3), Decl(recursiveTypesWithTypeof.ts, 30, 3)) ->h2 : Symbol(h2, Decl(recursiveTypesWithTypeof.ts, 29, 3), Decl(recursiveTypesWithTypeof.ts, 30, 3)) - -var i2: new (x: typeof i2) => typeof x; ->i2 : Symbol(i2, Decl(recursiveTypesWithTypeof.ts, 31, 3), Decl(recursiveTypesWithTypeof.ts, 32, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 31, 13)) ->i2 : Symbol(i2, Decl(recursiveTypesWithTypeof.ts, 31, 3), Decl(recursiveTypesWithTypeof.ts, 32, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 31, 13)) - -var i2 = new i2(i2); ->i2 : Symbol(i2, Decl(recursiveTypesWithTypeof.ts, 31, 3), Decl(recursiveTypesWithTypeof.ts, 32, 3)) ->i2 : Symbol(i2, Decl(recursiveTypesWithTypeof.ts, 31, 3), Decl(recursiveTypesWithTypeof.ts, 32, 3)) ->i2 : Symbol(i2, Decl(recursiveTypesWithTypeof.ts, 31, 3), Decl(recursiveTypesWithTypeof.ts, 32, 3)) - -var j2: new (x: T) => T; ->j2 : Symbol(j2, Decl(recursiveTypesWithTypeof.ts, 33, 3), Decl(recursiveTypesWithTypeof.ts, 34, 3)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 33, 13)) ->j2 : Symbol(j2, Decl(recursiveTypesWithTypeof.ts, 33, 3), Decl(recursiveTypesWithTypeof.ts, 34, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 33, 34)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 33, 13)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 33, 13)) - -var j2 = new j2(j2); ->j2 : Symbol(j2, Decl(recursiveTypesWithTypeof.ts, 33, 3), Decl(recursiveTypesWithTypeof.ts, 34, 3)) ->j2 : Symbol(j2, Decl(recursiveTypesWithTypeof.ts, 33, 3), Decl(recursiveTypesWithTypeof.ts, 34, 3)) ->j2 : Symbol(j2, Decl(recursiveTypesWithTypeof.ts, 33, 3), Decl(recursiveTypesWithTypeof.ts, 34, 3)) - -// Indexers -var k: { [n: number]: typeof k;[s: string]: typeof k }; ->k : Symbol(k, Decl(recursiveTypesWithTypeof.ts, 37, 3), Decl(recursiveTypesWithTypeof.ts, 38, 3), Decl(recursiveTypesWithTypeof.ts, 39, 3)) ->n : Symbol(n, Decl(recursiveTypesWithTypeof.ts, 37, 10)) ->k : Symbol(k, Decl(recursiveTypesWithTypeof.ts, 37, 3), Decl(recursiveTypesWithTypeof.ts, 38, 3), Decl(recursiveTypesWithTypeof.ts, 39, 3)) ->s : Symbol(s, Decl(recursiveTypesWithTypeof.ts, 37, 32)) ->k : Symbol(k, Decl(recursiveTypesWithTypeof.ts, 37, 3), Decl(recursiveTypesWithTypeof.ts, 38, 3), Decl(recursiveTypesWithTypeof.ts, 39, 3)) - -var k = k[0]; ->k : Symbol(k, Decl(recursiveTypesWithTypeof.ts, 37, 3), Decl(recursiveTypesWithTypeof.ts, 38, 3), Decl(recursiveTypesWithTypeof.ts, 39, 3)) ->k : Symbol(k, Decl(recursiveTypesWithTypeof.ts, 37, 3), Decl(recursiveTypesWithTypeof.ts, 38, 3), Decl(recursiveTypesWithTypeof.ts, 39, 3)) - -var k = k['']; ->k : Symbol(k, Decl(recursiveTypesWithTypeof.ts, 37, 3), Decl(recursiveTypesWithTypeof.ts, 38, 3), Decl(recursiveTypesWithTypeof.ts, 39, 3)) ->k : Symbol(k, Decl(recursiveTypesWithTypeof.ts, 37, 3), Decl(recursiveTypesWithTypeof.ts, 38, 3), Decl(recursiveTypesWithTypeof.ts, 39, 3)) - -// Hybrid - contains type literals as well as type arguments -// These two are recursive -var hy1: { x: typeof hy1 }[]; ->hy1 : Symbol(hy1, Decl(recursiveTypesWithTypeof.ts, 43, 3), Decl(recursiveTypesWithTypeof.ts, 44, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 43, 10)) ->hy1 : Symbol(hy1, Decl(recursiveTypesWithTypeof.ts, 43, 3), Decl(recursiveTypesWithTypeof.ts, 44, 3)) - -var hy1 = hy1[0].x; ->hy1 : Symbol(hy1, Decl(recursiveTypesWithTypeof.ts, 43, 3), Decl(recursiveTypesWithTypeof.ts, 44, 3)) ->hy1[0].x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 43, 10)) ->hy1 : Symbol(hy1, Decl(recursiveTypesWithTypeof.ts, 43, 3), Decl(recursiveTypesWithTypeof.ts, 44, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 43, 10)) - -var hy2: { x: Array }; ->hy2 : Symbol(hy2, Decl(recursiveTypesWithTypeof.ts, 45, 3), Decl(recursiveTypesWithTypeof.ts, 46, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 45, 10)) ->Array : Symbol(Array, Decl(lib.d.ts, 1000, 23), Decl(lib.d.ts, 1171, 11)) ->hy2 : Symbol(hy2, Decl(recursiveTypesWithTypeof.ts, 45, 3), Decl(recursiveTypesWithTypeof.ts, 46, 3)) - -var hy2 = hy2.x[0]; ->hy2 : Symbol(hy2, Decl(recursiveTypesWithTypeof.ts, 45, 3), Decl(recursiveTypesWithTypeof.ts, 46, 3)) ->hy2.x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 45, 10)) ->hy2 : Symbol(hy2, Decl(recursiveTypesWithTypeof.ts, 45, 3), Decl(recursiveTypesWithTypeof.ts, 46, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 45, 10)) - -interface Foo2 { } ->Foo2 : Symbol(Foo2, Decl(recursiveTypesWithTypeof.ts, 46, 19)) ->T : Symbol(T, Decl(recursiveTypesWithTypeof.ts, 48, 15)) ->U : Symbol(U, Decl(recursiveTypesWithTypeof.ts, 48, 17)) - -// This one should be any because the first type argument is not contained inside a type literal -var hy3: Foo2; ->hy3 : Symbol(hy3, Decl(recursiveTypesWithTypeof.ts, 51, 3), Decl(recursiveTypesWithTypeof.ts, 52, 3)) ->Foo2 : Symbol(Foo2, Decl(recursiveTypesWithTypeof.ts, 46, 19)) ->hy3 : Symbol(hy3, Decl(recursiveTypesWithTypeof.ts, 51, 3), Decl(recursiveTypesWithTypeof.ts, 52, 3)) ->x : Symbol(x, Decl(recursiveTypesWithTypeof.ts, 51, 27)) ->hy3 : Symbol(hy3, Decl(recursiveTypesWithTypeof.ts, 51, 3), Decl(recursiveTypesWithTypeof.ts, 52, 3)) - -var hy3: any; ->hy3 : Symbol(hy3, Decl(recursiveTypesWithTypeof.ts, 51, 3), Decl(recursiveTypesWithTypeof.ts, 52, 3)) - diff --git a/tests/baselines/reference/recursiveTypesWithTypeof.types b/tests/baselines/reference/recursiveTypesWithTypeof.types deleted file mode 100644 index 864c136743d..00000000000 --- a/tests/baselines/reference/recursiveTypesWithTypeof.types +++ /dev/null @@ -1,201 +0,0 @@ -=== tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts === -// None of these declarations should have any errors! -// Using typeof directly, these should be any -var c: typeof c; ->c : any ->c : any - -var c: any; ->c : any - -var d: typeof e; ->d : any ->e : any - -var d: any; ->d : any - -var e: typeof d; ->e : any ->d : any - -var e: any; ->e : any - -// In type arguments, these should be any -interface Foo { } ->Foo : Foo ->T : T - -var f: Array; ->f : any ->Array : T[] ->f : any - -var f: any; ->f : any - -var f2: Foo; ->f2 : any ->Foo : Foo ->f2 : any - -var f2: any; ->f2 : any - -var f3: Foo[]; ->f3 : any ->Foo : Foo ->f3 : any - -var f3: any; ->f3 : any - -// Truly recursive types -var g: { x: typeof g; }; ->g : { x: any; } ->x : { x: any; } ->g : { x: any; } - -var g: typeof g.x; ->g : { x: any; } ->g.x : { x: any; } ->g : { x: any; } ->x : { x: any; } - -var h: () => typeof h; ->h : () => any ->h : () => any - -var h = h(); ->h : () => any ->h() : () => any ->h : () => any - -var i: (x: typeof i) => typeof x; ->i : (x: any) => any ->x : (x: any) => any ->i : (x: any) => any ->x : (x: any) => any - -var i = i(i); ->i : (x: any) => any ->i(i) : (x: any) => any ->i : (x: any) => any ->i : (x: any) => any - -var j: (x: T) => T; ->j : (x: T) => T ->T : T ->j : (x: T) => T ->x : T ->T : T ->T : T - -var j = j(j); ->j : (x: T) => T ->j(j) : (x: T) => T ->j : (x: T) => T ->j : (x: T) => T - -// Same as h, i, j with construct signatures -var h2: new () => typeof h2; ->h2 : new () => any ->h2 : new () => any - -var h2 = new h2(); ->h2 : new () => any ->new h2() : new () => any ->h2 : new () => any - -var i2: new (x: typeof i2) => typeof x; ->i2 : new (x: any) => any ->x : new (x: any) => any ->i2 : new (x: any) => any ->x : new (x: any) => any - -var i2 = new i2(i2); ->i2 : new (x: any) => any ->new i2(i2) : new (x: any) => any ->i2 : new (x: any) => any ->i2 : new (x: any) => any - -var j2: new (x: T) => T; ->j2 : new (x: T) => T ->T : T ->j2 : new (x: T) => T ->x : T ->T : T ->T : T - -var j2 = new j2(j2); ->j2 : new (x: T) => T ->new j2(j2) : new (x: T) => T ->j2 : new (x: T) => T ->j2 : new (x: T) => T - -// Indexers -var k: { [n: number]: typeof k;[s: string]: typeof k }; ->k : { [s: string]: any; [n: number]: any; } ->n : number ->k : { [s: string]: any; [n: number]: any; } ->s : string ->k : { [s: string]: any; [n: number]: any; } - -var k = k[0]; ->k : { [s: string]: any; [n: number]: any; } ->k[0] : { [s: string]: any; [n: number]: any; } ->k : { [s: string]: any; [n: number]: any; } ->0 : number - -var k = k['']; ->k : { [s: string]: any; [n: number]: any; } ->k[''] : { [s: string]: any; [n: number]: any; } ->k : { [s: string]: any; [n: number]: any; } ->'' : string - -// Hybrid - contains type literals as well as type arguments -// These two are recursive -var hy1: { x: typeof hy1 }[]; ->hy1 : { x: any[]; }[] ->x : { x: any[]; }[] ->hy1 : { x: any[]; }[] - -var hy1 = hy1[0].x; ->hy1 : { x: any[]; }[] ->hy1[0].x : { x: any[]; }[] ->hy1[0] : { x: any[]; } ->hy1 : { x: any[]; }[] ->0 : number ->x : { x: any[]; }[] - -var hy2: { x: Array }; ->hy2 : { x: any[]; } ->x : { x: any[]; }[] ->Array : T[] ->hy2 : { x: any[]; } - -var hy2 = hy2.x[0]; ->hy2 : { x: any[]; } ->hy2.x[0] : { x: any[]; } ->hy2.x : { x: any[]; }[] ->hy2 : { x: any[]; } ->x : { x: any[]; }[] ->0 : number - -interface Foo2 { } ->Foo2 : Foo2 ->T : T ->U : U - -// This one should be any because the first type argument is not contained inside a type literal -var hy3: Foo2; ->hy3 : any ->Foo2 : Foo2 ->hy3 : any ->x : any ->hy3 : any - -var hy3: any; ->hy3 : any - diff --git a/tests/baselines/reference/typeofANonExportedType.errors.txt b/tests/baselines/reference/typeofANonExportedType.errors.txt index b6b165cdd4f..d07468f62e1 100644 --- a/tests/baselines/reference/typeofANonExportedType.errors.txt +++ b/tests/baselines/reference/typeofANonExportedType.errors.txt @@ -1,7 +1,8 @@ tests/cases/conformance/types/specifyingTypes/typeQueries/typeofANonExportedType.ts(2,1): error TS1148: Cannot compile modules unless the '--module' flag is provided. +tests/cases/conformance/types/specifyingTypes/typeQueries/typeofANonExportedType.ts(42,12): error TS2502: 'r12' is referenced directly or indirectly in its own type annotation. -==== tests/cases/conformance/types/specifyingTypes/typeQueries/typeofANonExportedType.ts (1 errors) ==== +==== tests/cases/conformance/types/specifyingTypes/typeQueries/typeofANonExportedType.ts (2 errors) ==== var x = 1; export var r1: typeof x; ~~~~~~~~~~~~~~~~~~~~~~~~ @@ -46,6 +47,8 @@ tests/cases/conformance/types/specifyingTypes/typeQueries/typeofANonExportedType export var r11: typeof E.A; export var r12: typeof r12; + ~~~ +!!! error TS2502: 'r12' is referenced directly or indirectly in its own type annotation. function foo() { } module foo { diff --git a/tests/baselines/reference/typeofAnExportedType.errors.txt b/tests/baselines/reference/typeofAnExportedType.errors.txt index 9f64f697c08..cb6d8c68887 100644 --- a/tests/baselines/reference/typeofAnExportedType.errors.txt +++ b/tests/baselines/reference/typeofAnExportedType.errors.txt @@ -1,7 +1,8 @@ tests/cases/conformance/types/specifyingTypes/typeQueries/typeofAnExportedType.ts(1,1): error TS1148: Cannot compile modules unless the '--module' flag is provided. +tests/cases/conformance/types/specifyingTypes/typeQueries/typeofAnExportedType.ts(42,12): error TS2502: 'r12' is referenced directly or indirectly in its own type annotation. -==== tests/cases/conformance/types/specifyingTypes/typeQueries/typeofAnExportedType.ts (1 errors) ==== +==== tests/cases/conformance/types/specifyingTypes/typeQueries/typeofAnExportedType.ts (2 errors) ==== export var x = 1; ~~~~~~~~~~~~~~~~~ !!! error TS1148: Cannot compile modules unless the '--module' flag is provided. @@ -46,6 +47,8 @@ tests/cases/conformance/types/specifyingTypes/typeQueries/typeofAnExportedType.t export var r11: typeof E.A; export var r12: typeof r12; + ~~~ +!!! error TS2502: 'r12' is referenced directly or indirectly in its own type annotation. export function foo() { } export module foo { From ab10d509f5368137af5c50e532616e1d0fb9e45a Mon Sep 17 00:00:00 2001 From: vvakame Date: Sat, 2 May 2015 15:27:06 +0900 Subject: [PATCH 05/31] support instantiate signature, it has type parameters. --- src/compiler/checker.ts | 20 +-- ...nstanceOfByConstructorSignature.errors.txt | 137 ++++++++++++++-- ...rdsWithInstanceOfByConstructorSignature.js | 151 +++++++++++++++++- ...rdsWithInstanceOfByConstructorSignature.ts | 107 ++++++++++++- 4 files changed, 380 insertions(+), 35 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 36f9bbb654b..c864a8aa76a 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5365,25 +5365,25 @@ module ts { } } // Target type is type of constructor signiture - let constructorSignitures: Signature[]; + let constructSignitures: Signature[]; if (rightType.flags & TypeFlags.Interface) { - constructorSignitures = (rightType).declaredConstructSignatures; + constructSignitures = (rightType).declaredConstructSignatures; } if (rightType.flags & TypeFlags.Anonymous) { - constructorSignitures = (rightType).constructSignatures; + constructSignitures = (rightType).constructSignatures; } - if (constructorSignitures) { - let constructorType = getUnionType(map(constructorSignitures, constructorSignature => { - if (constructorSignature.typeParameters && constructorSignature.typeParameters.length !== 0) { - // TODO convert type parameters to any or empty object types. e.g. Sample -> Sample or Sample<{}>. + if (constructSignitures) { + let instanceType = getUnionType(map(constructSignitures, constructSignature => { + if (constructSignature.typeParameters && constructSignature.typeParameters.length !== 0) { + constructSignature = instantiateSignature(constructSignature, createTypeMapper(constructSignature.typeParameters, map(constructSignature.typeParameters, _ => anyType)), true) } - return constructorSignature.resolvedReturnType; + return constructSignature.resolvedReturnType; })); // Pickup type from union types if (type.flags & TypeFlags.Union) { - return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, constructorType))); + return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, instanceType))); } - return constructorType; + return instanceType; } return type; } diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt index c7146541705..1816ef77fc2 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt @@ -1,12 +1,16 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(12,10): error TS2339: Property 'bar' does not exist on type 'A'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(32,10): error TS2339: Property 'foo' does not exist on type '{}'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(33,10): error TS2339: Property 'foo' does not exist on type '{}'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(34,10): error TS2339: Property 'bar' does not exist on type '{}'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(33,5): error TS2322: Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(34,10): error TS2339: Property 'bar' does not exist on type 'B'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(63,10): error TS2339: Property 'bar2' does not exist on type 'C1'. tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(82,10): error TS2339: Property 'bar' does not exist on type 'D'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(109,10): error TS2339: Property 'bar2' does not exist on type 'E1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(131,11): error TS2339: Property 'foo' does not exist on type 'string | F'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(132,11): error TS2339: Property 'bar' does not exist on type 'string | F'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(157,11): error TS2339: Property 'foo2' does not exist on type 'G1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(179,11): error TS2339: Property 'bar' does not exist on type 'H'. -==== tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts (6 errors) ==== +==== tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts (10 errors) ==== interface AConstructor { new (): A; } @@ -29,7 +33,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj2.bar; } - // with generics + // a construct signature with generics interface BConstructor { new (): B; } @@ -38,17 +42,15 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru } declare var B: BConstructor; - var obj3: B | A; - if (obj3 instanceof B) { // narrowed to B. - obj3.foo = "str"; - ~~~ -!!! error TS2339: Property 'foo' does not exist on type '{}'. + var obj3: B | string; + if (obj3 instanceof B) { // narrowed to B. obj3.foo = 1; - ~~~ -!!! error TS2339: Property 'foo' does not exist on type '{}'. + obj3.foo = "str"; + ~~~~~~~~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. obj3.bar = "str"; ~~~ -!!! error TS2339: Property 'bar' does not exist on type '{}'. +!!! error TS2339: Property 'bar' does not exist on type 'B'. } var obj4: any; @@ -58,7 +60,7 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj4.bar = "str"; } - // has multiple constructor signature + // has multiple construct signature interface CConstructor { new (value: string): C1; new (value: number): C2; @@ -108,4 +110,111 @@ tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstru obj8.foo; obj8.bar; } + + // a construct signature that returns a union type + interface EConstructor { + new (): E1 | E2; + } + interface E1 { + foo: string; + bar1: number; + } + interface E2 { + foo: string; + bar2: number; + } + declare var E: EConstructor; + + var obj9: E1 | A; + if (obj9 instanceof E) { // narrowed to E1. + obj9.foo; + obj9.bar1; + obj9.bar2; + ~~~~ +!!! error TS2339: Property 'bar2' does not exist on type 'E1'. + } + + var obj10: any; + if (obj10 instanceof E) { // can't type narrowing from any. + obj10.foo; + obj10.bar1; + obj10.bar2; + } + + // a construct signature that returns any + interface FConstructor { + new (): any; + } + interface F { + foo: string; + bar: number; + } + declare var F: FConstructor; + + var obj11: F | string; + if (obj11 instanceof F) { // can't type narrowing, construct signiture returns any. + obj11.foo; + ~~~ +!!! error TS2339: Property 'foo' does not exist on type 'string | F'. + obj11.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'string | F'. + } + + var obj12: any; + if (obj12 instanceof F) { // can't type narrowing from any. + obj12.foo; + obj12.bar; + } + + // a type with a prototype, it overrides the construct signiture + interface GConstructor { + prototype: G1; // high priority + new (): G2; // low priority + } + interface G1 { + foo1: number; + } + interface G2 { + foo2: boolean; + } + declare var G: GConstructor; + + var obj13: G1 | G2; + if (obj13 instanceof G) { // narrowed to G1. G1 is return type of prototype property. + obj13.foo1; + obj13.foo2; + ~~~~ +!!! error TS2339: Property 'foo2' does not exist on type 'G1'. + } + + var obj14: any; + if (obj14 instanceof G) { // can't type narrowing from any. + obj14.foo1; + obj14.foo2; + } + + // a type with a prototype that has any type + interface HConstructor { + prototype: any; // high priority, but any type is ignored. interface has implicit `prototype: any`. + new (): H; // low priority + } + interface H { + foo: number; + } + declare var H: HConstructor; + + var obj15: H | string; + if (obj15 instanceof H) { // narrowed to H. + obj15.foo; + obj15.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'H'. + } + + var obj16: any; + if (obj16 instanceof H) { // can't type narrowing from any. + obj16.foo1; + obj16.foo2; + } \ No newline at end of file diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js index c795126b0ff..395a5e96e05 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js @@ -19,7 +19,7 @@ if (obj2 instanceof A) { // can't type narrowing from any. obj2.bar; } -// with generics +// a construct signature with generics interface BConstructor { new (): B; } @@ -28,10 +28,10 @@ interface B { } declare var B: BConstructor; -var obj3: B | A; -if (obj3 instanceof B) { // narrowed to B. - obj3.foo = "str"; +var obj3: B | string; +if (obj3 instanceof B) { // narrowed to B. obj3.foo = 1; + obj3.foo = "str"; obj3.bar = "str"; } @@ -42,7 +42,7 @@ if (obj4 instanceof B) { // can't type narrowing from any. obj4.bar = "str"; } -// has multiple constructor signature +// has multiple construct signature interface CConstructor { new (value: string): C1; new (value: number): C2; @@ -89,6 +89,103 @@ if (obj8 instanceof D) { // can't type narrowing from any. obj8.bar; } +// a construct signature that returns a union type +interface EConstructor { + new (): E1 | E2; +} +interface E1 { + foo: string; + bar1: number; +} +interface E2 { + foo: string; + bar2: number; +} +declare var E: EConstructor; + +var obj9: E1 | A; +if (obj9 instanceof E) { // narrowed to E1. + obj9.foo; + obj9.bar1; + obj9.bar2; +} + +var obj10: any; +if (obj10 instanceof E) { // can't type narrowing from any. + obj10.foo; + obj10.bar1; + obj10.bar2; +} + +// a construct signature that returns any +interface FConstructor { + new (): any; +} +interface F { + foo: string; + bar: number; +} +declare var F: FConstructor; + +var obj11: F | string; +if (obj11 instanceof F) { // can't type narrowing, construct signiture returns any. + obj11.foo; + obj11.bar; +} + +var obj12: any; +if (obj12 instanceof F) { // can't type narrowing from any. + obj12.foo; + obj12.bar; +} + +// a type with a prototype, it overrides the construct signiture +interface GConstructor { + prototype: G1; // high priority + new (): G2; // low priority +} +interface G1 { + foo1: number; +} +interface G2 { + foo2: boolean; +} +declare var G: GConstructor; + +var obj13: G1 | G2; +if (obj13 instanceof G) { // narrowed to G1. G1 is return type of prototype property. + obj13.foo1; + obj13.foo2; +} + +var obj14: any; +if (obj14 instanceof G) { // can't type narrowing from any. + obj14.foo1; + obj14.foo2; +} + +// a type with a prototype that has any type +interface HConstructor { + prototype: any; // high priority, but any type is ignored. interface has implicit `prototype: any`. + new (): H; // low priority +} +interface H { + foo: number; +} +declare var H: HConstructor; + +var obj15: H | string; +if (obj15 instanceof H) { // narrowed to H. + obj15.foo; + obj15.bar; +} + +var obj16: any; +if (obj16 instanceof H) { // can't type narrowing from any. + obj16.foo1; + obj16.foo2; +} + //// [typeGuardsWithInstanceOfByConstructorSignature.js] var obj1; @@ -103,8 +200,8 @@ if (obj2 instanceof A) { } var obj3; if (obj3 instanceof B) { - obj3.foo = "str"; obj3.foo = 1; + obj3.foo = "str"; obj3.bar = "str"; } var obj4; @@ -135,3 +232,45 @@ if (obj8 instanceof D) { obj8.foo; obj8.bar; } +var obj9; +if (obj9 instanceof E) { + obj9.foo; + obj9.bar1; + obj9.bar2; +} +var obj10; +if (obj10 instanceof E) { + obj10.foo; + obj10.bar1; + obj10.bar2; +} +var obj11; +if (obj11 instanceof F) { + obj11.foo; + obj11.bar; +} +var obj12; +if (obj12 instanceof F) { + obj12.foo; + obj12.bar; +} +var obj13; +if (obj13 instanceof G) { + obj13.foo1; + obj13.foo2; +} +var obj14; +if (obj14 instanceof G) { + obj14.foo1; + obj14.foo2; +} +var obj15; +if (obj15 instanceof H) { + obj15.foo; + obj15.bar; +} +var obj16; +if (obj16 instanceof H) { + obj16.foo1; + obj16.foo2; +} diff --git a/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts b/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts index b28d92e2c8e..c432ceb2bda 100644 --- a/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts +++ b/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts @@ -18,7 +18,7 @@ if (obj2 instanceof A) { // can't type narrowing from any. obj2.bar; } -// with generics +// a construct signature with generics interface BConstructor { new (): B; } @@ -27,10 +27,10 @@ interface B { } declare var B: BConstructor; -var obj3: B | A; -if (obj3 instanceof B) { // narrowed to B. - obj3.foo = "str"; +var obj3: B | string; +if (obj3 instanceof B) { // narrowed to B. obj3.foo = 1; + obj3.foo = "str"; obj3.bar = "str"; } @@ -41,7 +41,7 @@ if (obj4 instanceof B) { // can't type narrowing from any. obj4.bar = "str"; } -// has multiple constructor signature +// has multiple construct signature interface CConstructor { new (value: string): C1; new (value: number): C2; @@ -87,3 +87,100 @@ if (obj8 instanceof D) { // can't type narrowing from any. obj8.foo; obj8.bar; } + +// a construct signature that returns a union type +interface EConstructor { + new (): E1 | E2; +} +interface E1 { + foo: string; + bar1: number; +} +interface E2 { + foo: string; + bar2: number; +} +declare var E: EConstructor; + +var obj9: E1 | A; +if (obj9 instanceof E) { // narrowed to E1. + obj9.foo; + obj9.bar1; + obj9.bar2; +} + +var obj10: any; +if (obj10 instanceof E) { // can't type narrowing from any. + obj10.foo; + obj10.bar1; + obj10.bar2; +} + +// a construct signature that returns any +interface FConstructor { + new (): any; +} +interface F { + foo: string; + bar: number; +} +declare var F: FConstructor; + +var obj11: F | string; +if (obj11 instanceof F) { // can't type narrowing, construct signiture returns any. + obj11.foo; + obj11.bar; +} + +var obj12: any; +if (obj12 instanceof F) { // can't type narrowing from any. + obj12.foo; + obj12.bar; +} + +// a type with a prototype, it overrides the construct signiture +interface GConstructor { + prototype: G1; // high priority + new (): G2; // low priority +} +interface G1 { + foo1: number; +} +interface G2 { + foo2: boolean; +} +declare var G: GConstructor; + +var obj13: G1 | G2; +if (obj13 instanceof G) { // narrowed to G1. G1 is return type of prototype property. + obj13.foo1; + obj13.foo2; +} + +var obj14: any; +if (obj14 instanceof G) { // can't type narrowing from any. + obj14.foo1; + obj14.foo2; +} + +// a type with a prototype that has any type +interface HConstructor { + prototype: any; // high priority, but any type is ignored. interface has implicit `prototype: any`. + new (): H; // low priority +} +interface H { + foo: number; +} +declare var H: HConstructor; + +var obj15: H | string; +if (obj15 instanceof H) { // narrowed to H. + obj15.foo; + obj15.bar; +} + +var obj16: any; +if (obj16 instanceof H) { // can't type narrowing from any. + obj16.foo1; + obj16.foo2; +} From 2792614f8b8f16b54215a455c1c842cf1699d527 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 2 May 2015 16:35:58 -0700 Subject: [PATCH 06/31] Improved circularity detection for types --- src/compiler/checker.ts | 153 +++++++++++++++++++++++----------------- 1 file changed, 88 insertions(+), 65 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c3f996b9c6d..77120637ea7 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -93,7 +93,7 @@ module ts { let emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); let noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); - + let anySignature = createSignature(undefined, undefined, emptyArray, anyType, 0, false, false); let unknownSignature = createSignature(undefined, undefined, emptyArray, unknownType, 0, false, false); @@ -118,7 +118,7 @@ module ts { let getGlobalParameterDecoratorType: () => ObjectType; let getGlobalPropertyDecoratorType: () => ObjectType; let getGlobalMethodDecoratorType: () => ObjectType; - + let tupleTypes: Map = {}; let unionTypes: Map = {}; let stringLiteralTypes: Map = {}; @@ -126,6 +126,10 @@ module ts { let emitDecorate = false; let emitParam = false; + let resolutionTargets: Object[] = []; + let resolutionResults: boolean[] = []; + let resolutionCount = 0; + let mergedSymbols: Symbol[] = []; let symbolLinks: SymbolLinks[] = []; let nodeLinks: NodeLinks[] = []; @@ -1980,7 +1984,7 @@ module ts { } } - function collectLinkedAliases(node: Identifier): Node[]{ + function collectLinkedAliases(node: Identifier): Node[] { var exportSymbol: Symbol; if (node.parent && node.parent.kind === SyntaxKind.ExportAssignment) { exportSymbol = resolveName(node.parent, node.text, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace, Diagnostics.Cannot_find_name_0, node); @@ -2014,6 +2018,34 @@ module ts { } } + // Push an entry on the type resolution stack. If an entry with the given target is not already on the stack, + // a new entry with that target and an associated result value of true is pushed on the stack, and the value + // true is returned. Otherwise, a circularity has occurred and the result values of the existing entry and + // all entries pushed after it are changed to false, and the value false is returned. The target object has + // no significance other than to provide a unique identity for a particular type resolution result. + function pushTypeResolution(target: Object): boolean { + for (let i = 0; i < resolutionCount; i++) { + if (resolutionTargets[i] === target) { + do { + resolutionResults[i++] = false; + } + while (i < resolutionCount); + return false; + } + } + resolutionTargets[resolutionCount] = target; + resolutionResults[resolutionCount] = true; + resolutionCount++; + return true; + } + + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution(): boolean { + resolutionTargets[--resolutionCount] = undefined; + return resolutionResults[resolutionCount]; + } + function getRootDeclaration(node: Node): Node { while (node.kind === SyntaxKind.BindingElement) { node = node.parent.parent; @@ -2271,27 +2303,27 @@ module ts { return links.type = checkExpression((declaration).expression); } // Handle variable, parameter or property - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } let type = getWidenedTypeForVariableLikeDeclaration(declaration, /*reportErrors*/ true); - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - if ((symbol.valueDeclaration).type) { - // Variable has type annotation that circularly references the variable itself - links.type = unknownType; - error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, - symbolToString(symbol)); - } - else { - // Variable has initializer that circularly references the variable itself - links.type = anyType; - if (compilerOptions.noImplicitAny) { - error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, + if (!popTypeResolution()) { + if ((symbol.valueDeclaration).type) { + // Variable has type annotation that circularly references the variable itself + type = unknownType; + error(symbol.valueDeclaration, Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); } + else { + // Variable has initializer that circularly references the variable itself + type = anyType; + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, + symbolToString(symbol)); + } + } } + links.type = type; } return links.type; } @@ -2315,19 +2347,13 @@ module ts { function getTypeOfAccessors(symbol: Symbol): Type { let links = getSymbolLinks(symbol); - checkAndStoreTypeOfAccessors(symbol, links); - return links.type; - } - - function checkAndStoreTypeOfAccessors(symbol: Symbol, links?: SymbolLinks) { - links = links || getSymbolLinks(symbol); if (!links.type) { - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); let setter = getDeclarationOfKind(symbol, SyntaxKind.SetAccessor); - let type: Type; - // First try to see if the user specified a return type on the get-accessor. let getterReturnType = getAnnotatedAccessorType(getter); if (getterReturnType) { @@ -2349,23 +2375,20 @@ module ts { if (compilerOptions.noImplicitAny) { error(setter, Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_type_annotation, symbolToString(symbol)); } - type = anyType; } } } - - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); - error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + let getter = getDeclarationOfKind(symbol, SyntaxKind.GetAccessor); + error(getter, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } } + links.type = type; } + return links.type; } function getTypeOfFuncClassEnumModule(symbol: Symbol): Type { @@ -2458,7 +2481,7 @@ module ts { return result; } - function getBaseTypes(type: InterfaceType): ObjectType[]{ + function getBaseTypes(type: InterfaceType): ObjectType[] { let typeWithBaseTypes = type; if (!typeWithBaseTypes.baseTypes) { if (type.symbol.flags & SymbolFlags.Class) { @@ -2543,17 +2566,18 @@ module ts { function getDeclaredTypeOfTypeAlias(symbol: Symbol): Type { let links = getSymbolLinks(symbol); if (!links.declaredType) { - links.declaredType = resolvingType; + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(links)) { + return unknownType; + } let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); let type = getTypeFromTypeNode(declaration.type); - if (links.declaredType === resolvingType) { - links.declaredType = type; + if (!popTypeResolution()) { + type = unknownType; + error(declaration.name, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } - } - else if (links.declaredType === resolvingType) { - links.declaredType = unknownType; - let declaration = getDeclarationOfKind(symbol, SyntaxKind.TypeAliasDeclaration); - error(declaration.name, Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + links.declaredType = type; } return links.declaredType; } @@ -3157,7 +3181,9 @@ module ts { function getReturnTypeOfSignature(signature: Signature): Type { if (!signature.resolvedReturnType) { - signature.resolvedReturnType = resolvingType; + if (!pushTypeResolution(signature)) { + return unknownType; + } let type: Type; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); @@ -3168,21 +3194,19 @@ module ts { else { type = getReturnTypeFromBody(signature.declaration); } - if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = type; - } - } - else if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = anyType; - if (compilerOptions.noImplicitAny) { - let declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name)); - } - else { - error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + let declaration = signature.declaration; + if (declaration.name) { + error(declaration.name, Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, declarationNameToString(declaration.name)); + } + else { + error(declaration, Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + signature.resolvedReturnType = type; } return signature.resolvedReturnType; } @@ -8366,8 +8390,7 @@ module ts { } } } - - checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); + getTypeOfAccessors(getSymbolOfNode(node)); } checkFunctionLikeDeclaration(node); From d0e526983a2a401ec7305638ab340e9446c9f1e9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 2 May 2015 16:37:45 -0700 Subject: [PATCH 07/31] Accepting new baselines --- ...ectDependenceBetweenTypeAliases.errors.txt | 20 ++++++++++++++++++- tests/baselines/reference/for-of33.errors.txt | 5 ++++- tests/baselines/reference/for-of34.errors.txt | 5 ++++- tests/baselines/reference/for-of35.errors.txt | 5 ++++- ...mplicitAnyFromCircularInference.errors.txt | 8 +++++++- .../recursiveTypesWithTypeof.errors.txt | 5 ++++- 6 files changed, 42 insertions(+), 6 deletions(-) diff --git a/tests/baselines/reference/directDependenceBetweenTypeAliases.errors.txt b/tests/baselines/reference/directDependenceBetweenTypeAliases.errors.txt index b9890e925c4..68ea92f8fb5 100644 --- a/tests/baselines/reference/directDependenceBetweenTypeAliases.errors.txt +++ b/tests/baselines/reference/directDependenceBetweenTypeAliases.errors.txt @@ -1,15 +1,21 @@ tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(4,6): error TS2456: Type alias 'T0' circularly references itself. +tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(5,6): error TS2456: Type alias 'T0_1' circularly references itself. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(6,6): error TS2456: Type alias 'T0_2' circularly references itself. +tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(7,6): error TS2456: Type alias 'T0_3' circularly references itself. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(11,6): error TS2456: Type alias 'T1' circularly references itself. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(14,6): error TS2456: Type alias 'T2' circularly references itself. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(16,6): error TS2456: Type alias 'T2_1' circularly references itself. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(19,6): error TS2456: Type alias 'T3' circularly references itself. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(22,6): error TS2456: Type alias 'T4' circularly references itself. +tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(25,5): error TS2502: 'x' is referenced directly or indirectly in its own type annotation. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(26,6): error TS2456: Type alias 'T5' circularly references itself. +tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(29,6): error TS2456: Type alias 'T6' circularly references itself. tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(30,6): error TS2456: Type alias 'T7' circularly references itself. +tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(31,5): error TS2502: 'yy' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts(32,6): error TS2456: Type alias 'T8' circularly references itself. -==== tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts (9 errors) ==== +==== tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts (15 errors) ==== // It is an error for the type specified in a type alias to depend on that type alias // A type alias directly depends on the type it aliases. @@ -17,10 +23,14 @@ tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts( ~~ !!! error TS2456: Type alias 'T0' circularly references itself. type T0_1 = T0_2 + ~~~~ +!!! error TS2456: Type alias 'T0_1' circularly references itself. type T0_2 = T0_3 ~~~~ !!! error TS2456: Type alias 'T0_2' circularly references itself. type T0_3 = T0_1 + ~~~~ +!!! error TS2456: Type alias 'T0_3' circularly references itself. // A type reference directly depends on the referenced type and each of the type arguments, if any. interface I {} @@ -49,17 +59,25 @@ tests/cases/conformance/types/typeAliases/directDependenceBetweenTypeAliases.ts( // A type query directly depends on the type of the referenced entity. var x: T5[] = [] + ~ +!!! error TS2502: 'x' is referenced directly or indirectly in its own type annotation. type T5 = typeof x ~~ !!! error TS2456: Type alias 'T5' circularly references itself. class C1 {} type T6 = T7 | number + ~~ +!!! error TS2456: Type alias 'T6' circularly references itself. type T7 = typeof yy ~~ !!! error TS2456: Type alias 'T7' circularly references itself. var yy: [string, T8[]]; + ~~ +!!! error TS2502: 'yy' is referenced directly or indirectly in its own type annotation. type T8 = C + ~~ +!!! error TS2456: Type alias 'T8' circularly references itself. // legal cases type T9 = () => T9 diff --git a/tests/baselines/reference/for-of33.errors.txt b/tests/baselines/reference/for-of33.errors.txt index 1c631042d7d..cd2d48566ab 100644 --- a/tests/baselines/reference/for-of33.errors.txt +++ b/tests/baselines/reference/for-of33.errors.txt @@ -1,13 +1,16 @@ tests/cases/conformance/es6/for-ofStatements/for-of33.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/conformance/es6/for-ofStatements/for-of33.ts(4,5): error TS7023: '[Symbol.iterator]' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. -==== tests/cases/conformance/es6/for-ofStatements/for-of33.ts (1 errors) ==== +==== tests/cases/conformance/es6/for-ofStatements/for-of33.ts (2 errors) ==== for (var v of new StringIterator) { } ~ !!! error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. class StringIterator { [Symbol.iterator]() { + ~~~~~~~~~~~~~~~~~ +!!! error TS7023: '[Symbol.iterator]' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. return v; } } \ No newline at end of file diff --git a/tests/baselines/reference/for-of34.errors.txt b/tests/baselines/reference/for-of34.errors.txt index 994302db88b..a4f55ed29ba 100644 --- a/tests/baselines/reference/for-of34.errors.txt +++ b/tests/baselines/reference/for-of34.errors.txt @@ -1,13 +1,16 @@ tests/cases/conformance/es6/for-ofStatements/for-of34.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/conformance/es6/for-ofStatements/for-of34.ts(4,5): error TS7023: 'next' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. -==== tests/cases/conformance/es6/for-ofStatements/for-of34.ts (1 errors) ==== +==== tests/cases/conformance/es6/for-ofStatements/for-of34.ts (2 errors) ==== for (var v of new StringIterator) { } ~ !!! error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. class StringIterator { next() { + ~~~~ +!!! error TS7023: 'next' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. return v; } diff --git a/tests/baselines/reference/for-of35.errors.txt b/tests/baselines/reference/for-of35.errors.txt index f83b6d2ec3c..65529752b9b 100644 --- a/tests/baselines/reference/for-of35.errors.txt +++ b/tests/baselines/reference/for-of35.errors.txt @@ -1,13 +1,16 @@ tests/cases/conformance/es6/for-ofStatements/for-of35.ts(1,10): error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. +tests/cases/conformance/es6/for-ofStatements/for-of35.ts(4,5): error TS7023: 'next' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. -==== tests/cases/conformance/es6/for-ofStatements/for-of35.ts (1 errors) ==== +==== tests/cases/conformance/es6/for-ofStatements/for-of35.ts (2 errors) ==== for (var v of new StringIterator) { } ~ !!! error TS7022: 'v' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. class StringIterator { next() { + ~~~~ +!!! error TS7023: 'next' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. return { done: true, value: v diff --git a/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt b/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt index deb7fc137b2..8d0aaf04c03 100644 --- a/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt +++ b/tests/baselines/reference/implicitAnyFromCircularInference.errors.txt @@ -1,15 +1,17 @@ tests/cases/compiler/implicitAnyFromCircularInference.ts(3,5): error TS2502: 'a' is referenced directly or indirectly in its own type annotation. +tests/cases/compiler/implicitAnyFromCircularInference.ts(6,5): error TS2502: 'b' is referenced directly or indirectly in its own type annotation. tests/cases/compiler/implicitAnyFromCircularInference.ts(7,5): error TS2502: 'c' is referenced directly or indirectly in its own type annotation. tests/cases/compiler/implicitAnyFromCircularInference.ts(10,5): error TS2502: 'd' is referenced directly or indirectly in its own type annotation. tests/cases/compiler/implicitAnyFromCircularInference.ts(15,10): error TS7023: 'g' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. tests/cases/compiler/implicitAnyFromCircularInference.ts(18,10): error TS7024: Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. tests/cases/compiler/implicitAnyFromCircularInference.ts(23,10): error TS7024: Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. tests/cases/compiler/implicitAnyFromCircularInference.ts(26,10): error TS7023: 'h' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. +tests/cases/compiler/implicitAnyFromCircularInference.ts(28,14): error TS7023: 'foo' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. tests/cases/compiler/implicitAnyFromCircularInference.ts(41,5): error TS7022: 's' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer. tests/cases/compiler/implicitAnyFromCircularInference.ts(46,5): error TS7023: 'x' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. -==== tests/cases/compiler/implicitAnyFromCircularInference.ts (9 errors) ==== +==== tests/cases/compiler/implicitAnyFromCircularInference.ts (11 errors) ==== // Error expected var a: typeof a; @@ -18,6 +20,8 @@ tests/cases/compiler/implicitAnyFromCircularInference.ts(46,5): error TS7023: 'x // Error expected on b or c var b: typeof c; + ~ +!!! error TS2502: 'b' is referenced directly or indirectly in its own type annotation. var c: typeof b; ~ !!! error TS2502: 'c' is referenced directly or indirectly in its own type annotation. @@ -52,6 +56,8 @@ tests/cases/compiler/implicitAnyFromCircularInference.ts(46,5): error TS7023: 'x !!! error TS7023: 'h' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. return foo(); function foo() { + ~~~ +!!! error TS7023: 'foo' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions. return h() || "hello"; } } diff --git a/tests/baselines/reference/recursiveTypesWithTypeof.errors.txt b/tests/baselines/reference/recursiveTypesWithTypeof.errors.txt index 77bb58bfe0a..0604e38bd94 100644 --- a/tests/baselines/reference/recursiveTypesWithTypeof.errors.txt +++ b/tests/baselines/reference/recursiveTypesWithTypeof.errors.txt @@ -1,4 +1,5 @@ tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(2,5): error TS2502: 'c' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(4,5): error TS2502: 'd' is referenced directly or indirectly in its own type annotation. tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(6,5): error TS2502: 'e' is referenced directly or indirectly in its own type annotation. tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(10,5): error TS2502: 'f' is referenced directly or indirectly in its own type annotation. tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(12,5): error TS2502: 'f2' is referenced directly or indirectly in its own type annotation. @@ -6,13 +7,15 @@ tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithType tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts(51,5): error TS2502: 'hy3' is referenced directly or indirectly in its own type annotation. -==== tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts (6 errors) ==== +==== tests/cases/conformance/types/specifyingTypes/typeQueries/recursiveTypesWithTypeof.ts (7 errors) ==== // The following are errors because of circular references var c: typeof c; ~ !!! error TS2502: 'c' is referenced directly or indirectly in its own type annotation. var c: any; var d: typeof e; + ~ +!!! error TS2502: 'd' is referenced directly or indirectly in its own type annotation. var d: any; var e: typeof d; ~ From 7efd93a9655b44562642f49292a05169d9a7cadf Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sat, 2 May 2015 16:57:18 -0700 Subject: [PATCH 08/31] Adding test --- .../circularTypeofWithVarOrFunc.errors.txt | 28 +++++++++++++++++++ .../reference/circularTypeofWithVarOrFunc.js | 17 +++++++++++ .../circularTypeofWithVarOrFunc.ts | 9 ++++++ 3 files changed, 54 insertions(+) create mode 100644 tests/baselines/reference/circularTypeofWithVarOrFunc.errors.txt create mode 100644 tests/baselines/reference/circularTypeofWithVarOrFunc.js create mode 100644 tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts diff --git a/tests/baselines/reference/circularTypeofWithVarOrFunc.errors.txt b/tests/baselines/reference/circularTypeofWithVarOrFunc.errors.txt new file mode 100644 index 00000000000..26bff709ae1 --- /dev/null +++ b/tests/baselines/reference/circularTypeofWithVarOrFunc.errors.txt @@ -0,0 +1,28 @@ +tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts(1,6): error TS2456: Type alias 'typeAlias1' circularly references itself. +tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts(2,5): error TS2502: 'varOfAliasedType1' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts(4,5): error TS2502: 'varOfAliasedType2' is referenced directly or indirectly in its own type annotation. +tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts(5,6): error TS2456: Type alias 'typeAlias2' circularly references itself. +tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts(9,6): error TS2456: Type alias 'typeAlias3' circularly references itself. + + +==== tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts (5 errors) ==== + type typeAlias1 = typeof varOfAliasedType1; + ~~~~~~~~~~ +!!! error TS2456: Type alias 'typeAlias1' circularly references itself. + var varOfAliasedType1: typeAlias1; + ~~~~~~~~~~~~~~~~~ +!!! error TS2502: 'varOfAliasedType1' is referenced directly or indirectly in its own type annotation. + + var varOfAliasedType2: typeAlias2; + ~~~~~~~~~~~~~~~~~ +!!! error TS2502: 'varOfAliasedType2' is referenced directly or indirectly in its own type annotation. + type typeAlias2 = typeof varOfAliasedType2; + ~~~~~~~~~~ +!!! error TS2456: Type alias 'typeAlias2' circularly references itself. + + function func(): typeAlias3 { return null; } + var varOfAliasedType3 = func(); + type typeAlias3 = typeof varOfAliasedType3; + ~~~~~~~~~~ +!!! error TS2456: Type alias 'typeAlias3' circularly references itself. + \ No newline at end of file diff --git a/tests/baselines/reference/circularTypeofWithVarOrFunc.js b/tests/baselines/reference/circularTypeofWithVarOrFunc.js new file mode 100644 index 00000000000..9d569a3d219 --- /dev/null +++ b/tests/baselines/reference/circularTypeofWithVarOrFunc.js @@ -0,0 +1,17 @@ +//// [circularTypeofWithVarOrFunc.ts] +type typeAlias1 = typeof varOfAliasedType1; +var varOfAliasedType1: typeAlias1; + +var varOfAliasedType2: typeAlias2; +type typeAlias2 = typeof varOfAliasedType2; + +function func(): typeAlias3 { return null; } +var varOfAliasedType3 = func(); +type typeAlias3 = typeof varOfAliasedType3; + + +//// [circularTypeofWithVarOrFunc.js] +var varOfAliasedType1; +var varOfAliasedType2; +function func() { return null; } +var varOfAliasedType3 = func(); diff --git a/tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts b/tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts new file mode 100644 index 00000000000..e3483aa27d3 --- /dev/null +++ b/tests/cases/conformance/types/specifyingTypes/typeQueries/circularTypeofWithVarOrFunc.ts @@ -0,0 +1,9 @@ +type typeAlias1 = typeof varOfAliasedType1; +var varOfAliasedType1: typeAlias1; + +var varOfAliasedType2: typeAlias2; +type typeAlias2 = typeof varOfAliasedType2; + +function func(): typeAlias3 { return null; } +var varOfAliasedType3 = func(); +type typeAlias3 = typeof varOfAliasedType3; From 41861670151e258480c57c9edfcc44b618a0b937 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Sun, 3 May 2015 15:05:10 -0700 Subject: [PATCH 09/31] Removing 'resolvingType' special type --- src/compiler/checker.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 77120637ea7..ff1d05da1dc 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -88,7 +88,6 @@ module ts { let undefinedType = createIntrinsicType(TypeFlags.Undefined | TypeFlags.ContainsUndefinedOrNull, "undefined"); let nullType = createIntrinsicType(TypeFlags.Null | TypeFlags.ContainsUndefinedOrNull, "null"); let unknownType = createIntrinsicType(TypeFlags.Any, "unknown"); - let resolvingType = createIntrinsicType(TypeFlags.Any, "__resolving__"); let emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -7373,10 +7372,9 @@ module ts { if (isContextSensitive(node)) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } - if (!node.type) { - signature.resolvedReturnType = resolvingType; + if (!node.type && !signature.resolvedReturnType) { let returnType = getReturnTypeFromBody(node, contextualMapper); - if (signature.resolvedReturnType === resolvingType) { + if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } } From d3a2c2a042bd85839054fa2b6e56edb4e40a021c Mon Sep 17 00:00:00 2001 From: Jason Freeman Date: Mon, 4 May 2015 17:29:57 -0700 Subject: [PATCH 10/31] Make the harness report a failure if the line endings differ from the baselines --- src/harness/harness.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 8e1bdbf07ee..7d04c042fdb 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1702,9 +1702,9 @@ module Harness { expected = IO.readFile(refFileName); } - var lineEndingSensitive = opts && opts.LineEndingSensitive; + var lineEndingInsensitive = opts && opts.LineEndingSensitive === false; // default is true - if (!lineEndingSensitive) { + if (lineEndingInsensitive) { expected = expected.replace(/\r\n?/g, '\n'); actual = actual.replace(/\r\n?/g, '\n'); } From 08cffc598c815e10f56e53654e6176cc14f836f9 Mon Sep 17 00:00:00 2001 From: Jason Freeman Date: Mon, 4 May 2015 17:30:06 -0700 Subject: [PATCH 11/31] Rebaseline tests --- .../reference/newLineFlagWithCRLF.js | 12 +++---- .../reference/newLineFlagWithCRLF.symbols | 16 +++++----- .../reference/newLineFlagWithCRLF.types | 22 ++++++------- .../baselines/reference/newLineFlagWithLF.js | 8 ++--- .../reference/newLineFlagWithLF.symbols | 16 +++++----- .../reference/newLineFlagWithLF.types | 22 ++++++------- tests/baselines/reference/noEmitHelpers.js | 32 +++++++++---------- .../baselines/reference/noEmitHelpers.symbols | 18 +++++------ tests/baselines/reference/noEmitHelpers.types | 18 +++++------ 9 files changed, 82 insertions(+), 82 deletions(-) diff --git a/tests/baselines/reference/newLineFlagWithCRLF.js b/tests/baselines/reference/newLineFlagWithCRLF.js index ebf095e5fc7..9aaaea41fad 100644 --- a/tests/baselines/reference/newLineFlagWithCRLF.js +++ b/tests/baselines/reference/newLineFlagWithCRLF.js @@ -1,9 +1,9 @@ -//// [newLineFlagWithCRLF.ts] +//// [newLineFlagWithCRLF.ts] var x=1; x=2; - - -//// [newLineFlagWithCRLF.js] -var x = 1; -x = 2; + + +//// [newLineFlagWithCRLF.js] +var x = 1; +x = 2; diff --git a/tests/baselines/reference/newLineFlagWithCRLF.symbols b/tests/baselines/reference/newLineFlagWithCRLF.symbols index 07825959fbe..0bf676067e4 100644 --- a/tests/baselines/reference/newLineFlagWithCRLF.symbols +++ b/tests/baselines/reference/newLineFlagWithCRLF.symbols @@ -1,8 +1,8 @@ -=== tests/cases/compiler/newLineFlagWithCRLF.ts === -var x=1; ->x : Symbol(x, Decl(newLineFlagWithCRLF.ts, 0, 3)) - -x=2; ->x : Symbol(x, Decl(newLineFlagWithCRLF.ts, 0, 3)) - - +=== tests/cases/compiler/newLineFlagWithCRLF.ts === +var x=1; +>x : Symbol(x, Decl(newLineFlagWithCRLF.ts, 0, 3)) + +x=2; +>x : Symbol(x, Decl(newLineFlagWithCRLF.ts, 0, 3)) + + diff --git a/tests/baselines/reference/newLineFlagWithCRLF.types b/tests/baselines/reference/newLineFlagWithCRLF.types index 2663f4bbc7b..4898d2495b2 100644 --- a/tests/baselines/reference/newLineFlagWithCRLF.types +++ b/tests/baselines/reference/newLineFlagWithCRLF.types @@ -1,11 +1,11 @@ -=== tests/cases/compiler/newLineFlagWithCRLF.ts === -var x=1; ->x : number ->1 : number - -x=2; ->x=2 : number ->x : number ->2 : number - - +=== tests/cases/compiler/newLineFlagWithCRLF.ts === +var x=1; +>x : number +>1 : number + +x=2; +>x=2 : number +>x : number +>2 : number + + diff --git a/tests/baselines/reference/newLineFlagWithLF.js b/tests/baselines/reference/newLineFlagWithLF.js index be1b9ed644e..f516cb9b7fc 100644 --- a/tests/baselines/reference/newLineFlagWithLF.js +++ b/tests/baselines/reference/newLineFlagWithLF.js @@ -1,9 +1,9 @@ -//// [newLineFlagWithLF.ts] +//// [newLineFlagWithLF.ts] var x=1; x=2; - - -//// [newLineFlagWithLF.js] + + +//// [newLineFlagWithLF.js] var x = 1; x = 2; diff --git a/tests/baselines/reference/newLineFlagWithLF.symbols b/tests/baselines/reference/newLineFlagWithLF.symbols index f4edf68dcb0..a8964eebd14 100644 --- a/tests/baselines/reference/newLineFlagWithLF.symbols +++ b/tests/baselines/reference/newLineFlagWithLF.symbols @@ -1,8 +1,8 @@ -=== tests/cases/compiler/newLineFlagWithLF.ts === -var x=1; ->x : Symbol(x, Decl(newLineFlagWithLF.ts, 0, 3)) - -x=2; ->x : Symbol(x, Decl(newLineFlagWithLF.ts, 0, 3)) - - +=== tests/cases/compiler/newLineFlagWithLF.ts === +var x=1; +>x : Symbol(x, Decl(newLineFlagWithLF.ts, 0, 3)) + +x=2; +>x : Symbol(x, Decl(newLineFlagWithLF.ts, 0, 3)) + + diff --git a/tests/baselines/reference/newLineFlagWithLF.types b/tests/baselines/reference/newLineFlagWithLF.types index 735f31d6c52..bfdf6072e0e 100644 --- a/tests/baselines/reference/newLineFlagWithLF.types +++ b/tests/baselines/reference/newLineFlagWithLF.types @@ -1,11 +1,11 @@ -=== tests/cases/compiler/newLineFlagWithLF.ts === -var x=1; ->x : number ->1 : number - -x=2; ->x=2 : number ->x : number ->2 : number - - +=== tests/cases/compiler/newLineFlagWithLF.ts === +var x=1; +>x : number +>1 : number + +x=2; +>x=2 : number +>x : number +>2 : number + + diff --git a/tests/baselines/reference/noEmitHelpers.js b/tests/baselines/reference/noEmitHelpers.js index 8db5cd862bf..bfe5a4f4445 100644 --- a/tests/baselines/reference/noEmitHelpers.js +++ b/tests/baselines/reference/noEmitHelpers.js @@ -1,19 +1,19 @@ -//// [noEmitHelpers.ts] +//// [noEmitHelpers.ts] class A { } class B extends A { } - - -//// [noEmitHelpers.js] -var A = (function () { - function A() { - } - return A; -})(); -var B = (function (_super) { - __extends(B, _super); - function B() { - _super.apply(this, arguments); - } - return B; -})(A); + + +//// [noEmitHelpers.js] +var A = (function () { + function A() { + } + return A; +})(); +var B = (function (_super) { + __extends(B, _super); + function B() { + _super.apply(this, arguments); + } + return B; +})(A); diff --git a/tests/baselines/reference/noEmitHelpers.symbols b/tests/baselines/reference/noEmitHelpers.symbols index efd281c812b..654f1a6cad5 100644 --- a/tests/baselines/reference/noEmitHelpers.symbols +++ b/tests/baselines/reference/noEmitHelpers.symbols @@ -1,9 +1,9 @@ -=== tests/cases/compiler/noEmitHelpers.ts === - -class A { } ->A : Symbol(A, Decl(noEmitHelpers.ts, 0, 0)) - -class B extends A { } ->B : Symbol(B, Decl(noEmitHelpers.ts, 1, 11)) ->A : Symbol(A, Decl(noEmitHelpers.ts, 0, 0)) - +=== tests/cases/compiler/noEmitHelpers.ts === + +class A { } +>A : Symbol(A, Decl(noEmitHelpers.ts, 0, 0)) + +class B extends A { } +>B : Symbol(B, Decl(noEmitHelpers.ts, 1, 11)) +>A : Symbol(A, Decl(noEmitHelpers.ts, 0, 0)) + diff --git a/tests/baselines/reference/noEmitHelpers.types b/tests/baselines/reference/noEmitHelpers.types index d25bd88255c..01c5d5acb3d 100644 --- a/tests/baselines/reference/noEmitHelpers.types +++ b/tests/baselines/reference/noEmitHelpers.types @@ -1,9 +1,9 @@ -=== tests/cases/compiler/noEmitHelpers.ts === - -class A { } ->A : A - -class B extends A { } ->B : B ->A : A - +=== tests/cases/compiler/noEmitHelpers.ts === + +class A { } +>A : A + +class B extends A { } +>B : B +>A : A + From 880ccf0221f482322d97da238abc26f64b731381 Mon Sep 17 00:00:00 2001 From: vvakame Date: Tue, 5 May 2015 20:29:43 +0900 Subject: [PATCH 12/31] PR feedback --- src/compiler/checker.ts | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c864a8aa76a..eac5d563357 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3599,6 +3599,10 @@ module ts { return type; } + function getUnionTypeOfSubtypeConstituents(source: UnionType, target: Type): Type { + return getUnionType(filter(source.types, t => isTypeSubtypeOf(t, target))); + } + function getReducedTypeOfUnionType(type: UnionType): Type { // If union type was created without subtype reduction, perform the deferred reduction now if (!type.reducedType) { @@ -5354,26 +5358,26 @@ module ts { if (prototypeProperty) { let targetType = getTypeOfSymbol(prototypeProperty); if (targetType !== anyType) { - // Narrow to target type if it is a subtype of current type + // Narrow to the target type if it's a subtype of the current type if (isTypeSubtypeOf(targetType, type)) { return targetType; } - // If current type is a union type, remove all constituents that aren't subtypes of target type + // If the current type is a union type, remove all constituents that aren't subtypes of the target. if (type.flags & TypeFlags.Union) { - return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, targetType))); + return getUnionTypeOfSubtypeConstituents(type, targetType); } } } // Target type is type of constructor signiture - let constructSignitures: Signature[]; + let constructSignatures: Signature[]; if (rightType.flags & TypeFlags.Interface) { - constructSignitures = (rightType).declaredConstructSignatures; + constructSignatures = (rightType).declaredConstructSignatures; + } else if (rightType.flags & TypeFlags.Anonymous) { + constructSignatures = (rightType).constructSignatures; } - if (rightType.flags & TypeFlags.Anonymous) { - constructSignitures = (rightType).constructSignatures; - } - if (constructSignitures) { - let instanceType = getUnionType(map(constructSignitures, constructSignature => { + + if (constructSignatures) { + let instanceType = getUnionType(map(constructSignatures, constructSignature => { if (constructSignature.typeParameters && constructSignature.typeParameters.length !== 0) { constructSignature = instantiateSignature(constructSignature, createTypeMapper(constructSignature.typeParameters, map(constructSignature.typeParameters, _ => anyType)), true) } @@ -5381,7 +5385,7 @@ module ts { })); // Pickup type from union types if (type.flags & TypeFlags.Union) { - return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, instanceType))); + return getUnionTypeOfSubtypeConstituents(type, instanceType); } return instanceType; } From eeb23ad96ec85385de335f13f40fc8f678f10da9 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 5 May 2015 07:23:56 -0700 Subject: [PATCH 13/31] Addressing CR feedback --- src/compiler/checker.ts | 35 +++++++++++++++++++---------------- 1 file changed, 19 insertions(+), 16 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ff1d05da1dc..ab3946cd880 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -127,7 +127,6 @@ module ts { let resolutionTargets: Object[] = []; let resolutionResults: boolean[] = []; - let resolutionCount = 0; let mergedSymbols: Symbol[] = []; let symbolLinks: SymbolLinks[] = []; @@ -2020,29 +2019,33 @@ module ts { // Push an entry on the type resolution stack. If an entry with the given target is not already on the stack, // a new entry with that target and an associated result value of true is pushed on the stack, and the value // true is returned. Otherwise, a circularity has occurred and the result values of the existing entry and - // all entries pushed after it are changed to false, and the value false is returned. The target object has - // no significance other than to provide a unique identity for a particular type resolution result. + // all entries pushed after it are changed to false, and the value false is returned. The target object provides + // a unique identity for a particular type resolution result: Symbol instances are used to track resolution of + // SymbolLinks.type, SymbolLinks instances are used to track resolution of SymbolLinks.declaredType, and + // Signature instances are used to track resolution of Signature.resolvedReturnType. function pushTypeResolution(target: Object): boolean { - for (let i = 0; i < resolutionCount; i++) { - if (resolutionTargets[i] === target) { - do { - resolutionResults[i++] = false; - } - while (i < resolutionCount); - return false; - } + let i = 0; + let count = resolutionTargets.length; + while (i < count && resolutionTargets[i] !== target) { + i++; } - resolutionTargets[resolutionCount] = target; - resolutionResults[resolutionCount] = true; - resolutionCount++; + if (i < count) { + do { + resolutionResults[i++] = false; + } + while (i < count); + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); return true; } // Pop an entry from the type resolution stack and return its associated result value. The result value will // be true if no circularities were detected, or false if a circularity was found. function popTypeResolution(): boolean { - resolutionTargets[--resolutionCount] = undefined; - return resolutionResults[resolutionCount]; + resolutionTargets.pop(); + return resolutionResults.pop(); } function getRootDeclaration(node: Node): Node { From e342c955625b10523cf753fa63982c1092502bee Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 6 May 2015 01:00:17 +0900 Subject: [PATCH 14/31] fix code styling --- src/compiler/checker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index eac5d563357..c279786c686 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5372,7 +5372,8 @@ module ts { let constructSignatures: Signature[]; if (rightType.flags & TypeFlags.Interface) { constructSignatures = (rightType).declaredConstructSignatures; - } else if (rightType.flags & TypeFlags.Anonymous) { + } + else if (rightType.flags & TypeFlags.Anonymous) { constructSignatures = (rightType).constructSignatures; } From 6338e2b1927fe525286ca98b23a2131789684cad Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 5 May 2015 09:50:11 -0700 Subject: [PATCH 15/31] Fix 'resolveName' to correctly obtain local name of export default --- src/compiler/checker.ts | 4 ++-- src/compiler/utilities.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 04766f22c4e..5e599a27c6e 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -350,9 +350,9 @@ module ts { } else if (location.kind === SyntaxKind.SourceFile || (location.kind === SyntaxKind.ModuleDeclaration && (location).name.kind === SyntaxKind.StringLiteral)) { - result = getSymbol(getSymbolOfNode(location).exports, "default", meaning & SymbolFlags.ModuleMember); + result = getSymbolOfNode(location).exports["default"]; let localSymbol = getLocalSymbolForExportDefault(result); - if (result && (result.flags & meaning) && localSymbol && localSymbol.name === name) { + if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 3ddd8338960..0bb0065d1b0 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -1695,7 +1695,7 @@ module ts { } export function getLocalSymbolForExportDefault(symbol: Symbol) { - return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & NodeFlags.Default) ? symbol.valueDeclaration.localSymbol : undefined; + return symbol && symbol.valueDeclaration && (symbol.valueDeclaration.flags & NodeFlags.Default) ? symbol.valueDeclaration.localSymbol : undefined; } /** From f08d3793a3df0057c6ad82efdca7fcc6e5d65579 Mon Sep 17 00:00:00 2001 From: Anders Hejlsberg Date: Tue, 5 May 2015 10:02:29 -0700 Subject: [PATCH 16/31] Adding regression test --- tests/baselines/reference/exportDefaultVariable.js | 12 ++++++++++++ .../reference/exportDefaultVariable.symbols | 11 +++++++++++ .../baselines/reference/exportDefaultVariable.types | 11 +++++++++++ tests/cases/compiler/exportDefaultVariable.ts | 7 +++++++ 4 files changed, 41 insertions(+) create mode 100644 tests/baselines/reference/exportDefaultVariable.js create mode 100644 tests/baselines/reference/exportDefaultVariable.symbols create mode 100644 tests/baselines/reference/exportDefaultVariable.types create mode 100644 tests/cases/compiler/exportDefaultVariable.ts diff --git a/tests/baselines/reference/exportDefaultVariable.js b/tests/baselines/reference/exportDefaultVariable.js new file mode 100644 index 00000000000..beb8bb84a80 --- /dev/null +++ b/tests/baselines/reference/exportDefaultVariable.js @@ -0,0 +1,12 @@ +//// [exportDefaultVariable.ts] +// Regression test for #3018 + +declare var io: any; + +declare module 'module' { + export default io; +} + + +//// [exportDefaultVariable.js] +// Regression test for #3018 diff --git a/tests/baselines/reference/exportDefaultVariable.symbols b/tests/baselines/reference/exportDefaultVariable.symbols new file mode 100644 index 00000000000..cd7ebed926c --- /dev/null +++ b/tests/baselines/reference/exportDefaultVariable.symbols @@ -0,0 +1,11 @@ +=== tests/cases/compiler/exportDefaultVariable.ts === +// Regression test for #3018 + +declare var io: any; +>io : Symbol(io, Decl(exportDefaultVariable.ts, 2, 11)) + +declare module 'module' { + export default io; +>io : Symbol(default, Decl(exportDefaultVariable.ts, 2, 11)) +} + diff --git a/tests/baselines/reference/exportDefaultVariable.types b/tests/baselines/reference/exportDefaultVariable.types new file mode 100644 index 00000000000..a61c64b4685 --- /dev/null +++ b/tests/baselines/reference/exportDefaultVariable.types @@ -0,0 +1,11 @@ +=== tests/cases/compiler/exportDefaultVariable.ts === +// Regression test for #3018 + +declare var io: any; +>io : any + +declare module 'module' { + export default io; +>io : any +} + diff --git a/tests/cases/compiler/exportDefaultVariable.ts b/tests/cases/compiler/exportDefaultVariable.ts new file mode 100644 index 00000000000..95fd503dfc4 --- /dev/null +++ b/tests/cases/compiler/exportDefaultVariable.ts @@ -0,0 +1,7 @@ +// Regression test for #3018 + +declare var io: any; + +declare module 'module' { + export default io; +} From 2a098cd36ccc2b415d3658f4f68522b7ec5afe56 Mon Sep 17 00:00:00 2001 From: Zhengbo Li Date: Tue, 5 May 2015 10:23:51 -0700 Subject: [PATCH 17/31] Add missing overload to XMLHttpRequest.send Fix issue #3002 --- src/lib/dom.generated.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 00b4e8ea570..5a4151c0c1c 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -12180,6 +12180,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { overrideMimeType(mime: string): void; send(data?: Document): void; send(data?: string): void; + send(data?: any): void; setRequestHeader(header: string, value: string): void; DONE: number; HEADERS_RECEIVED: number; From 13e4450de08f253191d1827ad0e658a949f1af04 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 5 May 2015 10:57:15 -0700 Subject: [PATCH 18/31] Delete emitter.js --- src/compiler/emitter.js | 5229 --------------------------------------- 1 file changed, 5229 deletions(-) delete mode 100644 src/compiler/emitter.js diff --git a/src/compiler/emitter.js b/src/compiler/emitter.js deleted file mode 100644 index a00f3a4dde3..00000000000 --- a/src/compiler/emitter.js +++ /dev/null @@ -1,5229 +0,0 @@ -/// -/// -/* @internal */ -var ts; -(function (ts) { - function isExternalModuleOrDeclarationFile(sourceFile) { - return ts.isExternalModule(sourceFile) || ts.isDeclarationFile(sourceFile); - } - ts.isExternalModuleOrDeclarationFile = isExternalModuleOrDeclarationFile; - // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile) { - // emit output for the __extends helper function - var extendsHelper = "\nvar __extends = this.__extends || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n __.prototype = b.prototype;\n d.prototype = new __();\n};"; - // emit output for the __decorate helper function - var decorateHelper = "\nvar __decorate = this.__decorate || (typeof Reflect === \"object\" && Reflect.decorate) || function (decorators, target, key, desc) {\n switch (arguments.length) {\n case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);\n case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);\n case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);\n }\n};"; - // emit output for the __metadata helper function - var metadataHelper = "\nvar __metadata = this.__metadata || (typeof Reflect === \"object\" && Reflect.metadata) || function () { };"; - // emit output for the __param helper function - var paramHelper = "\nvar __param = this.__param || function(index, decorator) { return function (target, key) { decorator(target, key, index); } };"; - var compilerOptions = host.getCompilerOptions(); - var languageVersion = compilerOptions.target || 0 /* ES3 */; - var sourceMapDataList = compilerOptions.sourceMap ? [] : undefined; - var diagnostics = []; - var newLine = host.getNewLine(); - if (targetSourceFile === undefined) { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (ts.shouldEmitToOwnFile(sourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, ".js"); - emitFile(jsFilePath, sourceFile); - } - }); - if (compilerOptions.out) { - emitFile(compilerOptions.out); - } - } - else { - // targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service) - if (ts.shouldEmitToOwnFile(targetSourceFile, compilerOptions)) { - var jsFilePath = ts.getOwnEmitOutputFilePath(targetSourceFile, host, ".js"); - emitFile(jsFilePath, targetSourceFile); - } - else if (!ts.isDeclarationFile(targetSourceFile) && compilerOptions.out) { - emitFile(compilerOptions.out); - } - } - // Sort and make the unique list of diagnostics - diagnostics = ts.sortAndDeduplicateDiagnostics(diagnostics); - return { - emitSkipped: false, - diagnostics: diagnostics, - sourceMaps: sourceMapDataList - }; - function isNodeDescendentOf(node, ancestor) { - while (node) { - if (node === ancestor) - return true; - node = node.parent; - } - return false; - } - function isUniqueLocalName(name, container) { - for (var node = container; isNodeDescendentOf(node, container); node = node.nextContainer) { - if (node.locals && ts.hasProperty(node.locals, name)) { - // We conservatively include alias symbols to cover cases where they're emitted as locals - if (node.locals[name].flags & (107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */)) { - return false; - } - } - } - return true; - } - function emitJavaScript(jsFilePath, root) { - var writer = ts.createTextWriter(newLine); - var write = writer.write; - var writeTextOfNode = writer.writeTextOfNode; - var writeLine = writer.writeLine; - var increaseIndent = writer.increaseIndent; - var decreaseIndent = writer.decreaseIndent; - var currentSourceFile; - // name of an exporter function if file is a System external module - // System.register([...], function () {...}) - // exporting in System modules looks like: - // export var x; ... x = 1 - // => - // var x;... exporter("x", x = 1) - var exportFunctionForFile; - var generatedNameSet = {}; - var nodeToGeneratedName = []; - var blockScopedVariableToGeneratedName; - var computedPropertyNamesToGeneratedNames; - var extendsEmitted = false; - var decorateEmitted = false; - var paramEmitted = false; - var tempFlags = 0; - var tempVariables; - var tempParameters; - var externalImports; - var exportSpecifiers; - var exportEquals; - var hasExportStars; - /** write emitted output to disk*/ - var writeEmittedFiles = writeJavaScriptFile; - var detachedCommentsInfo; - var writeComment = ts.writeCommentRange; - /** Emit a node */ - var emit = emitNodeWithoutSourceMap; - /** Called just before starting emit of a node */ - var emitStart = function (node) { }; - /** Called once the emit of the node is done */ - var emitEnd = function (node) { }; - /** Emit the text for the given token that comes after startPos - * This by default writes the text provided with the given tokenKind - * but if optional emitFn callback is provided the text is emitted using the callback instead of default text - * @param tokenKind the kind of the token to search and emit - * @param startPos the position in the source to start searching for the token - * @param emitFn if given will be invoked to emit the text instead of actual token emit */ - var emitToken = emitTokenText; - /** Called to before starting the lexical scopes as in function/class in the emitted code because of node - * @param scopeDeclaration node that starts the lexical scope - * @param scopeName Optional name of this scope instead of deducing one from the declaration node */ - var scopeEmitStart = function (scopeDeclaration, scopeName) { }; - /** Called after coming out of the scope */ - var scopeEmitEnd = function () { }; - /** Sourcemap data that will get encoded */ - var sourceMapData; - if (compilerOptions.sourceMap) { - initializeEmitterWithSourceMaps(); - } - if (root) { - // Do not call emit directly. It does not set the currentSourceFile. - emitSourceFile(root); - } - else { - ts.forEach(host.getSourceFiles(), function (sourceFile) { - if (!isExternalModuleOrDeclarationFile(sourceFile)) { - emitSourceFile(sourceFile); - } - }); - } - writeLine(); - writeEmittedFiles(writer.getText(), compilerOptions.emitBOM); - return; - function emitSourceFile(sourceFile) { - currentSourceFile = sourceFile; - exportFunctionForFile = undefined; - emit(sourceFile); - } - function isUniqueName(name) { - return !resolver.hasGlobalName(name) && - !ts.hasProperty(currentSourceFile.identifiers, name) && - !ts.hasProperty(generatedNameSet, name); - } - // Return the next available name in the pattern _a ... _z, _0, _1, ... - // TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. - // Note that names generated by makeTempVariableName and makeUniqueName will never conflict. - function makeTempVariableName(flags) { - if (flags && !(tempFlags & flags)) { - var name = flags === 268435456 /* _i */ ? "_i" : "_n"; - if (isUniqueName(name)) { - tempFlags |= flags; - return name; - } - } - while (true) { - var count = tempFlags & 268435455 /* CountMask */; - tempFlags++; - // Skip over 'i' and 'n' - if (count !== 8 && count !== 13) { - var name_1 = count < 26 ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); - if (isUniqueName(name_1)) { - return name_1; - } - } - } - } - // Generate a name that is unique within the current file and doesn't conflict with any names - // in global scope. The name is formed by adding an '_n' suffix to the specified base name, - // where n is a positive integer. Note that names generated by makeTempVariableName and - // makeUniqueName are guaranteed to never conflict. - function makeUniqueName(baseName) { - // Find the first unique 'name_n', where n is a positive number - if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) { - baseName += "_"; - } - var i = 1; - while (true) { - var generatedName = baseName + i; - if (isUniqueName(generatedName)) { - return generatedNameSet[generatedName] = generatedName; - } - i++; - } - } - function assignGeneratedName(node, name) { - nodeToGeneratedName[ts.getNodeId(node)] = ts.unescapeIdentifier(name); - } - function generateNameForFunctionOrClassDeclaration(node) { - if (!node.name) { - assignGeneratedName(node, makeUniqueName("default")); - } - } - function generateNameForModuleOrEnum(node) { - if (node.name.kind === 65 /* Identifier */) { - var name_2 = node.name.text; - // Use module/enum name itself if it is unique, otherwise make a unique variation - assignGeneratedName(node, isUniqueLocalName(name_2, node) ? name_2 : makeUniqueName(name_2)); - } - } - function generateNameForImportOrExportDeclaration(node) { - var expr = ts.getExternalModuleName(node); - var baseName = expr.kind === 8 /* StringLiteral */ ? - ts.escapeIdentifier(ts.makeIdentifierFromModuleName(expr.text)) : "module"; - assignGeneratedName(node, makeUniqueName(baseName)); - } - function generateNameForImportDeclaration(node) { - if (node.importClause) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportDeclaration(node) { - if (node.moduleSpecifier) { - generateNameForImportOrExportDeclaration(node); - } - } - function generateNameForExportAssignment(node) { - if (node.expression && node.expression.kind !== 65 /* Identifier */) { - assignGeneratedName(node, makeUniqueName("default")); - } - } - function generateNameForNode(node) { - switch (node.kind) { - case 200 /* FunctionDeclaration */: - case 201 /* ClassDeclaration */: - case 174 /* ClassExpression */: - generateNameForFunctionOrClassDeclaration(node); - break; - case 205 /* ModuleDeclaration */: - generateNameForModuleOrEnum(node); - generateNameForNode(node.body); - break; - case 204 /* EnumDeclaration */: - generateNameForModuleOrEnum(node); - break; - case 209 /* ImportDeclaration */: - generateNameForImportDeclaration(node); - break; - case 215 /* ExportDeclaration */: - generateNameForExportDeclaration(node); - break; - case 214 /* ExportAssignment */: - generateNameForExportAssignment(node); - break; - } - } - function getGeneratedNameForNode(node) { - var nodeId = ts.getNodeId(node); - if (!nodeToGeneratedName[nodeId]) { - generateNameForNode(node); - } - return nodeToGeneratedName[nodeId]; - } - function initializeEmitterWithSourceMaps() { - var sourceMapDir; // The directory in which sourcemap will be - // Current source map file and its index in the sources list - var sourceMapSourceIndex = -1; - // Names and its index map - var sourceMapNameIndexMap = {}; - var sourceMapNameIndices = []; - function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? lastOrUndefined(sourceMapNameIndices) : -1; - } - // Last recorded and encoded spans - var lastRecordedSourceMapSpan; - var lastEncodedSourceMapSpan = { - emittedLine: 1, - emittedColumn: 1, - sourceLine: 1, - sourceColumn: 1, - sourceIndex: 0 - }; - var lastEncodedNameIndex = 0; - // Encoding for sourcemap span - function encodeLastRecordedSourceMapSpan() { - if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { - return; - } - var prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Line/Comma delimiters - if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) { - // Emit comma to separate the entry - if (sourceMapData.sourceMapMappings) { - sourceMapData.sourceMapMappings += ","; - } - } - else { - // Emit line delimiters - for (var encodedLine = lastEncodedSourceMapSpan.emittedLine; encodedLine < lastRecordedSourceMapSpan.emittedLine; encodedLine++) { - sourceMapData.sourceMapMappings += ";"; - } - prevEncodedEmittedColumn = 1; - } - // 1. Relative Column 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.emittedColumn - prevEncodedEmittedColumn); - // 2. Relative sourceIndex - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceIndex - lastEncodedSourceMapSpan.sourceIndex); - // 3. Relative sourceLine 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceLine - lastEncodedSourceMapSpan.sourceLine); - // 4. Relative sourceColumn 0 based - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.sourceColumn - lastEncodedSourceMapSpan.sourceColumn); - // 5. Relative namePosition 0 based - if (lastRecordedSourceMapSpan.nameIndex >= 0) { - sourceMapData.sourceMapMappings += base64VLQFormatEncode(lastRecordedSourceMapSpan.nameIndex - lastEncodedNameIndex); - lastEncodedNameIndex = lastRecordedSourceMapSpan.nameIndex; - } - lastEncodedSourceMapSpan = lastRecordedSourceMapSpan; - sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); - function base64VLQFormatEncode(inValue) { - function base64FormatEncode(inValue) { - if (inValue < 64) { - return 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.charAt(inValue); - } - throw TypeError(inValue + ": not a 64 based value"); - } - // Add a new least significant bit that has the sign of the value. - // if negative number the least significant bit that gets added to the number has value 1 - // else least significant bit value that gets added is 0 - // eg. -1 changes to binary : 01 [1] => 3 - // +1 changes to binary : 01 [0] => 2 - if (inValue < 0) { - inValue = ((-inValue) << 1) + 1; - } - else { - inValue = inValue << 1; - } - // Encode 5 bits at a time starting from least significant bits - var encodedStr = ""; - do { - var currentDigit = inValue & 31; // 11111 - inValue = inValue >> 5; - if (inValue > 0) { - // There are still more digits to decode, set the msb (6th bit) - currentDigit = currentDigit | 32; - } - encodedStr = encodedStr + base64FormatEncode(currentDigit); - } while (inValue > 0); - return encodedStr; - } - } - function recordSourceMapSpan(pos) { - var sourceLinePos = ts.getLineAndCharacterOfPosition(currentSourceFile, pos); - // Convert the location to be one-based. - sourceLinePos.line++; - sourceLinePos.character++; - var emittedLine = writer.getLine(); - var emittedColumn = writer.getColumn(); - // If this location wasn't recorded or the location in source is going backwards, record the span - if (!lastRecordedSourceMapSpan || - lastRecordedSourceMapSpan.emittedLine != emittedLine || - lastRecordedSourceMapSpan.emittedColumn != emittedColumn || - (lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex && - (lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line || - (lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) { - // Encode the last recordedSpan before assigning new - encodeLastRecordedSourceMapSpan(); - // New span - lastRecordedSourceMapSpan = { - emittedLine: emittedLine, - emittedColumn: emittedColumn, - sourceLine: sourceLinePos.line, - sourceColumn: sourceLinePos.character, - nameIndex: getSourceMapNameIndex(), - sourceIndex: sourceMapSourceIndex - }; - } - else { - // Take the new pos instead since there is no change in emittedLine and column since last location - lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; - lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; - lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; - } - } - function recordEmitNodeStartSpan(node) { - // Get the token pos after skipping to the token (ignoring the leading trivia) - recordSourceMapSpan(ts.skipTrivia(currentSourceFile.text, node.pos)); - } - function recordEmitNodeEndSpan(node) { - recordSourceMapSpan(node.end); - } - function writeTextWithSpanRecord(tokenKind, startPos, emitFn) { - var tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos); - recordSourceMapSpan(tokenStartPos); - var tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn); - recordSourceMapSpan(tokenEndPos); - return tokenEndPos; - } - function recordNewSourceFileStart(node) { - // Add the file to tsFilePaths - // If sourceroot option: Use the relative path corresponding to the common directory path - // otherwise source locations relative to map file location - var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; - sourceMapData.sourceMapSources.push(ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, node.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true)); - sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1; - // The one that can be used from program to get the actual source file - sourceMapData.inputSourceFileNames.push(node.fileName); - } - function recordScopeNameOfNode(node, scopeName) { - function recordScopeNameIndex(scopeNameIndex) { - sourceMapNameIndices.push(scopeNameIndex); - } - function recordScopeNameStart(scopeName) { - var scopeNameIndex = -1; - if (scopeName) { - var parentIndex = getSourceMapNameIndex(); - if (parentIndex !== -1) { - // Child scopes are always shown with a dot (even if they have no name), - // unless it is a computed property. Then it is shown with brackets, - // but the brackets are included in the name. - var name_3 = node.name; - if (!name_3 || name_3.kind !== 127 /* ComputedPropertyName */) { - scopeName = "." + scopeName; - } - scopeName = sourceMapData.sourceMapNames[parentIndex] + scopeName; - } - scopeNameIndex = ts.getProperty(sourceMapNameIndexMap, scopeName); - if (scopeNameIndex === undefined) { - scopeNameIndex = sourceMapData.sourceMapNames.length; - sourceMapData.sourceMapNames.push(scopeName); - sourceMapNameIndexMap[scopeName] = scopeNameIndex; - } - } - recordScopeNameIndex(scopeNameIndex); - } - if (scopeName) { - // The scope was already given a name use it - recordScopeNameStart(scopeName); - } - else if (node.kind === 200 /* FunctionDeclaration */ || - node.kind === 162 /* FunctionExpression */ || - node.kind === 134 /* MethodDeclaration */ || - node.kind === 133 /* MethodSignature */ || - node.kind === 136 /* GetAccessor */ || - node.kind === 137 /* SetAccessor */ || - node.kind === 205 /* ModuleDeclaration */ || - node.kind === 201 /* ClassDeclaration */ || - node.kind === 204 /* EnumDeclaration */) { - // Declaration and has associated name use it - if (node.name) { - var name_4 = node.name; - // For computed property names, the text will include the brackets - scopeName = name_4.kind === 127 /* ComputedPropertyName */ - ? ts.getTextOfNode(name_4) - : node.name.text; - } - recordScopeNameStart(scopeName); - } - else { - // Block just use the name from upper level scope - recordScopeNameIndex(getSourceMapNameIndex()); - } - } - function recordScopeNameEnd() { - sourceMapNameIndices.pop(); - } - ; - function writeCommentRangeWithMap(curentSourceFile, writer, comment, newLine) { - recordSourceMapSpan(comment.pos); - ts.writeCommentRange(currentSourceFile, writer, comment, newLine); - recordSourceMapSpan(comment.end); - } - function serializeSourceMapContents(version, file, sourceRoot, sources, names, mappings) { - if (typeof JSON !== "undefined") { - return JSON.stringify({ - version: version, - file: file, - sourceRoot: sourceRoot, - sources: sources, - names: names, - mappings: mappings - }); - } - return "{\"version\":" + version + ",\"file\":\"" + ts.escapeString(file) + "\",\"sourceRoot\":\"" + ts.escapeString(sourceRoot) + "\",\"sources\":[" + serializeStringArray(sources) + "],\"names\":[" + serializeStringArray(names) + "],\"mappings\":\"" + ts.escapeString(mappings) + "\"}"; - function serializeStringArray(list) { - var output = ""; - for (var i = 0, n = list.length; i < n; i++) { - if (i) { - output += ","; - } - output += "\"" + ts.escapeString(list[i]) + "\""; - } - return output; - } - } - function writeJavaScriptAndSourceMapFile(emitOutput, writeByteOrderMark) { - // Write source map file - encodeLastRecordedSourceMapSpan(); - ts.writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents(3, sourceMapData.sourceMapFile, sourceMapData.sourceMapSourceRoot, sourceMapData.sourceMapSources, sourceMapData.sourceMapNames, sourceMapData.sourceMapMappings), false); - sourceMapDataList.push(sourceMapData); - // Write sourcemap url to the js file and write the js file - writeJavaScriptFile(emitOutput + "//# sourceMappingURL=" + sourceMapData.jsSourceMappingURL, writeByteOrderMark); - } - // Initialize source map data - var sourceMapJsFile = ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)); - sourceMapData = { - sourceMapFilePath: jsFilePath + ".map", - jsSourceMappingURL: sourceMapJsFile + ".map", - sourceMapFile: sourceMapJsFile, - sourceMapSourceRoot: compilerOptions.sourceRoot || "", - sourceMapSources: [], - inputSourceFileNames: [], - sourceMapNames: [], - sourceMapMappings: "", - sourceMapDecodedMappings: [] - }; - // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the - // relative paths of the sources list in the sourcemap - sourceMapData.sourceMapSourceRoot = ts.normalizeSlashes(sourceMapData.sourceMapSourceRoot); - if (sourceMapData.sourceMapSourceRoot.length && sourceMapData.sourceMapSourceRoot.charCodeAt(sourceMapData.sourceMapSourceRoot.length - 1) !== 47 /* slash */) { - sourceMapData.sourceMapSourceRoot += ts.directorySeparator; - } - if (compilerOptions.mapRoot) { - sourceMapDir = ts.normalizeSlashes(compilerOptions.mapRoot); - if (root) { - // For modules or multiple emit files the mapRoot will have directory structure like the sources - // So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map - sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(root, host, sourceMapDir)); - } - if (!ts.isRootedDiskPath(sourceMapDir) && !ts.isUrl(sourceMapDir)) { - // The relative paths are relative to the common directory - sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir); - sourceMapData.jsSourceMappingURL = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(jsFilePath)), ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), host.getCurrentDirectory(), host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ true); - } - else { - sourceMapData.jsSourceMappingURL = ts.combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL); - } - } - else { - sourceMapDir = ts.getDirectoryPath(ts.normalizePath(jsFilePath)); - } - function emitNodeWithSourceMap(node, allowGeneratedIdentifiers) { - if (node) { - if (ts.nodeIsSynthesized(node)) { - return emitNodeWithoutSourceMap(node, false); - } - if (node.kind != 227 /* SourceFile */) { - recordEmitNodeStartSpan(node); - emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers); - recordEmitNodeEndSpan(node); - } - else { - recordNewSourceFileStart(node); - emitNodeWithoutSourceMap(node, false); - } - } - } - writeEmittedFiles = writeJavaScriptAndSourceMapFile; - emit = emitNodeWithSourceMap; - emitStart = recordEmitNodeStartSpan; - emitEnd = recordEmitNodeEndSpan; - emitToken = writeTextWithSpanRecord; - scopeEmitStart = recordScopeNameOfNode; - scopeEmitEnd = recordScopeNameEnd; - writeComment = writeCommentRangeWithMap; - } - function writeJavaScriptFile(emitOutput, writeByteOrderMark) { - ts.writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark); - } - // Create a temporary variable with a unique unused name. - function createTempVariable(flags) { - var result = ts.createSynthesizedNode(65 /* Identifier */); - result.text = makeTempVariableName(flags); - return result; - } - function recordTempDeclaration(name) { - if (!tempVariables) { - tempVariables = []; - } - tempVariables.push(name); - } - function createAndRecordTempVariable(flags) { - var temp = createTempVariable(flags); - recordTempDeclaration(temp); - return temp; - } - function emitTempDeclarations(newLine) { - if (tempVariables) { - if (newLine) { - writeLine(); - } - else { - write(" "); - } - write("var "); - emitCommaList(tempVariables); - write(";"); - } - } - function emitTokenText(tokenKind, startPos, emitFn) { - var tokenString = ts.tokenToString(tokenKind); - if (emitFn) { - emitFn(); - } - else { - write(tokenString); - } - return startPos + tokenString.length; - } - function emitOptional(prefix, node) { - if (node) { - write(prefix); - emit(node); - } - } - function emitParenthesizedIf(node, parenthesized) { - if (parenthesized) { - write("("); - } - emit(node); - if (parenthesized) { - write(")"); - } - } - function emitTrailingCommaIfPresent(nodeList) { - if (nodeList.hasTrailingComma) { - write(","); - } - } - function emitLinePreservingList(parent, nodes, allowTrailingComma, spacesBetweenBraces) { - ts.Debug.assert(nodes.length > 0); - increaseIndent(); - if (nodeStartPositionsAreOnSameLine(parent, nodes[0])) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - for (var i = 0, n = nodes.length; i < n; i++) { - if (i) { - if (nodeEndIsOnSameLineAsNodeStart(nodes[i - 1], nodes[i])) { - write(", "); - } - else { - write(","); - writeLine(); - } - } - emit(nodes[i]); - } - if (nodes.hasTrailingComma && allowTrailingComma) { - write(","); - } - decreaseIndent(); - if (nodeEndPositionsAreOnSameLine(parent, ts.lastOrUndefined(nodes))) { - if (spacesBetweenBraces) { - write(" "); - } - } - else { - writeLine(); - } - } - function emitList(nodes, start, count, multiLine, trailingComma, leadingComma, noTrailingNewLine, emitNode) { - if (!emitNode) { - emitNode = emit; - } - for (var i = 0; i < count; i++) { - if (multiLine) { - if (i || leadingComma) { - write(","); - } - writeLine(); - } - else { - if (i || leadingComma) { - write(", "); - } - } - emitNode(nodes[start + i]); - leadingComma = true; - } - if (trailingComma) { - write(","); - } - if (multiLine && !noTrailingNewLine) { - writeLine(); - } - return count; - } - function emitCommaList(nodes) { - if (nodes) { - emitList(nodes, 0, nodes.length, false, false); - } - } - function emitLines(nodes) { - emitLinesStartingAt(nodes, 0); - } - function emitLinesStartingAt(nodes, startIndex) { - for (var i = startIndex; i < nodes.length; i++) { - writeLine(); - emit(nodes[i]); - } - } - function isBinaryOrOctalIntegerLiteral(node, text) { - if (node.kind === 7 /* NumericLiteral */ && text.length > 1) { - switch (text.charCodeAt(1)) { - case 98 /* b */: - case 66 /* B */: - case 111 /* o */: - case 79 /* O */: - return true; - } - } - return false; - } - function emitLiteral(node) { - var text = getLiteralText(node); - if (compilerOptions.sourceMap && (node.kind === 8 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); - } - else if (languageVersion < 2 /* ES6 */ && isBinaryOrOctalIntegerLiteral(node, text)) { - write(node.text); - } - else { - write(text); - } - } - function getLiteralText(node) { - // Any template literal or string literal with an extended escape - // (e.g. "\u{0067}") will need to be downleveled as a escaped string literal. - if (languageVersion < 2 /* ES6 */ && (ts.isTemplateLiteralKind(node.kind) || node.hasExtendedUnicodeEscape)) { - return getQuotedEscapedLiteralText('"', node.text, '"'); - } - // If we don't need to downlevel and we can reach the original source text using - // the node's parent reference, then simply get the text as it was originally written. - if (node.parent) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - } - // If we can't reach the original source text, use the canonical form if it's a number, - // or an escaped quoted form of the original text if it's string-like. - switch (node.kind) { - case 8 /* StringLiteral */: - return getQuotedEscapedLiteralText('"', node.text, '"'); - case 10 /* NoSubstitutionTemplateLiteral */: - return getQuotedEscapedLiteralText('`', node.text, '`'); - case 11 /* TemplateHead */: - return getQuotedEscapedLiteralText('`', node.text, '${'); - case 12 /* TemplateMiddle */: - return getQuotedEscapedLiteralText('}', node.text, '${'); - case 13 /* TemplateTail */: - return getQuotedEscapedLiteralText('}', node.text, '`'); - case 7 /* NumericLiteral */: - return node.text; - } - ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for."); - } - function getQuotedEscapedLiteralText(leftQuote, text, rightQuote) { - return leftQuote + ts.escapeNonAsciiCharacters(ts.escapeString(text)) + rightQuote; - } - function emitDownlevelRawTemplateLiteral(node) { - // Find original source text, since we need to emit the raw strings of the tagged template. - // The raw strings contain the (escaped) strings of what the user wrote. - // Examples: `\n` is converted to "\\n", a template string with a newline to "\n". - var text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node); - // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"), - // thus we need to remove those characters. - // First template piece starts with "`", others with "}" - // Last template piece ends with "`", others with "${" - var isLast = node.kind === 10 /* NoSubstitutionTemplateLiteral */ || node.kind === 13 /* TemplateTail */; - text = text.substring(1, text.length - (isLast ? 1 : 2)); - // Newline normalization: - // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's - // and LineTerminatorSequences are normalized to for both TV and TRV. - text = text.replace(/\r\n?/g, "\n"); - text = ts.escapeString(text); - write('"' + text + '"'); - } - function emitDownlevelTaggedTemplateArray(node, literalEmitter) { - write("["); - if (node.template.kind === 10 /* NoSubstitutionTemplateLiteral */) { - literalEmitter(node.template); - } - else { - literalEmitter(node.template.head); - ts.forEach(node.template.templateSpans, function (child) { - write(", "); - literalEmitter(child.literal); - }); - } - write("]"); - } - function emitDownlevelTaggedTemplate(node) { - var tempVariable = createAndRecordTempVariable(0 /* Auto */); - write("("); - emit(tempVariable); - write(" = "); - emitDownlevelTaggedTemplateArray(node, emit); - write(", "); - emit(tempVariable); - write(".raw = "); - emitDownlevelTaggedTemplateArray(node, emitDownlevelRawTemplateLiteral); - write(", "); - emitParenthesizedIf(node.tag, needsParenthesisForPropertyAccessOrInvocation(node.tag)); - write("("); - emit(tempVariable); - // Now we emit the expressions - if (node.template.kind === 171 /* TemplateExpression */) { - ts.forEach(node.template.templateSpans, function (templateSpan) { - write(", "); - var needsParens = templateSpan.expression.kind === 169 /* BinaryExpression */ - && templateSpan.expression.operatorToken.kind === 23 /* CommaToken */; - emitParenthesizedIf(templateSpan.expression, needsParens); - }); - } - write("))"); - } - function emitTemplateExpression(node) { - // In ES6 mode and above, we can simply emit each portion of a template in order, but in - // ES3 & ES5 we must convert the template expression into a series of string concatenations. - if (languageVersion >= 2 /* ES6 */) { - ts.forEachChild(node, emit); - return; - } - var emitOuterParens = ts.isExpression(node.parent) - && templateNeedsParens(node, node.parent); - if (emitOuterParens) { - write("("); - } - var headEmitted = false; - if (shouldEmitTemplateHead()) { - emitLiteral(node.head); - headEmitted = true; - } - for (var i = 0, n = node.templateSpans.length; i < n; i++) { - var templateSpan = node.templateSpans[i]; - // Check if the expression has operands and binds its operands less closely than binary '+'. - // If it does, we need to wrap the expression in parentheses. Otherwise, something like - // `abc${ 1 << 2 }` - // becomes - // "abc" + 1 << 2 + "" - // which is really - // ("abc" + 1) << (2 + "") - // rather than - // "abc" + (1 << 2) + "" - var needsParens = templateSpan.expression.kind !== 161 /* ParenthesizedExpression */ - && comparePrecedenceToBinaryPlus(templateSpan.expression) !== 1 /* GreaterThan */; - if (i > 0 || headEmitted) { - // If this is the first span and the head was not emitted, then this templateSpan's - // expression will be the first to be emitted. Don't emit the preceding ' + ' in that - // case. - write(" + "); - } - emitParenthesizedIf(templateSpan.expression, needsParens); - // Only emit if the literal is non-empty. - // The binary '+' operator is left-associative, so the first string concatenation - // with the head will force the result up to this point to be a string. - // Emitting a '+ ""' has no semantic effect for middles and tails. - if (templateSpan.literal.text.length !== 0) { - write(" + "); - emitLiteral(templateSpan.literal); - } - } - if (emitOuterParens) { - write(")"); - } - function shouldEmitTemplateHead() { - // If this expression has an empty head literal and the first template span has a non-empty - // literal, then emitting the empty head literal is not necessary. - // `${ foo } and ${ bar }` - // can be emitted as - // foo + " and " + bar - // This is because it is only required that one of the first two operands in the emit - // output must be a string literal, so that the other operand and all following operands - // are forced into strings. - // - // If the first template span has an empty literal, then the head must still be emitted. - // `${ foo }${ bar }` - // must still be emitted as - // "" + foo + bar - // There is always atleast one templateSpan in this code path, since - // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral() - ts.Debug.assert(node.templateSpans.length !== 0); - return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0; - } - function templateNeedsParens(template, parent) { - switch (parent.kind) { - case 157 /* CallExpression */: - case 158 /* NewExpression */: - return parent.expression === template; - case 159 /* TaggedTemplateExpression */: - case 161 /* ParenthesizedExpression */: - return false; - default: - return comparePrecedenceToBinaryPlus(parent) !== -1 /* LessThan */; - } - } - /** - * Returns whether the expression has lesser, greater, - * or equal precedence to the binary '+' operator - */ - function comparePrecedenceToBinaryPlus(expression) { - // All binary expressions have lower precedence than '+' apart from '*', '/', and '%' - // which have greater precedence and '-' which has equal precedence. - // All unary operators have a higher precedence apart from yield. - // Arrow functions and conditionals have a lower precedence, - // although we convert the former into regular function expressions in ES5 mode, - // and in ES6 mode this function won't get called anyway. - // - // TODO (drosen): Note that we need to account for the upcoming 'yield' and - // spread ('...') unary operators that are anticipated for ES6. - switch (expression.kind) { - case 169 /* BinaryExpression */: - switch (expression.operatorToken.kind) { - case 35 /* AsteriskToken */: - case 36 /* SlashToken */: - case 37 /* PercentToken */: - return 1 /* GreaterThan */; - case 33 /* PlusToken */: - case 34 /* MinusToken */: - return 0 /* EqualTo */; - default: - return -1 /* LessThan */; - } - case 172 /* YieldExpression */: - case 170 /* ConditionalExpression */: - return -1 /* LessThan */; - default: - return 1 /* GreaterThan */; - } - } - } - function emitTemplateSpan(span) { - emit(span.expression); - emit(span.literal); - } - // This function specifically handles numeric/string literals for enum and accessor 'identifiers'. - // In a sense, it does not actually emit identifiers as much as it declares a name for a specific property. - // For example, this is utilized when feeding in a result to Object.defineProperty. - function emitExpressionForPropertyName(node) { - ts.Debug.assert(node.kind !== 152 /* BindingElement */); - if (node.kind === 8 /* StringLiteral */) { - emitLiteral(node); - } - else if (node.kind === 127 /* ComputedPropertyName */) { - // if this is a decorated computed property, we will need to capture the result - // of the property expression so that we can apply decorators later. This is to ensure - // we don't introduce unintended side effects: - // - // class C { - // [_a = x]() { } - // } - // - // The emit for the decorated computed property decorator is: - // - // Object.defineProperty(C.prototype, _a, __decorate([dec], C.prototype, _a, Object.getOwnPropertyDescriptor(C.prototype, _a))); - // - if (ts.nodeIsDecorated(node.parent)) { - if (!computedPropertyNamesToGeneratedNames) { - computedPropertyNamesToGeneratedNames = []; - } - var generatedName = computedPropertyNamesToGeneratedNames[ts.getNodeId(node)]; - if (generatedName) { - // we have already generated a variable for this node, write that value instead. - write(generatedName); - return; - } - generatedName = createAndRecordTempVariable(0 /* Auto */).text; - computedPropertyNamesToGeneratedNames[ts.getNodeId(node)] = generatedName; - write(generatedName); - write(" = "); - } - emit(node.expression); - } - else { - write("\""); - if (node.kind === 7 /* NumericLiteral */) { - write(node.text); - } - else { - writeTextOfNode(currentSourceFile, node); - } - write("\""); - } - } - function isNotExpressionIdentifier(node) { - var parent = node.parent; - switch (parent.kind) { - case 129 /* Parameter */: - case 198 /* VariableDeclaration */: - case 152 /* BindingElement */: - case 132 /* PropertyDeclaration */: - case 131 /* PropertySignature */: - case 224 /* PropertyAssignment */: - case 225 /* ShorthandPropertyAssignment */: - case 226 /* EnumMember */: - case 134 /* MethodDeclaration */: - case 133 /* MethodSignature */: - case 200 /* FunctionDeclaration */: - case 136 /* GetAccessor */: - case 137 /* SetAccessor */: - case 162 /* FunctionExpression */: - case 201 /* ClassDeclaration */: - case 202 /* InterfaceDeclaration */: - case 204 /* EnumDeclaration */: - case 205 /* ModuleDeclaration */: - case 208 /* ImportEqualsDeclaration */: - case 210 /* ImportClause */: - case 211 /* NamespaceImport */: - return parent.name === node; - case 213 /* ImportSpecifier */: - case 217 /* ExportSpecifier */: - return parent.name === node || parent.propertyName === node; - case 190 /* BreakStatement */: - case 189 /* ContinueStatement */: - case 214 /* ExportAssignment */: - return false; - case 194 /* LabeledStatement */: - return node.parent.label === node; - } - } - function emitExpressionIdentifier(node) { - var substitution = resolver.getExpressionNameSubstitution(node, getGeneratedNameForNode); - if (substitution) { - write(substitution); - } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function getGeneratedNameForIdentifier(node) { - if (ts.nodeIsSynthesized(node) || !blockScopedVariableToGeneratedName) { - return undefined; - } - var variableId = resolver.getBlockScopedVariableId(node); - if (variableId === undefined) { - return undefined; - } - return blockScopedVariableToGeneratedName[variableId]; - } - function emitIdentifier(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers) { - var generatedName = getGeneratedNameForIdentifier(node); - if (generatedName) { - write(generatedName); - return; - } - } - if (!node.parent) { - write(node.text); - } - else if (!isNotExpressionIdentifier(node)) { - emitExpressionIdentifier(node); - } - else { - writeTextOfNode(currentSourceFile, node); - } - } - function emitThis(node) { - if (resolver.getNodeCheckFlags(node) & 2 /* LexicalThis */) { - write("_this"); - } - else { - write("this"); - } - } - function emitSuper(node) { - if (languageVersion >= 2 /* ES6 */) { - write("super"); - } - else { - var flags = resolver.getNodeCheckFlags(node); - if (flags & 16 /* SuperInstance */) { - write("_super.prototype"); - } - else { - write("_super"); - } - } - } - function emitObjectBindingPattern(node) { - write("{ "); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write(" }"); - } - function emitArrayBindingPattern(node) { - write("["); - var elements = node.elements; - emitList(elements, 0, elements.length, false, elements.hasTrailingComma); - write("]"); - } - function emitBindingElement(node) { - if (node.propertyName) { - emit(node.propertyName, false); - write(": "); - } - if (node.dotDotDotToken) { - write("..."); - } - if (ts.isBindingPattern(node.name)) { - emit(node.name); - } - else { - emitModuleMemberName(node); - } - emitOptional(" = ", node.initializer); - } - function emitSpreadElementExpression(node) { - write("..."); - emit(node.expression); - } - function emitYieldExpression(node) { - write(ts.tokenToString(110 /* YieldKeyword */)); - if (node.asteriskToken) { - write("*"); - } - if (node.expression) { - write(" "); - emit(node.expression); - } - } - function needsParenthesisForPropertyAccessOrInvocation(node) { - switch (node.kind) { - case 65 /* Identifier */: - case 153 /* ArrayLiteralExpression */: - case 155 /* PropertyAccessExpression */: - case 156 /* ElementAccessExpression */: - case 157 /* CallExpression */: - case 161 /* ParenthesizedExpression */: - // This list is not exhaustive and only includes those cases that are relevant - // to the check in emitArrayLiteral. More cases can be added as needed. - return false; - } - return true; - } - function emitListWithSpread(elements, multiLine, trailingComma) { - var pos = 0; - var group = 0; - var length = elements.length; - while (pos < length) { - // Emit using the pattern .concat(, , ...) - if (group === 1) { - write(".concat("); - } - else if (group > 1) { - write(", "); - } - var e = elements[pos]; - if (e.kind === 173 /* SpreadElementExpression */) { - e = e.expression; - emitParenthesizedIf(e, group === 0 && needsParenthesisForPropertyAccessOrInvocation(e)); - pos++; - } - else { - var i = pos; - while (i < length && elements[i].kind !== 173 /* SpreadElementExpression */) { - i++; - } - write("["); - if (multiLine) { - increaseIndent(); - } - emitList(elements, pos, i - pos, multiLine, trailingComma && i === length); - if (multiLine) { - decreaseIndent(); - } - write("]"); - pos = i; - } - group++; - } - if (group > 1) { - write(")"); - } - } - function isSpreadElementExpression(node) { - return node.kind === 173 /* SpreadElementExpression */; - } - function emitArrayLiteral(node) { - var elements = node.elements; - if (elements.length === 0) { - write("[]"); - } - else if (languageVersion >= 2 /* ES6 */ || !ts.forEach(elements, isSpreadElementExpression)) { - write("["); - emitLinePreservingList(node, node.elements, elements.hasTrailingComma, false); - write("]"); - } - else { - emitListWithSpread(elements, (node.flags & 512 /* MultiLine */) !== 0, - /*trailingComma*/ elements.hasTrailingComma); - } - } - function emitObjectLiteralBody(node, numElements) { - if (numElements === 0) { - write("{}"); - return; - } - write("{"); - if (numElements > 0) { - var properties = node.properties; - // If we are not doing a downlevel transformation for object literals, - // then try to preserve the original shape of the object literal. - // Otherwise just try to preserve the formatting. - if (numElements === properties.length) { - emitLinePreservingList(node, properties, languageVersion >= 1 /* ES5 */, true); - } - else { - var multiLine = (node.flags & 512 /* MultiLine */) !== 0; - if (!multiLine) { - write(" "); - } - else { - increaseIndent(); - } - emitList(properties, 0, numElements, multiLine, false); - if (!multiLine) { - write(" "); - } - else { - decreaseIndent(); - } - } - } - write("}"); - } - function emitDownlevelObjectLiteralWithComputedProperties(node, firstComputedPropertyIndex) { - var multiLine = (node.flags & 512 /* MultiLine */) !== 0; - var properties = node.properties; - write("("); - if (multiLine) { - increaseIndent(); - } - // For computed properties, we need to create a unique handle to the object - // literal so we can modify it without risking internal assignments tainting the object. - var tempVar = createAndRecordTempVariable(0 /* Auto */); - // Write out the first non-computed properties - // (or all properties if none of them are computed), - // then emit the rest through indexing on the temp variable. - emit(tempVar); - write(" = "); - emitObjectLiteralBody(node, firstComputedPropertyIndex); - for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); - var property = properties[i]; - emitStart(property); - if (property.kind === 136 /* GetAccessor */ || property.kind === 137 /* SetAccessor */) { - // TODO (drosen): Reconcile with 'emitMemberFunctions'. - var accessors = ts.getAllAccessorDeclarations(node.properties, property); - if (property !== accessors.firstAccessor) { - continue; - } - write("Object.defineProperty("); - emit(tempVar); - write(", "); - emitStart(node.name); - emitExpressionForPropertyName(property.name); - emitEnd(property.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("})"); - emitEnd(property); - } - else { - emitLeadingComments(property); - emitStart(property.name); - emit(tempVar); - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - if (property.kind === 224 /* PropertyAssignment */) { - emit(property.initializer); - } - else if (property.kind === 225 /* ShorthandPropertyAssignment */) { - emitExpressionIdentifier(property.name); - } - else if (property.kind === 134 /* MethodDeclaration */) { - emitFunctionDeclaration(property); - } - else { - ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); - } - } - emitEnd(property); - } - writeComma(); - emit(tempVar); - if (multiLine) { - decreaseIndent(); - writeLine(); - } - write(")"); - function writeComma() { - if (multiLine) { - write(","); - writeLine(); - } - else { - write(", "); - } - } - } - function emitObjectLiteral(node) { - var properties = node.properties; - if (languageVersion < 2 /* ES6 */) { - var numProperties = properties.length; - // Find the first computed property. - // Everything until that point can be emitted as part of the initial object literal. - var numInitialNonComputedProperties = numProperties; - for (var i = 0, n = properties.length; i < n; i++) { - if (properties[i].name.kind === 127 /* ComputedPropertyName */) { - numInitialNonComputedProperties = i; - break; - } - } - var hasComputedProperty = numInitialNonComputedProperties !== properties.length; - if (hasComputedProperty) { - emitDownlevelObjectLiteralWithComputedProperties(node, numInitialNonComputedProperties); - return; - } - } - // Ordinary case: either the object has no computed properties - // or we're compiling with an ES6+ target. - emitObjectLiteralBody(node, properties.length); - } - function createBinaryExpression(left, operator, right, startsOnNewLine) { - var result = ts.createSynthesizedNode(169 /* BinaryExpression */, startsOnNewLine); - result.operatorToken = ts.createSynthesizedNode(operator); - result.left = left; - result.right = right; - return result; - } - function createPropertyAccessExpression(expression, name) { - var result = ts.createSynthesizedNode(155 /* PropertyAccessExpression */); - result.expression = parenthesizeForAccess(expression); - result.dotToken = ts.createSynthesizedNode(20 /* DotToken */); - result.name = name; - return result; - } - function createElementAccessExpression(expression, argumentExpression) { - var result = ts.createSynthesizedNode(156 /* ElementAccessExpression */); - result.expression = parenthesizeForAccess(expression); - result.argumentExpression = argumentExpression; - return result; - } - function parenthesizeForAccess(expr) { - // isLeftHandSideExpression is almost the correct criterion for when it is not necessary - // to parenthesize the expression before a dot. The known exceptions are: - // - // NewExpression: - // new C.x -> not the same as (new C).x - // NumberLiteral - // 1.x -> not the same as (1).x - // - if (ts.isLeftHandSideExpression(expr) && expr.kind !== 158 /* NewExpression */ && expr.kind !== 7 /* NumericLiteral */) { - return expr; - } - var node = ts.createSynthesizedNode(161 /* ParenthesizedExpression */); - node.expression = expr; - return node; - } - function emitComputedPropertyName(node) { - write("["); - emitExpressionForPropertyName(node); - write("]"); - } - function emitMethod(node) { - if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { - write("*"); - } - emit(node.name, false); - if (languageVersion < 2 /* ES6 */) { - write(": function "); - } - emitSignatureAndBody(node); - } - function emitPropertyAssignment(node) { - emit(node.name, false); - write(": "); - emit(node.initializer); - } - function emitShorthandPropertyAssignment(node) { - emit(node.name, false); - // If short-hand property has a prefix, then regardless of the target version, we will emit it as normal property assignment. For example: - // module m { - // export let y; - // } - // module m { - // export let obj = { y }; - // } - // The short-hand property in obj need to emit as such ... = { y : m.y } regardless of the TargetScript version - if (languageVersion < 2 /* ES6 */) { - // Emit identifier as an identifier - write(": "); - var generatedName = getGeneratedNameForIdentifier(node.name); - if (generatedName) { - write(generatedName); - } - else { - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); - } - } - else if (resolver.getExpressionNameSubstitution(node.name, getGeneratedNameForNode)) { - // Emit identifier as an identifier - write(": "); - // Even though this is stored as identifier treat it as an expression - // Short-hand, { x }, is equivalent of normal form { x: x } - emitExpressionIdentifier(node.name); - } - } - function tryEmitConstantValue(node) { - if (compilerOptions.separateCompilation) { - // do not inline enum values in separate compilation mode - return false; - } - var constantValue = resolver.getConstantValue(node); - if (constantValue !== undefined) { - write(constantValue.toString()); - if (!compilerOptions.removeComments) { - var propertyName = node.kind === 155 /* PropertyAccessExpression */ ? ts.declarationNameToString(node.name) : ts.getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } - // Returns 'true' if the code was actually indented, false otherwise. - // If the code is not indented, an optional valueToWriteWhenNotIndenting will be - // emitted instead. - function indentIfOnDifferentLines(parent, node1, node2, valueToWriteWhenNotIndenting) { - var realNodesAreOnDifferentLines = !ts.nodeIsSynthesized(parent) && !nodeEndIsOnSameLineAsNodeStart(node1, node2); - // Always use a newline for synthesized code if the synthesizer desires it. - var synthesizedNodeIsOnDifferentLine = synthesizedNodeStartsOnNewLine(node2); - if (realNodesAreOnDifferentLines || synthesizedNodeIsOnDifferentLine) { - increaseIndent(); - writeLine(); - return true; - } - else { - if (valueToWriteWhenNotIndenting) { - write(valueToWriteWhenNotIndenting); - } - return false; - } - } - function emitPropertyAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - emit(node.expression); - var indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken); - write("."); - var indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name); - emit(node.name, false); - decreaseIndentIf(indentedBeforeDot, indentedAfterDot); - } - function emitQualifiedName(node) { - emit(node.left); - write("."); - emit(node.right); - } - function emitIndexedAccess(node) { - if (tryEmitConstantValue(node)) { - return; - } - emit(node.expression); - write("["); - emit(node.argumentExpression); - write("]"); - } - function hasSpreadElement(elements) { - return ts.forEach(elements, function (e) { return e.kind === 173 /* SpreadElementExpression */; }); - } - function skipParentheses(node) { - while (node.kind === 161 /* ParenthesizedExpression */ || node.kind === 160 /* TypeAssertionExpression */) { - node = node.expression; - } - return node; - } - function emitCallTarget(node) { - if (node.kind === 65 /* Identifier */ || node.kind === 93 /* ThisKeyword */ || node.kind === 91 /* SuperKeyword */) { - emit(node); - return node; - } - var temp = createAndRecordTempVariable(0 /* Auto */); - write("("); - emit(temp); - write(" = "); - emit(node); - write(")"); - return temp; - } - function emitCallWithSpread(node) { - var target; - var expr = skipParentheses(node.expression); - if (expr.kind === 155 /* PropertyAccessExpression */) { - // Target will be emitted as "this" argument - target = emitCallTarget(expr.expression); - write("."); - emit(expr.name); - } - else if (expr.kind === 156 /* ElementAccessExpression */) { - // Target will be emitted as "this" argument - target = emitCallTarget(expr.expression); - write("["); - emit(expr.argumentExpression); - write("]"); - } - else if (expr.kind === 91 /* SuperKeyword */) { - target = expr; - write("_super"); - } - else { - emit(node.expression); - } - write(".apply("); - if (target) { - if (target.kind === 91 /* SuperKeyword */) { - // Calls of form super(...) and super.foo(...) - emitThis(target); - } - else { - // Calls of form obj.foo(...) - emit(target); - } - } - else { - // Calls of form foo(...) - write("void 0"); - } - write(", "); - emitListWithSpread(node.arguments, false, false); - write(")"); - } - function emitCallExpression(node) { - if (languageVersion < 2 /* ES6 */ && hasSpreadElement(node.arguments)) { - emitCallWithSpread(node); - return; - } - var superCall = false; - if (node.expression.kind === 91 /* SuperKeyword */) { - emitSuper(node.expression); - superCall = true; - } - else { - emit(node.expression); - superCall = node.expression.kind === 155 /* PropertyAccessExpression */ && node.expression.expression.kind === 91 /* SuperKeyword */; - } - if (superCall && languageVersion < 2 /* ES6 */) { - write(".call("); - emitThis(node.expression); - if (node.arguments.length) { - write(", "); - emitCommaList(node.arguments); - } - write(")"); - } - else { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitNewExpression(node) { - write("new "); - emit(node.expression); - if (node.arguments) { - write("("); - emitCommaList(node.arguments); - write(")"); - } - } - function emitTaggedTemplateExpression(node) { - if (languageVersion >= 2 /* ES6 */) { - emit(node.tag); - write(" "); - emit(node.template); - } - else { - emitDownlevelTaggedTemplate(node); - } - } - function emitParenExpression(node) { - if (!node.parent || node.parent.kind !== 163 /* ArrowFunction */) { - if (node.expression.kind === 160 /* TypeAssertionExpression */) { - var operand = node.expression.expression; - // Make sure we consider all nested cast expressions, e.g.: - // (-A).x; - while (operand.kind == 160 /* TypeAssertionExpression */) { - operand = operand.expression; - } - // We have an expression of the form: (SubExpr) - // Emitting this as (SubExpr) is really not desirable. We would like to emit the subexpr as is. - // Omitting the parentheses, however, could cause change in the semantics of the generated - // code if the casted expression has a lower precedence than the rest of the expression, e.g.: - // (new A).foo should be emitted as (new A).foo and not new A.foo - // (typeof A).toString() should be emitted as (typeof A).toString() and not typeof A.toString() - // new (A()) should be emitted as new (A()) and not new A() - // (function foo() { })() should be emitted as an IIF (function foo(){})() and not declaration function foo(){} () - if (operand.kind !== 167 /* PrefixUnaryExpression */ && - operand.kind !== 166 /* VoidExpression */ && - operand.kind !== 165 /* TypeOfExpression */ && - operand.kind !== 164 /* DeleteExpression */ && - operand.kind !== 168 /* PostfixUnaryExpression */ && - operand.kind !== 158 /* NewExpression */ && - !(operand.kind === 157 /* CallExpression */ && node.parent.kind === 158 /* NewExpression */) && - !(operand.kind === 162 /* FunctionExpression */ && node.parent.kind === 157 /* CallExpression */)) { - emit(operand); - return; - } - } - } - write("("); - emit(node.expression); - write(")"); - } - function emitDeleteExpression(node) { - write(ts.tokenToString(74 /* DeleteKeyword */)); - write(" "); - emit(node.expression); - } - function emitVoidExpression(node) { - write(ts.tokenToString(99 /* VoidKeyword */)); - write(" "); - emit(node.expression); - } - function emitTypeOfExpression(node) { - write(ts.tokenToString(97 /* TypeOfKeyword */)); - write(" "); - emit(node.expression); - } - function isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node) { - if (!isCurrentFileSystemExternalModule() || node.kind !== 65 /* Identifier */ || ts.nodeIsSynthesized(node)) { - return false; - } - var isVariableDeclarationOrBindingElement = node.parent && (node.parent.kind === 198 /* VariableDeclaration */ || node.parent.kind === 152 /* BindingElement */); - var targetDeclaration = isVariableDeclarationOrBindingElement - ? node.parent - : resolver.getReferencedValueDeclaration(node); - return isSourceFileLevelDeclarationInSystemExternalModule(targetDeclaration, true); - } - function emitPrefixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - if (exportChanged) { - // emit - // ++x - // as - // exports('x', ++x) - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - } - write(ts.tokenToString(node.operator)); - // In some cases, we need to emit a space between the operator and the operand. One obvious case - // is when the operator is an identifier, like delete or typeof. We also need to do this for plus - // and minus expressions in certain cases. Specifically, consider the following two cases (parens - // are just for clarity of exposition, and not part of the source code): - // - // (+(+1)) - // (+(++1)) - // - // We need to emit a space in both cases. In the first case, the absence of a space will make - // the resulting expression a prefix increment operation. And in the second, it will make the resulting - // expression a prefix increment whose operand is a plus expression - (++(+x)) - // The same is true of minus of course. - if (node.operand.kind === 167 /* PrefixUnaryExpression */) { - var operand = node.operand; - if (node.operator === 33 /* PlusToken */ && (operand.operator === 33 /* PlusToken */ || operand.operator === 38 /* PlusPlusToken */)) { - write(" "); - } - else if (node.operator === 34 /* MinusToken */ && (operand.operator === 34 /* MinusToken */ || operand.operator === 39 /* MinusMinusToken */)) { - write(" "); - } - } - emit(node.operand); - if (exportChanged) { - write(")"); - } - } - function emitPostfixUnaryExpression(node) { - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.operand); - if (exportChanged) { - // export function returns the value that was passes as the second argument - // however for postfix unary expressions result value should be the value before modification. - // emit 'x++' as '(export('x', ++x) - 1)' and 'x--' as '(export('x', --x) + 1)' - write("(" + exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.operand); - write("\", "); - write(ts.tokenToString(node.operator)); - emit(node.operand); - if (node.operator === 38 /* PlusPlusToken */) { - write(") - 1)"); - } - else { - write(") + 1)"); - } - } - else { - emit(node.operand); - write(ts.tokenToString(node.operator)); - } - } - /* - * Checks if given node is a source file level declaration (not nested in module/function). - * If 'isExported' is true - then declaration must also be exported. - * This function is used in two cases: - * - check if node is a exported source file level value to determine - * if we should also export the value after its it changed - * - check if node is a source level declaration to emit it differently, - * i.e non-exported variable statement 'var x = 1' is hoisted so - * we we emit variable statement 'var' should be dropped. - */ - function isSourceFileLevelDeclarationInSystemExternalModule(node, isExported) { - if (!node || languageVersion >= 2 /* ES6 */ || !isCurrentFileSystemExternalModule()) { - return false; - } - var current = node; - while (current) { - if (current.kind === 227 /* SourceFile */) { - return !isExported || ((ts.getCombinedNodeFlags(node) & 1 /* Export */) !== 0); - } - else if (ts.isFunctionLike(current) || current.kind === 206 /* ModuleBlock */) { - return false; - } - else { - current = current.parent; - } - } - } - function emitBinaryExpression(node) { - if (languageVersion < 2 /* ES6 */ && node.operatorToken.kind === 53 /* EqualsToken */ && - (node.left.kind === 154 /* ObjectLiteralExpression */ || node.left.kind === 153 /* ArrayLiteralExpression */)) { - emitDestructuring(node, node.parent.kind === 182 /* ExpressionStatement */); - } - else { - var exportChanged = node.operatorToken.kind >= 53 /* FirstAssignment */ && - node.operatorToken.kind <= 64 /* LastAssignment */ && - isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.left); - if (exportChanged) { - // emit assignment 'x y' as 'exports("x", x y)' - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.left); - write("\", "); - } - emit(node.left); - var indentedBeforeOperator = indentIfOnDifferentLines(node, node.left, node.operatorToken, node.operatorToken.kind !== 23 /* CommaToken */ ? " " : undefined); - write(ts.tokenToString(node.operatorToken.kind)); - var indentedAfterOperator = indentIfOnDifferentLines(node, node.operatorToken, node.right, " "); - emit(node.right); - decreaseIndentIf(indentedBeforeOperator, indentedAfterOperator); - if (exportChanged) { - write(")"); - } - } - } - function synthesizedNodeStartsOnNewLine(node) { - return ts.nodeIsSynthesized(node) && node.startsOnNewLine; - } - function emitConditionalExpression(node) { - emit(node.condition); - var indentedBeforeQuestion = indentIfOnDifferentLines(node, node.condition, node.questionToken, " "); - write("?"); - var indentedAfterQuestion = indentIfOnDifferentLines(node, node.questionToken, node.whenTrue, " "); - emit(node.whenTrue); - decreaseIndentIf(indentedBeforeQuestion, indentedAfterQuestion); - var indentedBeforeColon = indentIfOnDifferentLines(node, node.whenTrue, node.colonToken, " "); - write(":"); - var indentedAfterColon = indentIfOnDifferentLines(node, node.colonToken, node.whenFalse, " "); - emit(node.whenFalse); - decreaseIndentIf(indentedBeforeColon, indentedAfterColon); - } - // Helper function to decrease the indent if we previously indented. Allows multiple - // previous indent values to be considered at a time. This also allows caller to just - // call this once, passing in all their appropriate indent values, instead of needing - // to call this helper function multiple times. - function decreaseIndentIf(value1, value2) { - if (value1) { - decreaseIndent(); - } - if (value2) { - decreaseIndent(); - } - } - function isSingleLineEmptyBlock(node) { - if (node && node.kind === 179 /* Block */) { - var block = node; - return block.statements.length === 0 && nodeEndIsOnSameLineAsNodeStart(block, block); - } - } - function emitBlock(node) { - if (isSingleLineEmptyBlock(node)) { - emitToken(14 /* OpenBraceToken */, node.pos); - write(" "); - emitToken(15 /* CloseBraceToken */, node.statements.end); - return; - } - emitToken(14 /* OpenBraceToken */, node.pos); - increaseIndent(); - scopeEmitStart(node.parent); - if (node.kind === 206 /* ModuleBlock */) { - ts.Debug.assert(node.parent.kind === 205 /* ModuleDeclaration */); - emitCaptureThisForNodeIfNecessary(node.parent); - } - emitLines(node.statements); - if (node.kind === 206 /* ModuleBlock */) { - emitTempDeclarations(true); - } - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.statements.end); - scopeEmitEnd(); - } - function emitEmbeddedStatement(node) { - if (node.kind === 179 /* Block */) { - write(" "); - emit(node); - } - else { - increaseIndent(); - writeLine(); - emit(node); - decreaseIndent(); - } - } - function emitExpressionStatement(node) { - emitParenthesizedIf(node.expression, node.expression.kind === 163 /* ArrowFunction */); - write(";"); - } - function emitIfStatement(node) { - var endPos = emitToken(84 /* IfKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - emit(node.expression); - emitToken(17 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.thenStatement); - if (node.elseStatement) { - writeLine(); - emitToken(76 /* ElseKeyword */, node.thenStatement.end); - if (node.elseStatement.kind === 183 /* IfStatement */) { - write(" "); - emit(node.elseStatement); - } - else { - emitEmbeddedStatement(node.elseStatement); - } - } - } - function emitDoStatement(node) { - write("do"); - emitEmbeddedStatement(node.statement); - if (node.statement.kind === 179 /* Block */) { - write(" "); - } - else { - writeLine(); - } - write("while ("); - emit(node.expression); - write(");"); - } - function emitWhileStatement(node) { - write("while ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - /* Returns true if start of variable declaration list was emitted. - * Return false if nothing was written - this can happen for source file level variable declarations - * in system modules - such variable declarations are hoisted. - */ - function tryEmitStartOfVariableDeclarationList(decl, startPos) { - if (shouldHoistVariable(decl, true)) { - // variables in variable declaration list were already hoisted - return false; - } - var tokenKind = 98 /* VarKeyword */; - if (decl && languageVersion >= 2 /* ES6 */) { - if (ts.isLet(decl)) { - tokenKind = 104 /* LetKeyword */; - } - else if (ts.isConst(decl)) { - tokenKind = 70 /* ConstKeyword */; - } - } - if (startPos !== undefined) { - emitToken(tokenKind, startPos); - write(" "); - } - else { - switch (tokenKind) { - case 98 /* VarKeyword */: - write("var "); - break; - case 104 /* LetKeyword */: - write("let "); - break; - case 70 /* ConstKeyword */: - write("const "); - break; - } - } - return true; - } - function emitVariableDeclarationListSkippingUninitializedEntries(list) { - var started = false; - for (var _i = 0, _a = list.declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - if (!decl.initializer) { - continue; - } - if (!started) { - started = true; - } - else { - write(", "); - } - emit(decl); - } - return started; - } - function emitForStatement(node) { - var endPos = emitToken(82 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.initializer && node.initializer.kind === 199 /* VariableDeclarationList */) { - var variableDeclarationList = node.initializer; - var startIsEmitted = tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); - if (startIsEmitted) { - emitCommaList(variableDeclarationList.declarations); - } - else { - emitVariableDeclarationListSkippingUninitializedEntries(variableDeclarationList); - } - } - else if (node.initializer) { - emit(node.initializer); - } - write(";"); - emitOptional(" ", node.condition); - write(";"); - emitOptional(" ", node.iterator); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitForInOrForOfStatement(node) { - if (languageVersion < 2 /* ES6 */ && node.kind === 188 /* ForOfStatement */) { - return emitDownLevelForOfStatement(node); - } - var endPos = emitToken(82 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - if (node.initializer.kind === 199 /* VariableDeclarationList */) { - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length >= 1) { - tryEmitStartOfVariableDeclarationList(variableDeclarationList, endPos); - emit(variableDeclarationList.declarations[0]); - } - } - else { - emit(node.initializer); - } - if (node.kind === 187 /* ForInStatement */) { - write(" in "); - } - else { - write(" of "); - } - emit(node.expression); - emitToken(17 /* CloseParenToken */, node.expression.end); - emitEmbeddedStatement(node.statement); - } - function emitDownLevelForOfStatement(node) { - // The following ES6 code: - // - // for (let v of expr) { } - // - // should be emitted as - // - // for (let _i = 0, _a = expr; _i < _a.length; _i++) { - // let v = _a[_i]; - // } - // - // where _a and _i are temps emitted to capture the RHS and the counter, - // respectively. - // When the left hand side is an expression instead of a let declaration, - // the "let v" is not emitted. - // When the left hand side is a let/const, the v is renamed if there is - // another v in scope. - // Note that all assignments to the LHS are emitted in the body, including - // all destructuring. - // Note also that because an extra statement is needed to assign to the LHS, - // for-of bodies are always emitted as blocks. - var endPos = emitToken(82 /* ForKeyword */, node.pos); - write(" "); - endPos = emitToken(16 /* OpenParenToken */, endPos); - // Do not emit the LHS let declaration yet, because it might contain destructuring. - // Do not call recordTempDeclaration because we are declaring the temps - // right here. Recording means they will be declared later. - // In the case where the user wrote an identifier as the RHS, like this: - // - // for (let v of arr) { } - // - // we don't want to emit a temporary variable for the RHS, just use it directly. - var rhsIsIdentifier = node.expression.kind === 65 /* Identifier */; - var counter = createTempVariable(268435456 /* _i */); - var rhsReference = rhsIsIdentifier ? node.expression : createTempVariable(0 /* Auto */); - // This is the let keyword for the counter and rhsReference. The let keyword for - // the LHS will be emitted inside the body. - emitStart(node.expression); - write("var "); - // _i = 0 - emitNodeWithoutSourceMap(counter); - write(" = 0"); - emitEnd(node.expression); - if (!rhsIsIdentifier) { - // , _a = expr - write(", "); - emitStart(node.expression); - emitNodeWithoutSourceMap(rhsReference); - write(" = "); - emitNodeWithoutSourceMap(node.expression); - emitEnd(node.expression); - } - write("; "); - // _i < _a.length; - emitStart(node.initializer); - emitNodeWithoutSourceMap(counter); - write(" < "); - emitNodeWithoutSourceMap(rhsReference); - write(".length"); - emitEnd(node.initializer); - write("; "); - // _i++) - emitStart(node.initializer); - emitNodeWithoutSourceMap(counter); - write("++"); - emitEnd(node.initializer); - emitToken(17 /* CloseParenToken */, node.expression.end); - // Body - write(" {"); - writeLine(); - increaseIndent(); - // Initialize LHS - // let v = _a[_i]; - var rhsIterationValue = createElementAccessExpression(rhsReference, counter); - emitStart(node.initializer); - if (node.initializer.kind === 199 /* VariableDeclarationList */) { - write("var "); - var variableDeclarationList = node.initializer; - if (variableDeclarationList.declarations.length > 0) { - var declaration = variableDeclarationList.declarations[0]; - if (ts.isBindingPattern(declaration.name)) { - // This works whether the declaration is a var, let, or const. - // It will use rhsIterationValue _a[_i] as the initializer. - emitDestructuring(declaration, false, rhsIterationValue); - } - else { - // The following call does not include the initializer, so we have - // to emit it separately. - emitNodeWithoutSourceMap(declaration); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - // It's an empty declaration list. This can only happen in an error case, if the user wrote - // for (let of []) {} - emitNodeWithoutSourceMap(createTempVariable(0 /* Auto */)); - write(" = "); - emitNodeWithoutSourceMap(rhsIterationValue); - } - } - else { - // Initializer is an expression. Emit the expression in the body, so that it's - // evaluated on every iteration. - var assignmentExpression = createBinaryExpression(node.initializer, 53 /* EqualsToken */, rhsIterationValue, false); - if (node.initializer.kind === 153 /* ArrayLiteralExpression */ || node.initializer.kind === 154 /* ObjectLiteralExpression */) { - // This is a destructuring pattern, so call emitDestructuring instead of emit. Calling emit will not work, because it will cause - // the BinaryExpression to be passed in instead of the expression statement, which will cause emitDestructuring to crash. - emitDestructuring(assignmentExpression, true, undefined); - } - else { - emitNodeWithoutSourceMap(assignmentExpression); - } - } - emitEnd(node.initializer); - write(";"); - if (node.statement.kind === 179 /* Block */) { - emitLines(node.statement.statements); - } - else { - writeLine(); - emit(node.statement); - } - writeLine(); - decreaseIndent(); - write("}"); - } - function emitBreakOrContinueStatement(node) { - emitToken(node.kind === 190 /* BreakStatement */ ? 66 /* BreakKeyword */ : 71 /* ContinueKeyword */, node.pos); - emitOptional(" ", node.label); - write(";"); - } - function emitReturnStatement(node) { - emitToken(90 /* ReturnKeyword */, node.pos); - emitOptional(" ", node.expression); - write(";"); - } - function emitWithStatement(node) { - write("with ("); - emit(node.expression); - write(")"); - emitEmbeddedStatement(node.statement); - } - function emitSwitchStatement(node) { - var endPos = emitToken(92 /* SwitchKeyword */, node.pos); - write(" "); - emitToken(16 /* OpenParenToken */, endPos); - emit(node.expression); - endPos = emitToken(17 /* CloseParenToken */, node.expression.end); - write(" "); - emitCaseBlock(node.caseBlock, endPos); - } - function emitCaseBlock(node, startPos) { - emitToken(14 /* OpenBraceToken */, startPos); - increaseIndent(); - emitLines(node.clauses); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.clauses.end); - } - function nodeStartPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node1.pos)) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); - } - function nodeEndPositionsAreOnSameLine(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, node2.end); - } - function nodeEndIsOnSameLineAsNodeStart(node1, node2) { - return ts.getLineOfLocalPosition(currentSourceFile, node1.end) === - ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node2.pos)); - } - function emitCaseOrDefaultClause(node) { - if (node.kind === 220 /* CaseClause */) { - write("case "); - emit(node.expression); - write(":"); - } - else { - write("default:"); - } - if (node.statements.length === 1 && nodeStartPositionsAreOnSameLine(node, node.statements[0])) { - write(" "); - emit(node.statements[0]); - } - else { - increaseIndent(); - emitLines(node.statements); - decreaseIndent(); - } - } - function emitThrowStatement(node) { - write("throw "); - emit(node.expression); - write(";"); - } - function emitTryStatement(node) { - write("try "); - emit(node.tryBlock); - emit(node.catchClause); - if (node.finallyBlock) { - writeLine(); - write("finally "); - emit(node.finallyBlock); - } - } - function emitCatchClause(node) { - writeLine(); - var endPos = emitToken(68 /* CatchKeyword */, node.pos); - write(" "); - emitToken(16 /* OpenParenToken */, endPos); - emit(node.variableDeclaration); - emitToken(17 /* CloseParenToken */, node.variableDeclaration ? node.variableDeclaration.end : endPos); - write(" "); - emitBlock(node.block); - } - function emitDebuggerStatement(node) { - emitToken(72 /* DebuggerKeyword */, node.pos); - write(";"); - } - function emitLabelledStatement(node) { - emit(node.label); - write(": "); - emit(node.statement); - } - function getContainingModule(node) { - do { - node = node.parent; - } while (node && node.kind !== 205 /* ModuleDeclaration */); - return node; - } - function emitContainingModuleName(node) { - var container = getContainingModule(node); - write(container ? getGeneratedNameForNode(container) : "exports"); - } - function emitModuleMemberName(node) { - emitStart(node.name); - if (ts.getCombinedNodeFlags(node) & 1 /* Export */) { - var container = getContainingModule(node); - if (container) { - write(getGeneratedNameForNode(container)); - write("."); - } - else if (languageVersion < 2 /* ES6 */ && compilerOptions.module !== 3 /* System */) { - write("exports."); - } - } - emitNodeWithoutSourceMap(node.name); - emitEnd(node.name); - } - function createVoidZero() { - var zero = ts.createSynthesizedNode(7 /* NumericLiteral */); - zero.text = "0"; - var result = ts.createSynthesizedNode(166 /* VoidExpression */); - result.expression = zero; - return result; - } - function emitExportMemberAssignment(node) { - if (node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - if (compilerOptions.module === 3 /* System */) { - // emit export default as - // export("default", ) - write(exportFunctionForFile + "(\""); - if (node.flags & 256 /* Default */) { - write("default"); - } - else { - emitNodeWithoutSourceMap(node.name); - } - write("\", "); - emitDeclarationName(node); - write(")"); - } - else { - if (node.flags & 256 /* Default */) { - if (languageVersion === 0 /* ES3 */) { - write("exports[\"default\"]"); - } - else { - write("exports.default"); - } - } - else { - emitModuleMemberName(node); - } - write(" = "); - emitDeclarationName(node); - } - emitEnd(node); - write(";"); - } - } - function emitExportMemberAssignments(name) { - if (!exportEquals && exportSpecifiers && ts.hasProperty(exportSpecifiers, name.text)) { - for (var _i = 0, _a = exportSpecifiers[name.text]; _i < _a.length; _i++) { - var specifier = _a[_i]; - writeLine(); - emitStart(specifier.name); - if (compilerOptions.module === 3 /* System */) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(specifier.name); - write("\", "); - emitExpressionIdentifier(name); - write(")"); - } - else { - emitContainingModuleName(specifier); - write("."); - emitNodeWithoutSourceMap(specifier.name); - emitEnd(specifier.name); - write(" = "); - emitExpressionIdentifier(name); - } - write(";"); - } - } - } - function emitDestructuring(root, isAssignmentExpressionStatement, value) { - var emitCount = 0; - // An exported declaration is actually emitted as an assignment (to a property on the module object), so - // temporary variables in an exported declaration need to have real declarations elsewhere - // Also temporary variables should be explicitly allocated for source level declarations when module target is system - // because actual variable declarations are hoisted - var canDefineTempVariablesInPlace = false; - if (root.kind === 198 /* VariableDeclaration */) { - var isExported = ts.getCombinedNodeFlags(root) & 1 /* Export */; - var isSourceLevelForSystemModuleKind = isSourceFileLevelDeclarationInSystemExternalModule(root, false); - canDefineTempVariablesInPlace = !isExported && !isSourceLevelForSystemModuleKind; - } - else if (root.kind === 129 /* Parameter */) { - canDefineTempVariablesInPlace = true; - } - if (root.kind === 169 /* BinaryExpression */) { - emitAssignmentExpression(root); - } - else { - ts.Debug.assert(!isAssignmentExpressionStatement); - emitBindingElement(root, value); - } - function emitAssignment(name, value) { - if (emitCount++) { - write(", "); - } - renameNonTopLevelLetAndConst(name); - var isVariableDeclarationOrBindingElement = name.parent && (name.parent.kind === 198 /* VariableDeclaration */ || name.parent.kind === 152 /* BindingElement */); - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(name); - write("\", "); - } - if (isVariableDeclarationOrBindingElement) { - emitModuleMemberName(name.parent); - } - else { - emit(name); - } - write(" = "); - emit(value); - if (exportChanged) { - write(")"); - } - } - function ensureIdentifier(expr) { - if (expr.kind !== 65 /* Identifier */) { - var identifier = createTempVariable(0 /* Auto */); - if (!canDefineTempVariablesInPlace) { - recordTempDeclaration(identifier); - } - emitAssignment(identifier, expr); - expr = identifier; - } - return expr; - } - function createDefaultValueCheck(value, defaultValue) { - // The value expression will be evaluated twice, so for anything but a simple identifier - // we need to generate a temporary variable - value = ensureIdentifier(value); - // Return the expression 'value === void 0 ? defaultValue : value' - var equals = ts.createSynthesizedNode(169 /* BinaryExpression */); - equals.left = value; - equals.operatorToken = ts.createSynthesizedNode(30 /* EqualsEqualsEqualsToken */); - equals.right = createVoidZero(); - return createConditionalExpression(equals, defaultValue, value); - } - function createConditionalExpression(condition, whenTrue, whenFalse) { - var cond = ts.createSynthesizedNode(170 /* ConditionalExpression */); - cond.condition = condition; - cond.questionToken = ts.createSynthesizedNode(50 /* QuestionToken */); - cond.whenTrue = whenTrue; - cond.colonToken = ts.createSynthesizedNode(51 /* ColonToken */); - cond.whenFalse = whenFalse; - return cond; - } - function createNumericLiteral(value) { - var node = ts.createSynthesizedNode(7 /* NumericLiteral */); - node.text = "" + value; - return node; - } - function createPropertyAccessForDestructuringProperty(object, propName) { - if (propName.kind !== 65 /* Identifier */) { - return createElementAccessExpression(object, propName); - } - return createPropertyAccessExpression(object, propName); - } - function createSliceCall(value, sliceIndex) { - var call = ts.createSynthesizedNode(157 /* CallExpression */); - var sliceIdentifier = ts.createSynthesizedNode(65 /* Identifier */); - sliceIdentifier.text = "slice"; - call.expression = createPropertyAccessExpression(value, sliceIdentifier); - call.arguments = ts.createSynthesizedNodeArray(); - call.arguments[0] = createNumericLiteral(sliceIndex); - return call; - } - function emitObjectLiteralAssignment(target, value) { - var properties = target.properties; - if (properties.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - value = ensureIdentifier(value); - } - for (var _i = 0; _i < properties.length; _i++) { - var p = properties[_i]; - if (p.kind === 224 /* PropertyAssignment */ || p.kind === 225 /* ShorthandPropertyAssignment */) { - // TODO(andersh): Computed property support - var propName = (p.name); - emitDestructuringAssignment(p.initializer || propName, createPropertyAccessForDestructuringProperty(value, propName)); - } - } - } - function emitArrayLiteralAssignment(target, value) { - var elements = target.elements; - if (elements.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - value = ensureIdentifier(value); - } - for (var i = 0; i < elements.length; i++) { - var e = elements[i]; - if (e.kind !== 175 /* OmittedExpression */) { - if (e.kind !== 173 /* SpreadElementExpression */) { - emitDestructuringAssignment(e, createElementAccessExpression(value, createNumericLiteral(i))); - } - else if (i === elements.length - 1) { - emitDestructuringAssignment(e.expression, createSliceCall(value, i)); - } - } - } - } - function emitDestructuringAssignment(target, value) { - if (target.kind === 169 /* BinaryExpression */ && target.operatorToken.kind === 53 /* EqualsToken */) { - value = createDefaultValueCheck(value, target.right); - target = target.left; - } - if (target.kind === 154 /* ObjectLiteralExpression */) { - emitObjectLiteralAssignment(target, value); - } - else if (target.kind === 153 /* ArrayLiteralExpression */) { - emitArrayLiteralAssignment(target, value); - } - else { - emitAssignment(target, value); - } - } - function emitAssignmentExpression(root) { - var target = root.left; - var value = root.right; - if (isAssignmentExpressionStatement) { - emitDestructuringAssignment(target, value); - } - else { - if (root.parent.kind !== 161 /* ParenthesizedExpression */) { - write("("); - } - value = ensureIdentifier(value); - emitDestructuringAssignment(target, value); - write(", "); - emit(value); - if (root.parent.kind !== 161 /* ParenthesizedExpression */) { - write(")"); - } - } - } - function emitBindingElement(target, value) { - if (target.initializer) { - // Combine value and initializer - value = value ? createDefaultValueCheck(value, target.initializer) : target.initializer; - } - else if (!value) { - // Use 'void 0' in absence of value and initializer - value = createVoidZero(); - } - if (ts.isBindingPattern(target.name)) { - var pattern = target.name; - var elements = pattern.elements; - if (elements.length !== 1) { - // For anything but a single element destructuring we need to generate a temporary - // to ensure value is evaluated exactly once. - value = ensureIdentifier(value); - } - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; - if (pattern.kind === 150 /* ObjectBindingPattern */) { - // Rewrite element to a declaration with an initializer that fetches property - var propName = element.propertyName || element.name; - emitBindingElement(element, createPropertyAccessForDestructuringProperty(value, propName)); - } - else if (element.kind !== 175 /* OmittedExpression */) { - if (!element.dotDotDotToken) { - // Rewrite element to a declaration that accesses array element at index i - emitBindingElement(element, createElementAccessExpression(value, createNumericLiteral(i))); - } - else if (i === elements.length - 1) { - emitBindingElement(element, createSliceCall(value, i)); - } - } - } - } - else { - emitAssignment(target.name, value); - } - } - } - function emitVariableDeclaration(node) { - if (ts.isBindingPattern(node.name)) { - if (languageVersion < 2 /* ES6 */) { - emitDestructuring(node, false); - } - else { - emit(node.name); - emitOptional(" = ", node.initializer); - } - } - else { - renameNonTopLevelLetAndConst(node.name); - var initializer = node.initializer; - if (!initializer && languageVersion < 2 /* ES6 */) { - // downlevel emit for non-initialized let bindings defined in loops - // for (...) { let x; } - // should be - // for (...) { var = void 0; } - // this is necessary to preserve ES6 semantic in scenarios like - // for (...) { let x; console.log(x); x = 1 } // assignment on one iteration should not affect other iterations - var isUninitializedLet = (resolver.getNodeCheckFlags(node) & 256 /* BlockScopedBindingInLoop */) && - (getCombinedFlagsForIdentifier(node.name) & 4096 /* Let */); - // NOTE: default initialization should not be added to let bindings in for-in\for-of statements - if (isUninitializedLet && - node.parent.parent.kind !== 187 /* ForInStatement */ && - node.parent.parent.kind !== 188 /* ForOfStatement */) { - initializer = createVoidZero(); - } - } - var exportChanged = isNameOfExportedSourceLevelDeclarationInSystemExternalModule(node.name); - if (exportChanged) { - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(node.name); - write("\", "); - } - emitModuleMemberName(node); - emitOptional(" = ", initializer); - if (exportChanged) { - write(")"); - } - } - } - function emitExportVariableAssignments(node) { - if (node.kind === 175 /* OmittedExpression */) { - return; - } - var name = node.name; - if (name.kind === 65 /* Identifier */) { - emitExportMemberAssignments(name); - } - else if (ts.isBindingPattern(name)) { - ts.forEach(name.elements, emitExportVariableAssignments); - } - } - function getCombinedFlagsForIdentifier(node) { - if (!node.parent || (node.parent.kind !== 198 /* VariableDeclaration */ && node.parent.kind !== 152 /* BindingElement */)) { - return 0; - } - return ts.getCombinedNodeFlags(node.parent); - } - function renameNonTopLevelLetAndConst(node) { - // do not rename if - // - language version is ES6+ - // - node is synthesized - // - node is not identifier (can happen when tree is malformed) - // - node is definitely not name of variable declaration. - // it still can be part of parameter declaration, this check will be done next - if (languageVersion >= 2 /* ES6 */ || - ts.nodeIsSynthesized(node) || - node.kind !== 65 /* Identifier */ || - (node.parent.kind !== 198 /* VariableDeclaration */ && node.parent.kind !== 152 /* BindingElement */)) { - return; - } - var combinedFlags = getCombinedFlagsForIdentifier(node); - if (((combinedFlags & 12288 /* BlockScoped */) === 0) || combinedFlags & 1 /* Export */) { - // do not rename exported or non-block scoped variables - return; - } - // here it is known that node is a block scoped variable - var list = ts.getAncestor(node, 199 /* VariableDeclarationList */); - if (list.parent.kind === 180 /* VariableStatement */) { - var isSourceFileLevelBinding = list.parent.parent.kind === 227 /* SourceFile */; - var isModuleLevelBinding = list.parent.parent.kind === 206 /* ModuleBlock */; - var isFunctionLevelBinding = list.parent.parent.kind === 179 /* Block */ && ts.isFunctionLike(list.parent.parent.parent); - if (isSourceFileLevelBinding || isModuleLevelBinding || isFunctionLevelBinding) { - return; - } - } - var blockScopeContainer = ts.getEnclosingBlockScopeContainer(node); - var parent = blockScopeContainer.kind === 227 /* SourceFile */ - ? blockScopeContainer - : blockScopeContainer.parent; - if (resolver.resolvesToSomeValue(parent, node.text)) { - var variableId = resolver.getBlockScopedVariableId(node); - if (!blockScopedVariableToGeneratedName) { - blockScopedVariableToGeneratedName = []; - } - var generatedName = makeUniqueName(node.text); - blockScopedVariableToGeneratedName[variableId] = generatedName; - } - } - function isES6ExportedDeclaration(node) { - return !!(node.flags & 1 /* Export */) && - languageVersion >= 2 /* ES6 */ && - node.parent.kind === 227 /* SourceFile */; - } - function emitVariableStatement(node) { - var startIsEmitted = true; - if (!(node.flags & 1 /* Export */)) { - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - else if (isES6ExportedDeclaration(node)) { - // Exported ES6 module member - write("export "); - startIsEmitted = tryEmitStartOfVariableDeclarationList(node.declarationList); - } - if (startIsEmitted) { - emitCommaList(node.declarationList.declarations); - write(";"); - } - else { - var atLeastOneItem = emitVariableDeclarationListSkippingUninitializedEntries(node.declarationList); - if (atLeastOneItem) { - write(";"); - } - } - if (languageVersion < 2 /* ES6 */ && node.parent === currentSourceFile) { - ts.forEach(node.declarationList.declarations, emitExportVariableAssignments); - } - } - function emitParameter(node) { - if (languageVersion < 2 /* ES6 */) { - if (ts.isBindingPattern(node.name)) { - var name_5 = createTempVariable(0 /* Auto */); - if (!tempParameters) { - tempParameters = []; - } - tempParameters.push(name_5); - emit(name_5); - } - else { - emit(node.name); - } - } - else { - if (node.dotDotDotToken) { - write("..."); - } - emit(node.name); - emitOptional(" = ", node.initializer); - } - } - function emitDefaultValueAssignments(node) { - if (languageVersion < 2 /* ES6 */) { - var tempIndex = 0; - ts.forEach(node.parameters, function (p) { - // A rest parameter cannot have a binding pattern or an initializer, - // so let's just ignore it. - if (p.dotDotDotToken) { - return; - } - if (ts.isBindingPattern(p.name)) { - writeLine(); - write("var "); - emitDestructuring(p, false, tempParameters[tempIndex]); - write(";"); - tempIndex++; - } - else if (p.initializer) { - writeLine(); - emitStart(p); - write("if ("); - emitNodeWithoutSourceMap(p.name); - write(" === void 0)"); - emitEnd(p); - write(" { "); - emitStart(p); - emitNodeWithoutSourceMap(p.name); - write(" = "); - emitNodeWithoutSourceMap(p.initializer); - emitEnd(p); - write("; }"); - } - }); - } - } - function emitRestParameter(node) { - if (languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node)) { - var restIndex = node.parameters.length - 1; - var restParam = node.parameters[restIndex]; - // A rest parameter cannot have a binding pattern, so let's just ignore it if it does. - if (ts.isBindingPattern(restParam.name)) { - return; - } - var tempName = createTempVariable(268435456 /* _i */).text; - writeLine(); - emitLeadingComments(restParam); - emitStart(restParam); - write("var "); - emitNodeWithoutSourceMap(restParam.name); - write(" = [];"); - emitEnd(restParam); - emitTrailingComments(restParam); - writeLine(); - write("for ("); - emitStart(restParam); - write("var " + tempName + " = " + restIndex + ";"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + " < arguments.length;"); - emitEnd(restParam); - write(" "); - emitStart(restParam); - write(tempName + "++"); - emitEnd(restParam); - write(") {"); - increaseIndent(); - writeLine(); - emitStart(restParam); - emitNodeWithoutSourceMap(restParam.name); - write("[" + tempName + " - " + restIndex + "] = arguments[" + tempName + "];"); - emitEnd(restParam); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function emitAccessor(node) { - write(node.kind === 136 /* GetAccessor */ ? "get " : "set "); - emit(node.name, false); - emitSignatureAndBody(node); - } - function shouldEmitAsArrowFunction(node) { - return node.kind === 163 /* ArrowFunction */ && languageVersion >= 2 /* ES6 */; - } - function emitDeclarationName(node) { - if (node.name) { - emitNodeWithoutSourceMap(node.name); - } - else { - write(getGeneratedNameForNode(node)); - } - } - function shouldEmitFunctionName(node) { - if (node.kind === 162 /* FunctionExpression */) { - // Emit name if one is present - return !!node.name; - } - if (node.kind === 200 /* FunctionDeclaration */) { - // Emit name if one is present, or emit generated name in down-level case (for export default case) - return !!node.name || languageVersion < 2 /* ES6 */; - } - } - function emitFunctionDeclaration(node) { - if (ts.nodeIsMissing(node.body)) { - return emitOnlyPinnedOrTripleSlashComments(node); - } - if (node.kind !== 134 /* MethodDeclaration */ && node.kind !== 133 /* MethodSignature */) { - // Methods will emit the comments as part of emitting method declaration - emitLeadingComments(node); - } - // For targeting below es6, emit functions-like declaration including arrow function using function keyword. - // When targeting ES6, emit arrow function natively in ES6 by omitting function keyword and using fat arrow instead - if (!shouldEmitAsArrowFunction(node)) { - if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 256 /* Default */) { - write("default "); - } - } - write("function"); - if (languageVersion >= 2 /* ES6 */ && node.asteriskToken) { - write("*"); - } - write(" "); - } - if (shouldEmitFunctionName(node)) { - emitDeclarationName(node); - } - emitSignatureAndBody(node); - if (languageVersion < 2 /* ES6 */ && node.kind === 200 /* FunctionDeclaration */ && node.parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - if (node.kind !== 134 /* MethodDeclaration */ && node.kind !== 133 /* MethodSignature */) { - emitTrailingComments(node); - } - } - function emitCaptureThisForNodeIfNecessary(node) { - if (resolver.getNodeCheckFlags(node) & 4 /* CaptureThis */) { - writeLine(); - emitStart(node); - write("var _this = this;"); - emitEnd(node); - } - } - function emitSignatureParameters(node) { - increaseIndent(); - write("("); - if (node) { - var parameters = node.parameters; - var omitCount = languageVersion < 2 /* ES6 */ && ts.hasRestParameters(node) ? 1 : 0; - emitList(parameters, 0, parameters.length - omitCount, false, false); - } - write(")"); - decreaseIndent(); - } - function emitSignatureParametersForArrow(node) { - // Check whether the parameter list needs parentheses and preserve no-parenthesis - if (node.parameters.length === 1 && node.pos === node.parameters[0].pos) { - emit(node.parameters[0]); - return; - } - emitSignatureParameters(node); - } - function emitSignatureAndBody(node) { - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - // When targeting ES6, emit arrow function natively in ES6 - if (shouldEmitAsArrowFunction(node)) { - emitSignatureParametersForArrow(node); - write(" =>"); - } - else { - emitSignatureParameters(node); - } - if (!node.body) { - // There can be no body when there are parse errors. Just emit an empty block - // in that case. - write(" { }"); - } - else if (node.body.kind === 179 /* Block */) { - emitBlockFunctionBody(node, node.body); - } - else { - emitExpressionFunctionBody(node, node.body); - } - if (!isES6ExportedDeclaration(node)) { - emitExportMemberAssignment(node); - } - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - // Returns true if any preamble code was emitted. - function emitFunctionBodyPreamble(node) { - emitCaptureThisForNodeIfNecessary(node); - emitDefaultValueAssignments(node); - emitRestParameter(node); - } - function emitExpressionFunctionBody(node, body) { - if (languageVersion < 2 /* ES6 */) { - emitDownLevelExpressionFunctionBody(node, body); - return; - } - // For es6 and higher we can emit the expression as is. However, in the case - // where the expression might end up looking like a block when emitted, we'll - // also wrap it in parentheses first. For example if you have: a => {} - // then we need to generate: a => ({}) - write(" "); - // Unwrap all type assertions. - var current = body; - while (current.kind === 160 /* TypeAssertionExpression */) { - current = current.expression; - } - emitParenthesizedIf(body, current.kind === 154 /* ObjectLiteralExpression */); - } - function emitDownLevelExpressionFunctionBody(node, body) { - write(" {"); - scopeEmitStart(node); - increaseIndent(); - var outPos = writer.getTextPos(); - emitDetachedComments(node.body); - emitFunctionBodyPreamble(node); - var preambleEmitted = writer.getTextPos() !== outPos; - decreaseIndent(); - // If we didn't have to emit any preamble code, then attempt to keep the arrow - // function on one line. - if (!preambleEmitted && nodeStartPositionsAreOnSameLine(node, body)) { - write(" "); - emitStart(body); - write("return "); - emit(body); - emitEnd(body); - write(";"); - emitTempDeclarations(false); - write(" "); - } - else { - increaseIndent(); - writeLine(); - emitLeadingComments(node.body); - write("return "); - emit(body); - write(";"); - emitTrailingComments(node.body); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - } - emitStart(node.body); - write("}"); - emitEnd(node.body); - scopeEmitEnd(); - } - function emitBlockFunctionBody(node, body) { - write(" {"); - scopeEmitStart(node); - var initialTextPos = writer.getTextPos(); - increaseIndent(); - emitDetachedComments(body.statements); - // Emit all the directive prologues (like "use strict"). These have to come before - // any other preamble code we write (like parameter initializers). - var startIndex = emitDirectivePrologues(body.statements, true); - emitFunctionBodyPreamble(node); - decreaseIndent(); - var preambleEmitted = writer.getTextPos() !== initialTextPos; - if (!preambleEmitted && nodeEndIsOnSameLineAsNodeStart(body, body)) { - for (var _i = 0, _a = body.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - write(" "); - emit(statement); - } - emitTempDeclarations(false); - write(" "); - emitLeadingCommentsOfPosition(body.statements.end); - } - else { - increaseIndent(); - emitLinesStartingAt(body.statements, startIndex); - emitTempDeclarations(true); - writeLine(); - emitLeadingCommentsOfPosition(body.statements.end); - decreaseIndent(); - } - emitToken(15 /* CloseBraceToken */, body.statements.end); - scopeEmitEnd(); - } - function findInitialSuperCall(ctor) { - if (ctor.body) { - var statement = ctor.body.statements[0]; - if (statement && statement.kind === 182 /* ExpressionStatement */) { - var expr = statement.expression; - if (expr && expr.kind === 157 /* CallExpression */) { - var func = expr.expression; - if (func && func.kind === 91 /* SuperKeyword */) { - return statement; - } - } - } - } - } - function emitParameterPropertyAssignments(node) { - ts.forEach(node.parameters, function (param) { - if (param.flags & 112 /* AccessibilityModifier */) { - writeLine(); - emitStart(param); - emitStart(param.name); - write("this."); - emitNodeWithoutSourceMap(param.name); - emitEnd(param.name); - write(" = "); - emit(param.name); - write(";"); - emitEnd(param); - } - }); - } - function emitMemberAccessForPropertyName(memberName) { - // TODO: (jfreeman,drosen): comment on why this is emitNodeWithoutSourceMap instead of emit here. - if (memberName.kind === 8 /* StringLiteral */ || memberName.kind === 7 /* NumericLiteral */) { - write("["); - emitNodeWithoutSourceMap(memberName); - write("]"); - } - else if (memberName.kind === 127 /* ComputedPropertyName */) { - emitComputedPropertyName(memberName); - } - else { - write("."); - emitNodeWithoutSourceMap(memberName); - } - } - function getInitializedProperties(node, static) { - var properties = []; - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if (member.kind === 132 /* PropertyDeclaration */ && static === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { - properties.push(member); - } - } - return properties; - } - function emitPropertyDeclarations(node, properties) { - for (var _i = 0; _i < properties.length; _i++) { - var property = properties[_i]; - emitPropertyDeclaration(node, property); - } - } - function emitPropertyDeclaration(node, property, receiver, isExpression) { - writeLine(); - emitLeadingComments(property); - emitStart(property); - emitStart(property.name); - if (receiver) { - emit(receiver); - } - else { - if (property.flags & 128 /* Static */) { - emitDeclarationName(node); - } - else { - write("this"); - } - } - emitMemberAccessForPropertyName(property.name); - emitEnd(property.name); - write(" = "); - emit(property.initializer); - if (!isExpression) { - write(";"); - } - emitEnd(property); - emitTrailingComments(property); - } - function emitMemberFunctionsForES5AndLower(node) { - ts.forEach(node.members, function (member) { - if (member.kind === 178 /* SemicolonClassElement */) { - writeLine(); - write(";"); - } - else if (member.kind === 134 /* MethodDeclaration */ || node.kind === 133 /* MethodSignature */) { - if (!member.body) { - return emitOnlyPinnedOrTripleSlashComments(member); - } - writeLine(); - emitLeadingComments(member); - emitStart(member); - emitStart(member.name); - emitClassMemberPrefix(node, member); - emitMemberAccessForPropertyName(member.name); - emitEnd(member.name); - write(" = "); - emitStart(member); - emitFunctionDeclaration(member); - emitEnd(member); - emitEnd(member); - write(";"); - emitTrailingComments(member); - } - else if (member.kind === 136 /* GetAccessor */ || member.kind === 137 /* SetAccessor */) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member === accessors.firstAccessor) { - writeLine(); - emitStart(member); - write("Object.defineProperty("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(", {"); - increaseIndent(); - if (accessors.getAccessor) { - writeLine(); - emitLeadingComments(accessors.getAccessor); - write("get: "); - emitStart(accessors.getAccessor); - write("function "); - emitSignatureAndBody(accessors.getAccessor); - emitEnd(accessors.getAccessor); - emitTrailingComments(accessors.getAccessor); - write(","); - } - if (accessors.setAccessor) { - writeLine(); - emitLeadingComments(accessors.setAccessor); - write("set: "); - emitStart(accessors.setAccessor); - write("function "); - emitSignatureAndBody(accessors.setAccessor); - emitEnd(accessors.setAccessor); - emitTrailingComments(accessors.setAccessor); - write(","); - } - writeLine(); - write("enumerable: true,"); - writeLine(); - write("configurable: true"); - decreaseIndent(); - writeLine(); - write("});"); - emitEnd(member); - } - } - }); - } - function emitMemberFunctionsForES6AndHigher(node) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - if ((member.kind === 134 /* MethodDeclaration */ || node.kind === 133 /* MethodSignature */) && !member.body) { - emitOnlyPinnedOrTripleSlashComments(member); - } - else if (member.kind === 134 /* MethodDeclaration */ || - member.kind === 136 /* GetAccessor */ || - member.kind === 137 /* SetAccessor */) { - writeLine(); - emitLeadingComments(member); - emitStart(member); - if (member.flags & 128 /* Static */) { - write("static "); - } - if (member.kind === 136 /* GetAccessor */) { - write("get "); - } - else if (member.kind === 137 /* SetAccessor */) { - write("set "); - } - if (member.asteriskToken) { - write("*"); - } - emit(member.name); - emitSignatureAndBody(member); - emitEnd(member); - emitTrailingComments(member); - } - else if (member.kind === 178 /* SemicolonClassElement */) { - writeLine(); - write(";"); - } - } - } - function emitConstructor(node, baseTypeElement) { - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - emitConstructorWorker(node, baseTypeElement); - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - } - function emitConstructorWorker(node, baseTypeElement) { - // Check if we have property assignment inside class declaration. - // If there is property assignment, we need to emit constructor whether users define it or not - // If there is no property assignment, we can omit constructor if users do not define it - var hasInstancePropertyWithInitializer = false; - // Emit the constructor overload pinned comments - ts.forEach(node.members, function (member) { - if (member.kind === 135 /* Constructor */ && !member.body) { - emitOnlyPinnedOrTripleSlashComments(member); - } - // Check if there is any non-static property assignment - if (member.kind === 132 /* PropertyDeclaration */ && member.initializer && (member.flags & 128 /* Static */) === 0) { - hasInstancePropertyWithInitializer = true; - } - }); - var ctor = ts.getFirstConstructorWithBody(node); - // For target ES6 and above, if there is no user-defined constructor and there is no property assignment - // do not emit constructor in class declaration. - if (languageVersion >= 2 /* ES6 */ && !ctor && !hasInstancePropertyWithInitializer) { - return; - } - if (ctor) { - emitLeadingComments(ctor); - } - emitStart(ctor || node); - if (languageVersion < 2 /* ES6 */) { - write("function "); - emitDeclarationName(node); - emitSignatureParameters(ctor); - } - else { - write("constructor"); - if (ctor) { - emitSignatureParameters(ctor); - } - else { - // Based on EcmaScript6 section 14.5.14: Runtime Semantics: ClassDefinitionEvaluation. - // If constructor is empty, then, - // If ClassHeritageopt is present, then - // Let constructor be the result of parsing the String "constructor(... args){ super (...args);}" using the syntactic grammar with the goal symbol MethodDefinition. - // Else, - // Let constructor be the result of parsing the String "constructor( ){ }" using the syntactic grammar with the goal symbol MethodDefinition - if (baseTypeElement) { - write("(...args)"); - } - else { - write("()"); - } - } - } - write(" {"); - scopeEmitStart(node, "constructor"); - increaseIndent(); - if (ctor) { - emitDetachedComments(ctor.body.statements); - } - emitCaptureThisForNodeIfNecessary(node); - if (ctor) { - emitDefaultValueAssignments(ctor); - emitRestParameter(ctor); - if (baseTypeElement) { - var superCall = findInitialSuperCall(ctor); - if (superCall) { - writeLine(); - emit(superCall); - } - } - emitParameterPropertyAssignments(ctor); - } - else { - if (baseTypeElement) { - writeLine(); - emitStart(baseTypeElement); - if (languageVersion < 2 /* ES6 */) { - write("_super.apply(this, arguments);"); - } - else { - write("super(...args);"); - } - emitEnd(baseTypeElement); - } - } - emitPropertyDeclarations(node, getInitializedProperties(node, false)); - if (ctor) { - var statements = ctor.body.statements; - if (superCall) { - statements = statements.slice(1); - } - emitLines(statements); - } - emitTempDeclarations(true); - writeLine(); - if (ctor) { - emitLeadingCommentsOfPosition(ctor.body.statements.end); - } - decreaseIndent(); - emitToken(15 /* CloseBraceToken */, ctor ? ctor.body.statements.end : node.members.end); - scopeEmitEnd(); - emitEnd(ctor || node); - if (ctor) { - emitTrailingComments(ctor); - } - } - function emitClassExpression(node) { - return emitClassLikeDeclaration(node); - } - function emitClassDeclaration(node) { - return emitClassLikeDeclaration(node); - } - function emitClassLikeDeclaration(node) { - if (languageVersion < 2 /* ES6 */) { - emitClassLikeDeclarationBelowES6(node); - } - else { - emitClassLikeDeclarationForES6AndHigher(node); - } - } - function emitClassLikeDeclarationForES6AndHigher(node) { - var thisNodeIsDecorated = ts.nodeIsDecorated(node); - if (node.kind === 201 /* ClassDeclaration */) { - if (thisNodeIsDecorated) { - // To preserve the correct runtime semantics when decorators are applied to the class, - // the emit needs to follow one of the following rules: - // - // * For a local class declaration: - // - // @dec class C { - // } - // - // The emit should be: - // - // let C = class { - // }; - // Object.defineProperty(C, "name", { value: "C", configurable: true }); - // C = __decorate([dec], C); - // - // * For an exported class declaration: - // - // @dec export class C { - // } - // - // The emit should be: - // - // export let C = class { - // }; - // Object.defineProperty(C, "name", { value: "C", configurable: true }); - // C = __decorate([dec], C); - // - // * For a default export of a class declaration with a name: - // - // @dec default export class C { - // } - // - // The emit should be: - // - // let C = class { - // } - // Object.defineProperty(C, "name", { value: "C", configurable: true }); - // C = __decorate([dec], C); - // export default C; - // - // * For a default export of a class declaration without a name: - // - // @dec default export class { - // } - // - // The emit should be: - // - // let _default = class { - // } - // _default = __decorate([dec], _default); - // export default _default; - // - if (isES6ExportedDeclaration(node) && !(node.flags & 256 /* Default */)) { - write("export "); - } - write("let "); - emitDeclarationName(node); - write(" = "); - } - else if (isES6ExportedDeclaration(node)) { - write("export "); - if (node.flags & 256 /* Default */) { - write("default "); - } - } - } - // If the class has static properties, and it's a class expression, then we'll need - // to specialize the emit a bit. for a class expression of the form: - // - // class C { static a = 1; static b = 2; ... } - // - // We'll emit: - // - // (_temp = class C { ... }, _temp.a = 1, _temp.b = 2, _temp) - // - // This keeps the expression as an expression, while ensuring that the static parts - // of it have been initialized by the time it is used. - var staticProperties = getInitializedProperties(node, true); - var isClassExpressionWithStaticProperties = staticProperties.length > 0 && node.kind === 174 /* ClassExpression */; - var tempVariable; - if (isClassExpressionWithStaticProperties) { - tempVariable = createAndRecordTempVariable(0 /* Auto */); - write("("); - increaseIndent(); - emit(tempVariable); - write(" = "); - } - write("class"); - // check if this is an "export default class" as it may not have a name. Do not emit the name if the class is decorated. - if ((node.name || !(node.flags & 256 /* Default */)) && !thisNodeIsDecorated) { - write(" "); - emitDeclarationName(node); - } - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write(" extends "); - emit(baseTypeNode.expression); - } - write(" {"); - increaseIndent(); - scopeEmitStart(node); - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES6AndHigher(node); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - // For a decorated class, we need to assign its name (if it has one). This is because we emit - // the class as a class expression to avoid the double-binding of the identifier: - // - // let C = class { - // } - // Object.defineProperty(C, "name", { value: "C", configurable: true }); - // - if (thisNodeIsDecorated) { - write(";"); - if (node.name) { - writeLine(); - write("Object.defineProperty("); - emitDeclarationName(node); - write(", \"name\", { value: \""); - emitDeclarationName(node); - write("\", configurable: true });"); - writeLine(); - } - } - // Emit static property assignment. Because classDeclaration is lexically evaluated, - // it is safe to emit static property assignment after classDeclaration - // From ES6 specification: - // HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using - // a lexical declaration such as a LexicalDeclaration or a ClassDeclaration. - if (isClassExpressionWithStaticProperties) { - for (var _i = 0; _i < staticProperties.length; _i++) { - var property = staticProperties[_i]; - write(","); - writeLine(); - emitPropertyDeclaration(node, property, tempVariable, true); - } - write(","); - writeLine(); - emit(tempVariable); - decreaseIndent(); - write(")"); - } - else { - writeLine(); - emitPropertyDeclarations(node, staticProperties); - emitDecoratorsOfClass(node); - } - // If this is an exported class, but not on the top level (i.e. on an internal - // module), export it - if (!isES6ExportedDeclaration(node) && (node.flags & 1 /* Export */)) { - writeLine(); - emitStart(node); - emitModuleMemberName(node); - write(" = "); - emitDeclarationName(node); - emitEnd(node); - write(";"); - } - else if (isES6ExportedDeclaration(node) && (node.flags & 256 /* Default */) && thisNodeIsDecorated) { - // if this is a top level default export of decorated class, write the export after the declaration. - writeLine(); - write("export default "); - emitDeclarationName(node); - write(";"); - } - } - function emitClassLikeDeclarationBelowES6(node) { - if (node.kind === 201 /* ClassDeclaration */) { - // source file level classes in system modules are hoisted so 'var's for them are already defined - if (!isSourceFileLevelDeclarationInSystemExternalModule(node, false)) { - write("var "); - } - emitDeclarationName(node); - write(" = "); - } - write("(function ("); - var baseTypeNode = ts.getClassExtendsHeritageClauseElement(node); - if (baseTypeNode) { - write("_super"); - } - write(") {"); - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - var saveTempParameters = tempParameters; - var saveComputedPropertyNamesToGeneratedNames = computedPropertyNamesToGeneratedNames; - tempFlags = 0; - tempVariables = undefined; - tempParameters = undefined; - computedPropertyNamesToGeneratedNames = undefined; - increaseIndent(); - scopeEmitStart(node); - if (baseTypeNode) { - writeLine(); - emitStart(baseTypeNode); - write("__extends("); - emitDeclarationName(node); - write(", _super);"); - emitEnd(baseTypeNode); - } - writeLine(); - emitConstructor(node, baseTypeNode); - emitMemberFunctionsForES5AndLower(node); - emitPropertyDeclarations(node, getInitializedProperties(node, true)); - writeLine(); - emitDecoratorsOfClass(node); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end, function () { - write("return "); - emitDeclarationName(node); - }); - write(";"); - emitTempDeclarations(true); - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - tempParameters = saveTempParameters; - computedPropertyNamesToGeneratedNames = saveComputedPropertyNamesToGeneratedNames; - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - emitStart(node); - write(")("); - if (baseTypeNode) { - emit(baseTypeNode.expression); - } - write(")"); - if (node.kind === 201 /* ClassDeclaration */) { - write(";"); - } - emitEnd(node); - if (node.kind === 201 /* ClassDeclaration */) { - emitExportMemberAssignment(node); - } - if (languageVersion < 2 /* ES6 */ && node.parent === currentSourceFile && node.name) { - emitExportMemberAssignments(node.name); - } - } - function emitClassMemberPrefix(node, member) { - emitDeclarationName(node); - if (!(member.flags & 128 /* Static */)) { - write(".prototype"); - } - } - function emitDecoratorsOfClass(node) { - emitDecoratorsOfMembers(node, 0); - emitDecoratorsOfMembers(node, 128 /* Static */); - emitDecoratorsOfConstructor(node); - } - function emitDecoratorsOfConstructor(node) { - var decorators = node.decorators; - var constructor = ts.getFirstConstructorWithBody(node); - var hasDecoratedParameters = constructor && ts.forEach(constructor.parameters, ts.nodeIsDecorated); - // skip decoration of the constructor if neither it nor its parameters are decorated - if (!decorators && !hasDecoratedParameters) { - return; - } - // Emit the call to __decorate. Given the class: - // - // @dec - // class C { - // } - // - // The emit for the class is: - // - // C = __decorate([dec], C); - // - writeLine(); - emitStart(node); - emitDeclarationName(node); - write(" = __decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(constructor, argumentsWritten > 0); - emitSerializedTypeMetadata(node, argumentsWritten >= 0); - decreaseIndent(); - writeLine(); - write("], "); - emitDeclarationName(node); - write(");"); - emitEnd(node); - writeLine(); - } - function emitDecoratorsOfMembers(node, staticFlag) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - // only emit members in the correct group - if ((member.flags & 128 /* Static */) !== staticFlag) { - continue; - } - // skip members that cannot be decorated (such as the constructor) - if (!ts.nodeCanBeDecorated(member)) { - continue; - } - // skip a member if it or any of its parameters are not decorated - if (!ts.nodeOrChildIsDecorated(member)) { - continue; - } - // skip an accessor declaration if it is not the first accessor - var decorators = void 0; - var functionLikeMember = void 0; - if (ts.isAccessor(member)) { - var accessors = ts.getAllAccessorDeclarations(node.members, member); - if (member !== accessors.firstAccessor) { - continue; - } - // get the decorators from the first accessor with decorators - decorators = accessors.firstAccessor.decorators; - if (!decorators && accessors.secondAccessor) { - decorators = accessors.secondAccessor.decorators; - } - // we only decorate parameters of the set accessor - functionLikeMember = accessors.setAccessor; - } - else { - decorators = member.decorators; - // we only decorate the parameters here if this is a method - if (member.kind === 134 /* MethodDeclaration */) { - functionLikeMember = member; - } - } - // Emit the call to __decorate. Given the following: - // - // class C { - // @dec method(@dec2 x) {} - // @dec get accessor() {} - // @dec prop; - // } - // - // The emit for a method is: - // - // Object.defineProperty(C.prototype, "method", - // __decorate([ - // dec, - // __param(0, dec2), - // __metadata("design:type", Function), - // __metadata("design:paramtypes", [Object]), - // __metadata("design:returntype", void 0) - // ], C.prototype, "method", Object.getOwnPropertyDescriptor(C.prototype, "method"))); - // - // The emit for an accessor is: - // - // Object.defineProperty(C.prototype, "accessor", - // __decorate([ - // dec - // ], C.prototype, "accessor", Object.getOwnPropertyDescriptor(C.prototype, "accessor"))); - // - // The emit for a property is: - // - // __decorate([ - // dec - // ], C.prototype, "prop"); - // - writeLine(); - emitStart(member); - if (member.kind !== 132 /* PropertyDeclaration */) { - write("Object.defineProperty("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write(","); - increaseIndent(); - writeLine(); - } - write("__decorate(["); - increaseIndent(); - writeLine(); - var decoratorCount = decorators ? decorators.length : 0; - var argumentsWritten = emitList(decorators, 0, decoratorCount, true, false, false, true, function (decorator) { - emitStart(decorator); - emit(decorator.expression); - emitEnd(decorator); - }); - argumentsWritten += emitDecoratorsOfParameters(functionLikeMember, argumentsWritten > 0); - emitSerializedTypeMetadata(member, argumentsWritten > 0); - decreaseIndent(); - writeLine(); - write("], "); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - if (member.kind !== 132 /* PropertyDeclaration */) { - write(", Object.getOwnPropertyDescriptor("); - emitStart(member.name); - emitClassMemberPrefix(node, member); - write(", "); - emitExpressionForPropertyName(member.name); - emitEnd(member.name); - write("))"); - decreaseIndent(); - } - write(");"); - emitEnd(member); - writeLine(); - } - } - function emitDecoratorsOfParameters(node, leadingComma) { - var argumentsWritten = 0; - if (node) { - var parameterIndex = 0; - for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { - var parameter = _a[_i]; - if (ts.nodeIsDecorated(parameter)) { - var decorators = parameter.decorators; - argumentsWritten += emitList(decorators, 0, decorators.length, true, false, leadingComma, true, function (decorator) { - emitStart(decorator); - write("__param(" + parameterIndex + ", "); - emit(decorator.expression); - write(")"); - emitEnd(decorator); - }); - leadingComma = true; - } - ++parameterIndex; - } - } - return argumentsWritten; - } - function shouldEmitTypeMetadata(node) { - // This method determines whether to emit the "design:type" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 134 /* MethodDeclaration */: - case 136 /* GetAccessor */: - case 137 /* SetAccessor */: - case 132 /* PropertyDeclaration */: - return true; - } - return false; - } - function shouldEmitReturnTypeMetadata(node) { - // This method determines whether to emit the "design:returntype" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 134 /* MethodDeclaration */: - return true; - } - return false; - } - function shouldEmitParamTypesMetadata(node) { - // This method determines whether to emit the "design:paramtypes" metadata based on the node's kind. - // The caller should have already tested whether the node has decorators and whether the emitDecoratorMetadata - // compiler option is set. - switch (node.kind) { - case 201 /* ClassDeclaration */: - case 134 /* MethodDeclaration */: - case 137 /* SetAccessor */: - return true; - } - return false; - } - function emitSerializedTypeMetadata(node, writeComma) { - // This method emits the serialized type metadata for a decorator target. - // The caller should have already tested whether the node has decorators. - var argumentsWritten = 0; - if (compilerOptions.emitDecoratorMetadata) { - if (shouldEmitTypeMetadata(node)) { - var serializedType = resolver.serializeTypeOfNode(node, getGeneratedNameForNode); - if (serializedType) { - if (writeComma) { - write(", "); - } - writeLine(); - write("__metadata('design:type', "); - emitSerializedType(node, serializedType); - write(")"); - argumentsWritten++; - } - } - if (shouldEmitParamTypesMetadata(node)) { - var serializedTypes = resolver.serializeParameterTypesOfNode(node, getGeneratedNameForNode); - if (serializedTypes) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:paramtypes', ["); - for (var i = 0; i < serializedTypes.length; ++i) { - if (i > 0) { - write(", "); - } - emitSerializedType(node, serializedTypes[i]); - } - write("])"); - argumentsWritten++; - } - } - if (shouldEmitReturnTypeMetadata(node)) { - var serializedType = resolver.serializeReturnTypeOfNode(node, getGeneratedNameForNode); - if (serializedType) { - if (writeComma || argumentsWritten) { - write(", "); - } - writeLine(); - write("__metadata('design:returntype', "); - emitSerializedType(node, serializedType); - write(")"); - argumentsWritten++; - } - } - } - return argumentsWritten; - } - function serializeTypeNameSegment(location, path, index) { - switch (index) { - case 0: - return "typeof " + path[index] + " !== 'undefined' && " + path[index]; - case 1: - return serializeTypeNameSegment(location, path, index - 1) + "." + path[index]; - default: - var temp = createAndRecordTempVariable(0 /* Auto */).text; - return "(" + temp + " = " + serializeTypeNameSegment(location, path, index - 1) + ") && " + temp + "." + path[index]; - } - } - function emitSerializedType(location, name) { - if (typeof name === "string") { - write(name); - return; - } - else { - ts.Debug.assert(name.length > 0, "Invalid serialized type name"); - write("(" + serializeTypeNameSegment(location, name, name.length - 1) + ") || Object"); - } - } - function emitInterfaceDeclaration(node) { - emitOnlyPinnedOrTripleSlashComments(node); - } - function shouldEmitEnumDeclaration(node) { - var isConstEnum = ts.isConst(node); - return !isConstEnum || compilerOptions.preserveConstEnums || compilerOptions.separateCompilation; - } - function emitEnumDeclaration(node) { - // const enums are completely erased during compilation. - if (!shouldEmitEnumDeclaration(node)) { - return; - } - if (!(node.flags & 1 /* Export */) || isES6ExportedDeclaration(node)) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); - } - write("var "); - emit(node.name); - emitEnd(node); - write(";"); - } - writeLine(); - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") {"); - increaseIndent(); - scopeEmitStart(node); - emitLines(node.members); - decreaseIndent(); - writeLine(); - emitToken(15 /* CloseBraceToken */, node.members.end); - scopeEmitEnd(); - write(")("); - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.flags & 1 /* Export */) { - writeLine(); - emitStart(node); - write("var "); - emit(node.name); - write(" = "); - emitModuleMemberName(node); - emitEnd(node); - write(";"); - } - if (languageVersion < 2 /* ES6 */ && node.parent === currentSourceFile) { - emitExportMemberAssignments(node.name); - } - } - function emitEnumMember(node) { - var enumParent = node.parent; - emitStart(node); - write(getGeneratedNameForNode(enumParent)); - write("["); - write(getGeneratedNameForNode(enumParent)); - write("["); - emitExpressionForPropertyName(node.name); - write("] = "); - writeEnumMemberDeclarationValue(node); - write("] = "); - emitExpressionForPropertyName(node.name); - emitEnd(node); - write(";"); - } - function writeEnumMemberDeclarationValue(member) { - var value = resolver.getConstantValue(member); - if (value !== undefined) { - write(value.toString()); - return; - } - else if (member.initializer) { - emit(member.initializer); - } - else { - write("undefined"); - } - } - function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) { - if (moduleDeclaration.body.kind === 205 /* ModuleDeclaration */) { - var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body); - return recursiveInnerModule || moduleDeclaration.body; - } - } - function shouldEmitModuleDeclaration(node) { - return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.separateCompilation); - } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ && !!(resolver.getNodeCheckFlags(node) & 2048 /* LexicalModuleMergesWithClass */); - } - function emitModuleDeclaration(node) { - // Emit only if this module is non-ambient. - var shouldEmit = shouldEmitModuleDeclaration(node); - if (!shouldEmit) { - return emitOnlyPinnedOrTripleSlashComments(node); - } - var hoistedInDeclarationScope = isSourceFileLevelDeclarationInSystemExternalModule(node, false); - var emitVarForModule = !hoistedInDeclarationScope && !isModuleMergedWithES6Class(node); - if (emitVarForModule) { - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); - } - write("var "); - emit(node.name); - write(";"); - emitEnd(node); - writeLine(); - } - emitStart(node); - write("(function ("); - emitStart(node.name); - write(getGeneratedNameForNode(node)); - emitEnd(node.name); - write(") "); - if (node.body.kind === 206 /* ModuleBlock */) { - var saveTempFlags = tempFlags; - var saveTempVariables = tempVariables; - tempFlags = 0; - tempVariables = undefined; - emit(node.body); - tempFlags = saveTempFlags; - tempVariables = saveTempVariables; - } - else { - write("{"); - increaseIndent(); - scopeEmitStart(node); - emitCaptureThisForNodeIfNecessary(node); - writeLine(); - emit(node.body); - decreaseIndent(); - writeLine(); - var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body; - emitToken(15 /* CloseBraceToken */, moduleBlock.statements.end); - scopeEmitEnd(); - } - write(")("); - // write moduleDecl = containingModule.m only if it is not exported es6 module member - if ((node.flags & 1 /* Export */) && !isES6ExportedDeclaration(node)) { - emit(node.name); - write(" = "); - } - emitModuleMemberName(node); - write(" || ("); - emitModuleMemberName(node); - write(" = {}));"); - emitEnd(node); - if (!isES6ExportedDeclaration(node) && node.name.kind === 65 /* Identifier */ && node.parent === currentSourceFile) { - if (compilerOptions.module === 3 /* System */ && (node.flags & 1 /* Export */)) { - writeLine(); - write(exportFunctionForFile + "(\""); - emitDeclarationName(node); - write("\", "); - emitDeclarationName(node); - write(")"); - } - emitExportMemberAssignments(node.name); - } - } - function emitRequire(moduleName) { - if (moduleName.kind === 8 /* StringLiteral */) { - write("require("); - emitStart(moduleName); - emitLiteral(moduleName); - emitEnd(moduleName); - emitToken(17 /* CloseParenToken */, moduleName.end); - } - else { - write("require()"); - } - } - function getNamespaceDeclarationNode(node) { - if (node.kind === 208 /* ImportEqualsDeclaration */) { - return node; - } - var importClause = node.importClause; - if (importClause && importClause.namedBindings && importClause.namedBindings.kind === 211 /* NamespaceImport */) { - return importClause.namedBindings; - } - } - function isDefaultImport(node) { - return node.kind === 209 /* ImportDeclaration */ && node.importClause && !!node.importClause.name; - } - function emitExportImportAssignments(node) { - if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node)) { - emitExportMemberAssignments(node.name); - } - ts.forEachChild(node, emitExportImportAssignments); - } - function emitImportDeclaration(node) { - if (languageVersion < 2 /* ES6 */) { - return emitExternalImportDeclaration(node); - } - // ES6 import - if (node.importClause) { - var shouldEmitDefaultBindings = resolver.isReferencedAliasDeclaration(node.importClause); - var shouldEmitNamedBindings = node.importClause.namedBindings && resolver.isReferencedAliasDeclaration(node.importClause.namedBindings, true); - if (shouldEmitDefaultBindings || shouldEmitNamedBindings) { - write("import "); - emitStart(node.importClause); - if (shouldEmitDefaultBindings) { - emit(node.importClause.name); - if (shouldEmitNamedBindings) { - write(", "); - } - } - if (shouldEmitNamedBindings) { - emitLeadingComments(node.importClause.namedBindings); - emitStart(node.importClause.namedBindings); - if (node.importClause.namedBindings.kind === 211 /* NamespaceImport */) { - write("* as "); - emit(node.importClause.namedBindings.name); - } - else { - write("{ "); - emitExportOrImportSpecifierList(node.importClause.namedBindings.elements, resolver.isReferencedAliasDeclaration); - write(" }"); - } - emitEnd(node.importClause.namedBindings); - emitTrailingComments(node.importClause.namedBindings); - } - emitEnd(node.importClause); - write(" from "); - emit(node.moduleSpecifier); - write(";"); - } - } - else { - write("import "); - emit(node.moduleSpecifier); - write(";"); - } - } - function emitExternalImportDeclaration(node) { - if (ts.contains(externalImports, node)) { - var isExportedImport = node.kind === 208 /* ImportEqualsDeclaration */ && (node.flags & 1 /* Export */) !== 0; - var namespaceDeclaration = getNamespaceDeclarationNode(node); - if (compilerOptions.module !== 2 /* AMD */) { - emitLeadingComments(node); - emitStart(node); - if (namespaceDeclaration && !isDefaultImport(node)) { - // import x = require("foo") - // import * as x from "foo" - if (!isExportedImport) - write("var "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - } - else { - // import "foo" - // import x from "foo" - // import { x, y } from "foo" - // import d, * as x from "foo" - // import d, { x, y } from "foo" - var isNakedImport = 209 /* ImportDeclaration */ && !node.importClause; - if (!isNakedImport) { - write("var "); - write(getGeneratedNameForNode(node)); - write(" = "); - } - } - emitRequire(ts.getExternalModuleName(node)); - if (namespaceDeclaration && isDefaultImport(node)) { - // import d, * as x from "foo" - write(", "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - } - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - else { - if (isExportedImport) { - emitModuleMemberName(namespaceDeclaration); - write(" = "); - emit(namespaceDeclaration.name); - write(";"); - } - else if (namespaceDeclaration && isDefaultImport(node)) { - // import d, * as x from "foo" - write("var "); - emitModuleMemberName(namespaceDeclaration); - write(" = "); - write(getGeneratedNameForNode(node)); - write(";"); - } - emitExportImportAssignments(node); - } - } - } - function emitImportEqualsDeclaration(node) { - if (ts.isExternalModuleImportEqualsDeclaration(node)) { - emitExternalImportDeclaration(node); - return; - } - // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when - // - current file is not external module - // - import declaration is top level and target is value imported by entity name - if (resolver.isReferencedAliasDeclaration(node) || - (!ts.isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) { - emitLeadingComments(node); - emitStart(node); - if (isES6ExportedDeclaration(node)) { - write("export "); - write("var "); - } - else if (!(node.flags & 1 /* Export */)) { - write("var "); - } - emitModuleMemberName(node); - write(" = "); - emit(node.moduleReference); - write(";"); - emitEnd(node); - emitExportImportAssignments(node); - emitTrailingComments(node); - } - } - function emitExportDeclaration(node) { - ts.Debug.assert(compilerOptions.module !== 3 /* System */); - if (languageVersion < 2 /* ES6 */) { - if (node.moduleSpecifier && (!node.exportClause || resolver.isValueAliasDeclaration(node))) { - emitStart(node); - var generatedName = getGeneratedNameForNode(node); - if (node.exportClause) { - // export { x, y, ... } from "foo" - if (compilerOptions.module !== 2 /* AMD */) { - write("var "); - write(generatedName); - write(" = "); - emitRequire(ts.getExternalModuleName(node)); - write(";"); - } - for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) { - var specifier = _a[_i]; - if (resolver.isValueAliasDeclaration(specifier)) { - writeLine(); - emitStart(specifier); - emitContainingModuleName(specifier); - write("."); - emitNodeWithoutSourceMap(specifier.name); - write(" = "); - write(generatedName); - write("."); - emitNodeWithoutSourceMap(specifier.propertyName || specifier.name); - write(";"); - emitEnd(specifier); - } - } - } - else { - // export * from "foo" - writeLine(); - write("__export("); - if (compilerOptions.module !== 2 /* AMD */) { - emitRequire(ts.getExternalModuleName(node)); - } - else { - write(generatedName); - } - write(");"); - } - emitEnd(node); - } - } - else { - if (!node.exportClause || resolver.isValueAliasDeclaration(node)) { - emitStart(node); - write("export "); - if (node.exportClause) { - // export { x, y, ... } - write("{ "); - emitExportOrImportSpecifierList(node.exportClause.elements, resolver.isValueAliasDeclaration); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitNodeWithoutSourceMap(node.moduleSpecifier); - } - write(";"); - emitEnd(node); - } - } - } - function emitExportOrImportSpecifierList(specifiers, shouldEmit) { - ts.Debug.assert(languageVersion >= 2 /* ES6 */); - var needsComma = false; - for (var _i = 0; _i < specifiers.length; _i++) { - var specifier = specifiers[_i]; - if (shouldEmit(specifier)) { - if (needsComma) { - write(", "); - } - emitStart(specifier); - if (specifier.propertyName) { - emitNodeWithoutSourceMap(specifier.propertyName); - write(" as "); - } - emitNodeWithoutSourceMap(specifier.name); - emitEnd(specifier); - needsComma = true; - } - } - } - function emitExportAssignment(node) { - if (!node.isExportEquals && resolver.isValueAliasDeclaration(node)) { - if (languageVersion >= 2 /* ES6 */) { - writeLine(); - emitStart(node); - write("export default "); - var expression = node.expression; - emit(expression); - if (expression.kind !== 200 /* FunctionDeclaration */ && - expression.kind !== 201 /* ClassDeclaration */) { - write(";"); - } - emitEnd(node); - } - else { - writeLine(); - emitStart(node); - if (compilerOptions.module === 3 /* System */) { - write(exportFunctionForFile + "(\"default\","); - emit(node.expression); - write(")"); - } - else { - emitContainingModuleName(node); - if (languageVersion === 0 /* ES3 */) { - write("[\"default\"] = "); - } - else { - write(".default = "); - } - emit(node.expression); - } - write(";"); - emitEnd(node); - } - } - } - function collectExternalModuleInfo(sourceFile) { - externalImports = []; - exportSpecifiers = {}; - exportEquals = undefined; - hasExportStars = false; - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var node = _a[_i]; - switch (node.kind) { - case 209 /* ImportDeclaration */: - if (!node.importClause || - resolver.isReferencedAliasDeclaration(node.importClause, true)) { - // import "mod" - // import x from "mod" where x is referenced - // import * as x from "mod" where x is referenced - // import { x, y } from "mod" where at least one import is referenced - externalImports.push(node); - } - break; - case 208 /* ImportEqualsDeclaration */: - if (node.moduleReference.kind === 219 /* ExternalModuleReference */ && resolver.isReferencedAliasDeclaration(node)) { - // import x = require("mod") where x is referenced - externalImports.push(node); - } - break; - case 215 /* ExportDeclaration */: - if (node.moduleSpecifier) { - if (!node.exportClause) { - // export * from "mod" - externalImports.push(node); - hasExportStars = true; - } - else if (resolver.isValueAliasDeclaration(node)) { - // export { x, y } from "mod" where at least one export is a value symbol - externalImports.push(node); - } - } - else { - // export { x, y } - for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { - var specifier = _c[_b]; - var name_6 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_6] || (exportSpecifiers[name_6] = [])).push(specifier); - } - } - break; - case 214 /* ExportAssignment */: - if (node.isExportEquals && !exportEquals) { - // export = x - exportEquals = node; - } - break; - } - } - } - function emitExportStarHelper() { - if (hasExportStars) { - writeLine(); - write("function __export(m) {"); - increaseIndent(); - writeLine(); - write("for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];"); - decreaseIndent(); - writeLine(); - write("}"); - } - } - function getLocalNameForExternalImport(importNode) { - var namespaceDeclaration = getNamespaceDeclarationNode(importNode); - if (namespaceDeclaration && !isDefaultImport(importNode)) { - return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name); - } - else { - return getGeneratedNameForNode(importNode); - } - } - function getExternalModuleNameText(importNode) { - var moduleName = ts.getExternalModuleName(importNode); - if (moduleName.kind === 8 /* StringLiteral */) { - return getLiteralText(moduleName); - } - return undefined; - } - function emitVariableDeclarationsForImports() { - if (externalImports.length === 0) { - return; - } - writeLine(); - var started = false; - for (var _i = 0; _i < externalImports.length; _i++) { - var importNode = externalImports[_i]; - // do not create variable declaration for exports and imports that lack import clause - var skipNode = importNode.kind === 215 /* ExportDeclaration */ || - (importNode.kind === 209 /* ImportDeclaration */ && !importNode.importClause); - if (skipNode) { - continue; - } - if (!started) { - write("var "); - started = true; - } - else { - write(", "); - } - write(getLocalNameForExternalImport(importNode)); - } - if (started) { - write(";"); - } - } - function hoistTopLevelVariableAndFunctionDeclarations(node) { - // per ES6 spec: - // 15.2.1.16.4 ModuleDeclarationInstantiation() Concrete Method - // - var declarations are initialized to undefined - 14.a.ii - // - function/generator declarations are instantiated - 16.a.iv - // this means that after module is instantiated but before its evaluation - // exported functions are already accessible at import sites - // in theory we should hoist only exported functions and its dependencies - // in practice to simplify things we'll hoist all source level functions and variable declaration - // including variables declarations for module and class declarations - var hoistedVars; - var hoistedFunctionDeclarations; - visit(node); - if (hoistedVars) { - writeLine(); - write("var "); - for (var i = 0; i < hoistedVars.length; ++i) { - var local = hoistedVars[i]; - if (i !== 0) { - write(", "); - } - if (local.kind === 201 /* ClassDeclaration */ || local.kind === 205 /* ModuleDeclaration */) { - emitDeclarationName(local); - } - else { - emit(local); - } - } - write(";"); - } - if (hoistedFunctionDeclarations) { - for (var _i = 0; _i < hoistedFunctionDeclarations.length; _i++) { - var f = hoistedFunctionDeclarations[_i]; - writeLine(); - emit(f); - } - } - function visit(node) { - if (node.kind === 200 /* FunctionDeclaration */) { - if (!hoistedFunctionDeclarations) { - hoistedFunctionDeclarations = []; - } - hoistedFunctionDeclarations.push(node); - return; - } - if (node.kind === 201 /* ClassDeclaration */) { - // TODO: rename block scoped classes - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - return; - } - if (node.kind === 205 /* ModuleDeclaration */ && shouldEmitModuleDeclaration(node)) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(node); - return; - } - if (node.kind === 198 /* VariableDeclaration */ || node.kind === 152 /* BindingElement */) { - if (shouldHoistVariable(node, false)) { - var name_7 = node.name; - if (name_7.kind === 65 /* Identifier */) { - if (!hoistedVars) { - hoistedVars = []; - } - hoistedVars.push(name_7); - } - else { - ts.forEachChild(name_7, visit); - } - } - return; - } - if (ts.isBindingPattern(node)) { - ts.forEach(node.elements, visit); - return; - } - if (!ts.isDeclaration(node)) { - ts.forEachChild(node, visit); - } - } - } - function shouldHoistVariable(node, checkIfSourceFileLevelDecl) { - if (checkIfSourceFileLevelDecl && !isSourceFileLevelDeclarationInSystemExternalModule(node, false)) { - return false; - } - // hoist variable if - // - it is not block scoped - // - it is top level block scoped - // if block scoped variables are nested in some another block then - // no other functions can use them except ones that are defined at least in the same block - return (ts.getCombinedNodeFlags(node) & 12288 /* BlockScoped */) === 0 || - ts.getEnclosingBlockScopeContainer(node).kind === 227 /* SourceFile */; - } - function isCurrentFileSystemExternalModule() { - return compilerOptions.module === 3 /* System */ && ts.isExternalModule(currentSourceFile); - } - function emitSystemModuleBody(node, startIndex) { - // shape of the body in system modules: - // function (exports) { - // - // - // - // return { - // setters: [ - // - // ], - // execute: function() { - // - // } - // } - // - // } - // I.e: - // import {x} from 'file1' - // var y = 1; - // export function foo() { return y + x(); } - // console.log(y); - // will be transformed to - // function(exports) { - // var file1; // local alias - // var y; - // function foo() { return y + file1.x(); } - // exports("foo", foo); - // return { - // setters: [ - // function(v) { file1 = v } - // ], - // execute(): function() { - // y = 1; - // console.log(y); - // } - // }; - // } - emitVariableDeclarationsForImports(); - writeLine(); - hoistTopLevelVariableAndFunctionDeclarations(node); - writeLine(); - write("return {"); - increaseIndent(); - writeLine(); - emitSetters(); - writeLine(); - emitExecute(node, startIndex); - emitTempDeclarations(true); - decreaseIndent(); - writeLine(); - write("}"); // return - } - function emitSetters() { - write("setters:["); - for (var i = 0; i < externalImports.length; ++i) { - if (i !== 0) { - write(","); - } - writeLine(); - increaseIndent(); - var importNode = externalImports[i]; - var importVariableName = getLocalNameForExternalImport(importNode) || ""; - var parameterName = "_" + importVariableName; - write("function (" + parameterName + ") {"); - switch (importNode.kind) { - case 209 /* ImportDeclaration */: - if (!importNode.importClause) { - // 'import "..."' case - // module is imported only for side-effects, setter body will be empty - break; - } - // fall-through - case 208 /* ImportEqualsDeclaration */: - ts.Debug.assert(importVariableName !== ""); - increaseIndent(); - writeLine(); - // save import into the local - write(importVariableName + " = " + parameterName); - writeLine(); - var defaultName = importNode.kind === 209 /* ImportDeclaration */ - ? importNode.importClause.name - : importNode.name; - if (defaultName) { - // emit re-export for imported default name - // import n1 from 'foo1' - // import n2 = require('foo2') - // export {n1} - // export {n2} - emitExportMemberAssignments(defaultName); - writeLine(); - } - if (importNode.kind === 209 /* ImportDeclaration */ && - importNode.importClause.namedBindings) { - var namedBindings = importNode.importClause.namedBindings; - if (namedBindings.kind === 211 /* NamespaceImport */) { - // emit re-export for namespace - // import * as n from 'foo' - // export {n} - emitExportMemberAssignments(namedBindings.name); - writeLine(); - } - else { - // emit re-exports for named imports - // import {a, b} from 'foo' - // export {a, b as c} - for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) { - var element = _a[_i]; - emitExportMemberAssignments(element.name || element.propertyName); - writeLine(); - } - } - } - decreaseIndent(); - break; - case 215 /* ExportDeclaration */: - ts.Debug.assert(importVariableName !== ""); - increaseIndent(); - if (importNode.exportClause) { - // export {a, b as c} from 'foo' - // emit as: - // exports('a', _foo["a"]) - // exports('c', _foo["b"]) - for (var _b = 0, _c = importNode.exportClause.elements; _b < _c.length; _b++) { - var e = _c[_b]; - writeLine(); - write(exportFunctionForFile + "(\""); - emitNodeWithoutSourceMap(e.name); - write("\", " + parameterName + "[\""); - emitNodeWithoutSourceMap(e.propertyName || e.name); - write("\"]);"); - } - } - else { - writeLine(); - // export * from 'foo' - // emit as: - // for (var n in _foo) exports(n, _foo[n]); - // NOTE: it is safe to use name 'n' since parameter name always starts with '_' - write("for (var n in " + parameterName + ") " + exportFunctionForFile + "(n, " + parameterName + "[n]);"); - } - writeLine(); - decreaseIndent(); - break; - } - write("}"); - decreaseIndent(); - } - write("],"); - } - function emitExecute(node, startIndex) { - write("execute: function() {"); - increaseIndent(); - writeLine(); - for (var i = startIndex; i < node.statements.length; ++i) { - var statement = node.statements[i]; - // - imports/exports are not emitted for system modules - // - function declarations are not emitted because they were already hoisted - switch (statement.kind) { - case 215 /* ExportDeclaration */: - case 209 /* ImportDeclaration */: - case 208 /* ImportEqualsDeclaration */: - case 200 /* FunctionDeclaration */: - continue; - } - writeLine(); - emit(statement); - } - decreaseIndent(); - writeLine(); - write("}"); // execute - } - function emitSystemModule(node, startIndex) { - collectExternalModuleInfo(node); - // System modules has the following shape - // System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */}) - // 'exports' here is a function 'exports(name: string, value: T): T' that is used to publish exported values. - // 'exports' returns its 'value' argument so in most cases expressions - // that mutate exported values can be rewritten as: - // expr -> exports('name', expr). - // The only exception in this rule is postfix unary operators, - // see comment to 'emitPostfixUnaryExpression' for more details - ts.Debug.assert(!exportFunctionForFile); - // make sure that name of 'exports' function does not conflict with existing identifiers - exportFunctionForFile = makeUniqueName("exports"); - write("System.register(["); - for (var i = 0; i < externalImports.length; ++i) { - var text = getExternalModuleNameText(externalImports[i]); - if (i !== 0) { - write(", "); - } - write(text); - } - write("], function(" + exportFunctionForFile + ") {"); - writeLine(); - increaseIndent(); - emitCaptureThisForNodeIfNecessary(node); - emitSystemModuleBody(node, startIndex); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitAMDModule(node, startIndex) { - collectExternalModuleInfo(node); - // An AMD define function has the following shape: - // define(id?, dependencies?, factory); - // - // This has the shape of - // define(name, ["module1", "module2"], function (module1Alias) { - // The location of the alias in the parameter list in the factory function needs to - // match the position of the module name in the dependency list. - // - // To ensure this is true in cases of modules with no aliases, e.g.: - // `import "module"` or `` - // we need to add modules without alias names to the end of the dependencies list - var aliasedModuleNames = []; // names of modules with corresponding parameter in the - // factory function. - var unaliasedModuleNames = []; // names of modules with no corresponding parameters in - // factory function. - var importAliasNames = []; // names of the parameters in the factory function; these - // parameters need to match the indexes of the corresponding - // module names in aliasedModuleNames. - // Fill in amd-dependency tags - for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) { - var amdDependency = _a[_i]; - if (amdDependency.name) { - aliasedModuleNames.push("\"" + amdDependency.path + "\""); - importAliasNames.push(amdDependency.name); - } - else { - unaliasedModuleNames.push("\"" + amdDependency.path + "\""); - } - } - for (var _b = 0; _b < externalImports.length; _b++) { - var importNode = externalImports[_b]; - // Find the name of the external module - var externalModuleName = getExternalModuleNameText(importNode); - // Find the name of the module alias, if there is one - var importAliasName = getLocalNameForExternalImport(importNode); - if (importAliasName) { - aliasedModuleNames.push(externalModuleName); - importAliasNames.push(importAliasName); - } - else { - unaliasedModuleNames.push(externalModuleName); - } - } - writeLine(); - write("define("); - if (node.amdModuleName) { - write("\"" + node.amdModuleName + "\", "); - } - write("[\"require\", \"exports\""); - if (aliasedModuleNames.length) { - write(", "); - write(aliasedModuleNames.join(", ")); - } - if (unaliasedModuleNames.length) { - write(", "); - write(unaliasedModuleNames.join(", ")); - } - write("], function (require, exports"); - if (importAliasNames.length) { - write(", "); - write(importAliasNames.join(", ")); - } - write(") {"); - increaseIndent(); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - emitExportEquals(true); - decreaseIndent(); - writeLine(); - write("});"); - } - function emitCommonJSModule(node, startIndex) { - collectExternalModuleInfo(node); - emitExportStarHelper(); - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - emitExportEquals(false); - } - function emitES6Module(node, startIndex) { - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStars = false; - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - // Emit exportDefault if it exists will happen as part - // or normal statement emit. - } - function emitExportEquals(emitAsReturn) { - if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { - writeLine(); - emitStart(exportEquals); - write(emitAsReturn ? "return " : "module.exports = "); - emit(exportEquals.expression); - write(";"); - emitEnd(exportEquals); - } - } - function emitDirectivePrologues(statements, startWithNewLine) { - for (var i = 0; i < statements.length; ++i) { - if (ts.isPrologueDirective(statements[i])) { - if (startWithNewLine || i > 0) { - writeLine(); - } - emit(statements[i]); - } - else { - // return index of the first non prologue directive - return i; - } - } - return statements.length; - } - function writeLines(text) { - var lines = text.split(/\r\n|\r|\n/g); - for (var i = 0; i < lines.length; ++i) { - var line = lines[i]; - if (line.length) { - writeLine(); - write(line); - } - } - } - function emitSourceFileNode(node) { - // Start new file on new line - writeLine(); - emitDetachedComments(node); - // emit prologue directives prior to __extends - var startIndex = emitDirectivePrologues(node.statements, false); - // Only Emit __extends function when target ES5. - // For target ES6 and above, we can emit classDeclaration as is. - if ((languageVersion < 2 /* ES6 */) && (!extendsEmitted && resolver.getNodeCheckFlags(node) & 8 /* EmitExtends */)) { - writeLines(extendsHelper); - extendsEmitted = true; - } - if (!decorateEmitted && resolver.getNodeCheckFlags(node) & 512 /* EmitDecorate */) { - writeLines(decorateHelper); - if (compilerOptions.emitDecoratorMetadata) { - writeLines(metadataHelper); - } - decorateEmitted = true; - } - if (!paramEmitted && resolver.getNodeCheckFlags(node) & 1024 /* EmitParam */) { - writeLines(paramHelper); - paramEmitted = true; - } - if (ts.isExternalModule(node)) { - if (languageVersion >= 2 /* ES6 */) { - emitES6Module(node, startIndex); - } - else if (compilerOptions.module === 2 /* AMD */) { - emitAMDModule(node, startIndex); - } - else if (compilerOptions.module === 3 /* System */) { - emitSystemModule(node, startIndex); - } - else { - emitCommonJSModule(node, startIndex); - } - } - else { - externalImports = undefined; - exportSpecifiers = undefined; - exportEquals = undefined; - hasExportStars = false; - emitCaptureThisForNodeIfNecessary(node); - emitLinesStartingAt(node.statements, startIndex); - emitTempDeclarations(true); - } - emitLeadingComments(node.endOfFileToken); - } - function emitNodeWithoutSourceMap(node, allowGeneratedIdentifiers) { - if (!node) { - return; - } - if (node.flags & 2 /* Ambient */) { - return emitOnlyPinnedOrTripleSlashComments(node); - } - var emitComments = shouldEmitLeadingAndTrailingComments(node); - if (emitComments) { - emitLeadingComments(node); - } - emitJavaScriptWorker(node, allowGeneratedIdentifiers); - if (emitComments) { - emitTrailingComments(node); - } - } - function shouldEmitLeadingAndTrailingComments(node) { - switch (node.kind) { - // All of these entities are emitted in a specialized fashion. As such, we allow - // the specialized methods for each to handle the comments on the nodes. - case 202 /* InterfaceDeclaration */: - case 200 /* FunctionDeclaration */: - case 209 /* ImportDeclaration */: - case 208 /* ImportEqualsDeclaration */: - case 203 /* TypeAliasDeclaration */: - case 214 /* ExportAssignment */: - return false; - case 205 /* ModuleDeclaration */: - // Only emit the leading/trailing comments for a module if we're actually - // emitting the module as well. - return shouldEmitModuleDeclaration(node); - case 204 /* EnumDeclaration */: - // Only emit the leading/trailing comments for an enum if we're actually - // emitting the module as well. - return shouldEmitEnumDeclaration(node); - } - // If this is the expression body of an arrow function that we're down-leveling, - // then we don't want to emit comments when we emit the body. It will have already - // been taken care of when we emitted the 'return' statement for the function - // expression body. - if (node.kind !== 179 /* Block */ && - node.parent && - node.parent.kind === 163 /* ArrowFunction */ && - node.parent.body === node && - compilerOptions.target <= 1 /* ES5 */) { - return false; - } - // Emit comments for everything else. - return true; - } - function emitJavaScriptWorker(node, allowGeneratedIdentifiers) { - if (allowGeneratedIdentifiers === void 0) { allowGeneratedIdentifiers = true; } - // Check if the node can be emitted regardless of the ScriptTarget - switch (node.kind) { - case 65 /* Identifier */: - return emitIdentifier(node, allowGeneratedIdentifiers); - case 129 /* Parameter */: - return emitParameter(node); - case 134 /* MethodDeclaration */: - case 133 /* MethodSignature */: - return emitMethod(node); - case 136 /* GetAccessor */: - case 137 /* SetAccessor */: - return emitAccessor(node); - case 93 /* ThisKeyword */: - return emitThis(node); - case 91 /* SuperKeyword */: - return emitSuper(node); - case 89 /* NullKeyword */: - return write("null"); - case 95 /* TrueKeyword */: - return write("true"); - case 80 /* FalseKeyword */: - return write("false"); - case 7 /* NumericLiteral */: - case 8 /* StringLiteral */: - case 9 /* RegularExpressionLiteral */: - case 10 /* NoSubstitutionTemplateLiteral */: - case 11 /* TemplateHead */: - case 12 /* TemplateMiddle */: - case 13 /* TemplateTail */: - return emitLiteral(node); - case 171 /* TemplateExpression */: - return emitTemplateExpression(node); - case 176 /* TemplateSpan */: - return emitTemplateSpan(node); - case 126 /* QualifiedName */: - return emitQualifiedName(node); - case 150 /* ObjectBindingPattern */: - return emitObjectBindingPattern(node); - case 151 /* ArrayBindingPattern */: - return emitArrayBindingPattern(node); - case 152 /* BindingElement */: - return emitBindingElement(node); - case 153 /* ArrayLiteralExpression */: - return emitArrayLiteral(node); - case 154 /* ObjectLiteralExpression */: - return emitObjectLiteral(node); - case 224 /* PropertyAssignment */: - return emitPropertyAssignment(node); - case 225 /* ShorthandPropertyAssignment */: - return emitShorthandPropertyAssignment(node); - case 127 /* ComputedPropertyName */: - return emitComputedPropertyName(node); - case 155 /* PropertyAccessExpression */: - return emitPropertyAccess(node); - case 156 /* ElementAccessExpression */: - return emitIndexedAccess(node); - case 157 /* CallExpression */: - return emitCallExpression(node); - case 158 /* NewExpression */: - return emitNewExpression(node); - case 159 /* TaggedTemplateExpression */: - return emitTaggedTemplateExpression(node); - case 160 /* TypeAssertionExpression */: - return emit(node.expression); - case 161 /* ParenthesizedExpression */: - return emitParenExpression(node); - case 200 /* FunctionDeclaration */: - case 162 /* FunctionExpression */: - case 163 /* ArrowFunction */: - return emitFunctionDeclaration(node); - case 164 /* DeleteExpression */: - return emitDeleteExpression(node); - case 165 /* TypeOfExpression */: - return emitTypeOfExpression(node); - case 166 /* VoidExpression */: - return emitVoidExpression(node); - case 167 /* PrefixUnaryExpression */: - return emitPrefixUnaryExpression(node); - case 168 /* PostfixUnaryExpression */: - return emitPostfixUnaryExpression(node); - case 169 /* BinaryExpression */: - return emitBinaryExpression(node); - case 170 /* ConditionalExpression */: - return emitConditionalExpression(node); - case 173 /* SpreadElementExpression */: - return emitSpreadElementExpression(node); - case 172 /* YieldExpression */: - return emitYieldExpression(node); - case 175 /* OmittedExpression */: - return; - case 179 /* Block */: - case 206 /* ModuleBlock */: - return emitBlock(node); - case 180 /* VariableStatement */: - return emitVariableStatement(node); - case 181 /* EmptyStatement */: - return write(";"); - case 182 /* ExpressionStatement */: - return emitExpressionStatement(node); - case 183 /* IfStatement */: - return emitIfStatement(node); - case 184 /* DoStatement */: - return emitDoStatement(node); - case 185 /* WhileStatement */: - return emitWhileStatement(node); - case 186 /* ForStatement */: - return emitForStatement(node); - case 188 /* ForOfStatement */: - case 187 /* ForInStatement */: - return emitForInOrForOfStatement(node); - case 189 /* ContinueStatement */: - case 190 /* BreakStatement */: - return emitBreakOrContinueStatement(node); - case 191 /* ReturnStatement */: - return emitReturnStatement(node); - case 192 /* WithStatement */: - return emitWithStatement(node); - case 193 /* SwitchStatement */: - return emitSwitchStatement(node); - case 220 /* CaseClause */: - case 221 /* DefaultClause */: - return emitCaseOrDefaultClause(node); - case 194 /* LabeledStatement */: - return emitLabelledStatement(node); - case 195 /* ThrowStatement */: - return emitThrowStatement(node); - case 196 /* TryStatement */: - return emitTryStatement(node); - case 223 /* CatchClause */: - return emitCatchClause(node); - case 197 /* DebuggerStatement */: - return emitDebuggerStatement(node); - case 198 /* VariableDeclaration */: - return emitVariableDeclaration(node); - case 174 /* ClassExpression */: - return emitClassExpression(node); - case 201 /* ClassDeclaration */: - return emitClassDeclaration(node); - case 202 /* InterfaceDeclaration */: - return emitInterfaceDeclaration(node); - case 204 /* EnumDeclaration */: - return emitEnumDeclaration(node); - case 226 /* EnumMember */: - return emitEnumMember(node); - case 205 /* ModuleDeclaration */: - return emitModuleDeclaration(node); - case 209 /* ImportDeclaration */: - return emitImportDeclaration(node); - case 208 /* ImportEqualsDeclaration */: - return emitImportEqualsDeclaration(node); - case 215 /* ExportDeclaration */: - return emitExportDeclaration(node); - case 214 /* ExportAssignment */: - return emitExportAssignment(node); - case 227 /* SourceFile */: - return emitSourceFileNode(node); - } - } - function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && lastOrUndefined(detachedCommentsInfo).nodePos === pos; - } - function getLeadingCommentsWithoutDetachedComments() { - // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); - if (detachedCommentsInfo.length - 1) { - detachedCommentsInfo.pop(); - } - else { - detachedCommentsInfo = undefined; - } - return leadingComments; - } - function filterComments(ranges, onlyPinnedOrTripleSlashComments) { - // If we're removing comments, then we want to strip out all but the pinned or - // triple slash comments. - if (ranges && onlyPinnedOrTripleSlashComments) { - ranges = ts.filter(ranges, isPinnedOrTripleSlashComment); - if (ranges.length === 0) { - return undefined; - } - } - return ranges; - } - function getLeadingCommentsToEmit(node) { - // Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments - if (node.parent) { - if (node.parent.kind === 227 /* SourceFile */ || node.pos !== node.parent.pos) { - if (hasDetachedComments(node.pos)) { - // get comments without detached comments - return getLeadingCommentsWithoutDetachedComments(); - } - else { - // get the leading comments from the node - return ts.getLeadingCommentRangesOfNode(node, currentSourceFile); - } - } - } - } - function getTrailingCommentsToEmit(node) { - // Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments - if (node.parent) { - if (node.parent.kind === 227 /* SourceFile */ || node.end !== node.parent.end) { - return ts.getTrailingCommentRanges(currentSourceFile.text, node.end); - } - } - } - function emitOnlyPinnedOrTripleSlashComments(node) { - emitLeadingCommentsWorker(node, true); - } - function emitLeadingComments(node) { - return emitLeadingCommentsWorker(node, compilerOptions.removeComments); - } - function emitLeadingCommentsWorker(node, onlyPinnedOrTripleSlashComments) { - // If the caller only wants pinned or triple slash comments, then always filter - // down to that set. Otherwise, filter based on the current compiler options. - var leadingComments = filterComments(getLeadingCommentsToEmit(node), onlyPinnedOrTripleSlashComments); - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); - } - function emitTrailingComments(node) { - // Emit the trailing comments only if the parent's end doesn't match - var trailingComments = filterComments(getTrailingCommentsToEmit(node), compilerOptions.removeComments); - // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/ - ts.emitComments(currentSourceFile, writer, trailingComments, false, newLine, writeComment); - } - function emitLeadingCommentsOfPosition(pos) { - var leadingComments; - if (hasDetachedComments(pos)) { - // get comments without detached comments - leadingComments = getLeadingCommentsWithoutDetachedComments(); - } - else { - // get the leading comments from the node - leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, pos); - } - leadingComments = filterComments(leadingComments, compilerOptions.removeComments); - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments); - // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space - ts.emitComments(currentSourceFile, writer, leadingComments, true, newLine, writeComment); - } - function emitDetachedComments(node) { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, node.pos); - if (leadingComments) { - var detachedComments = []; - var lastComment; - ts.forEach(leadingComments, function (comment) { - if (lastComment) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastComment.end); - var commentLine = ts.getLineOfLocalPosition(currentSourceFile, comment.pos); - if (commentLine >= lastCommentLine + 2) { - // There was a blank line between the last comment and this comment. This - // comment is not part of the copyright comments. Return what we have so - // far. - return detachedComments; - } - } - detachedComments.push(comment); - lastComment = comment; - }); - if (detachedComments.length) { - // All comments look like they could have been part of the copyright header. Make - // sure there is at least one blank line between it and the node. If not, it's not - // a copyright header. - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end); - var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); - if (nodeLine >= lastCommentLine + 2) { - // Valid detachedComments - ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); - ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: lastOrUndefined(detachedComments).end }; - if (detachedCommentsInfo) { - detachedCommentsInfo.push(currentDetachedCommentInfo); - } - else { - detachedCommentsInfo = [currentDetachedCommentInfo]; - } - } - } - } - } - function isPinnedOrTripleSlashComment(comment) { - if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 42 /* asterisk */) { - return currentSourceFile.text.charCodeAt(comment.pos + 2) === 33 /* exclamation */; - } - else if (currentSourceFile.text.charCodeAt(comment.pos + 1) === 47 /* slash */ && - comment.pos + 2 < comment.end && - currentSourceFile.text.charCodeAt(comment.pos + 2) === 47 /* slash */ && - currentSourceFile.text.substring(comment.pos, comment.end).match(ts.fullTripleSlashReferencePathRegEx)) { - return true; - } - } - } - function emitFile(jsFilePath, sourceFile) { - emitJavaScript(jsFilePath, sourceFile); - if (compilerOptions.declaration) { - ts.writeDeclarationFile(jsFilePath, sourceFile, host, resolver, diagnostics); - } - } - } - ts.emitFiles = emitFiles; -})(ts || (ts = {})); From a25534bd8d26c1461837c6e379dcc74991c5f5aa Mon Sep 17 00:00:00 2001 From: Jason Freeman Date: Tue, 5 May 2015 11:36:21 -0700 Subject: [PATCH 19/31] Remove unnecessary LineEndingSensitive option from BaselineOptions --- src/harness/harness.ts | 8 -------- 1 file changed, 8 deletions(-) diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 7d04c042fdb..ee4e37c19f4 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -1610,7 +1610,6 @@ module Harness { export module Baseline { export interface BaselineOptions { - LineEndingSensitive?: boolean; Subfolder?: string; Baselinefolder?: string; } @@ -1702,13 +1701,6 @@ module Harness { expected = IO.readFile(refFileName); } - var lineEndingInsensitive = opts && opts.LineEndingSensitive === false; // default is true - - if (lineEndingInsensitive) { - expected = expected.replace(/\r\n?/g, '\n'); - actual = actual.replace(/\r\n?/g, '\n'); - } - return { expected, actual }; } From e62db556f61d9f2bf116a8d70e441db40266e7d2 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 5 May 2015 11:47:10 -0700 Subject: [PATCH 20/31] Update LKG --- bin/lib.d.ts | 1 + bin/lib.dom.d.ts | 1 + bin/lib.es6.d.ts | 1 + bin/tsc.js | 62 +++++---- bin/tsserver.js | 251 +++++++++++++++++++++++------------- bin/typescript.d.ts | 34 +++++ bin/typescript.js | 248 +++++++++++++++++++++-------------- bin/typescriptServices.d.ts | 34 +++++ bin/typescriptServices.js | 248 +++++++++++++++++++++-------------- 9 files changed, 578 insertions(+), 302 deletions(-) diff --git a/bin/lib.d.ts b/bin/lib.d.ts index 944b10ac881..e583f1ac783 100644 --- a/bin/lib.d.ts +++ b/bin/lib.d.ts @@ -15838,6 +15838,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { overrideMimeType(mime: string): void; send(data?: Document): void; send(data?: string): void; + send(data?: any): void; setRequestHeader(header: string, value: string): void; DONE: number; HEADERS_RECEIVED: number; diff --git a/bin/lib.dom.d.ts b/bin/lib.dom.d.ts index 422b4b8803c..142486a1662 100644 --- a/bin/lib.dom.d.ts +++ b/bin/lib.dom.d.ts @@ -14668,6 +14668,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { overrideMimeType(mime: string): void; send(data?: Document): void; send(data?: string): void; + send(data?: any): void; setRequestHeader(header: string, value: string): void; DONE: number; HEADERS_RECEIVED: number; diff --git a/bin/lib.es6.d.ts b/bin/lib.es6.d.ts index 8266e4264c1..f839a3e3a0b 100644 --- a/bin/lib.es6.d.ts +++ b/bin/lib.es6.d.ts @@ -17217,6 +17217,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { overrideMimeType(mime: string): void; send(data?: Document): void; send(data?: string): void; + send(data?: any): void; setRequestHeader(header: string, value: string): void; DONE: number; HEADERS_RECEIVED: number; diff --git a/bin/tsc.js b/bin/tsc.js index 653540b7b99..4912544383a 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -444,7 +444,7 @@ var ts; for (var _i = 0; _i < parts.length; _i++) { var part = parts[_i]; if (part !== ".") { - if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { + if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); } else { @@ -536,7 +536,7 @@ var ts; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { + if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { directoryComponents.length--; } for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { @@ -1416,6 +1416,9 @@ var ts; Preserve_new_lines_when_emitting_code: { code: 6057, category: ts.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: ts.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: ts.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: ts.DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, + NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE" }, + Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -1844,7 +1847,7 @@ var ts; } collecting = true; if (result && result.length) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } continue; case 9: @@ -1890,7 +1893,7 @@ var ts; default: if (ch > 127 && (isWhiteSpace(ch) || isLineBreak(ch))) { if (result && result.length && isLineBreak(ch)) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } pos++; continue; @@ -3908,7 +3911,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function hasRestParameters(s) { - return s.parameters.length > 0 && s.parameters[s.parameters.length - 1].dotDotDotToken !== undefined; + return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; } ts.hasRestParameters = hasRestParameters; function isLiteralKind(kind) { @@ -4336,7 +4339,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; + linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); } } } @@ -4405,8 +4408,8 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function shouldEmitToOwnFile(sourceFile, compilerOptions) { if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.fileName, ".js")) { - return true; + if ((isExternalModule(sourceFile) || !compilerOptions.out)) { + return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -5981,7 +5984,7 @@ var ts; templateSpans.pos = getNodePos(); do { templateSpans.push(parseTemplateSpan()); - } while (templateSpans[templateSpans.length - 1].literal.kind === 12); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 12); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); @@ -11125,7 +11128,7 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); if (type.flags & 4096 && type.target === globalArrayType) { return type.typeArguments[0]; } @@ -13219,7 +13222,7 @@ var ts; } if (indexOfParameter === (func.parameters.length - 1) && funcHasRestParameters && contextualSignature.hasRestParameter && func.parameters.length >= contextualSignature.parameters.length) { - return getTypeOfSymbol(contextualSignature.parameters[contextualSignature.parameters.length - 1]); + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } } @@ -14279,9 +14282,9 @@ var ts; links.type = instantiateType(getTypeAtPosition(context, i), mapper); } if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) { - var parameter = signature.parameters[signature.parameters.length - 1]; + var parameter = ts.lastOrUndefined(signature.parameters); var links = getSymbolLinks(parameter); - links.type = instantiateType(getTypeOfSymbol(context.parameters[context.parameters.length - 1]), mapper); + links.type = instantiateType(getTypeOfSymbol(ts.lastOrUndefined(context.parameters)), mapper); } } function getReturnTypeFromBody(func, contextualMapper) { @@ -18660,7 +18663,7 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== elements[elements.length - 1]) { + if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } if (node.name.kind === 152 || node.name.kind === 151) { @@ -20446,7 +20449,7 @@ var ts; var sourceMapNameIndexMap = {}; var sourceMapNameIndices = []; function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; + return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; } var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan = { @@ -22922,11 +22925,11 @@ var ts; emitNodeWithoutSourceMap(memberName); } } - function getInitializedProperties(node, static) { + function getInitializedProperties(node, isStatic) { var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 && static === ((member.flags & 128) !== 0) && member.initializer) { + if (member.kind === 133 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { properties.push(member); } } @@ -24834,10 +24837,10 @@ var ts; } } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -24918,12 +24921,12 @@ var ts; lastComment = comment; }); if (detachedComments.length) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); + var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); if (nodeLine >= lastCommentLine + 2) { ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; + var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); } @@ -24964,6 +24967,8 @@ var ts; ts.ioReadTime = 0; ts.ioWriteTime = 0; ts.version = "1.5.0"; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -25034,6 +25039,9 @@ var ts; } } } + var newLine = options.newLine === 0 ? carriageReturnLineFeed : + options.newLine === 1 ? lineFeed : + ts.sys.newLine; return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -25041,7 +25049,7 @@ var ts; getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return ts.sys.newLine; } + getNewLine: function () { return newLine; } }; } ts.createCompilerHost = createCompilerHost; @@ -25526,6 +25534,16 @@ var ts; paramType: ts.Diagnostics.KIND, error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_or_umd }, + { + name: "newLine", + type: { + "crlf": 0, + "lf": 1 + }, + description: ts.Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + paramType: ts.Diagnostics.NEWLINE, + error: ts.Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF + }, { name: "noEmit", type: "boolean", diff --git a/bin/tsserver.js b/bin/tsserver.js index f49850e8aca..e492912a282 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -444,7 +444,7 @@ var ts; for (var _i = 0; _i < parts.length; _i++) { var part = parts[_i]; if (part !== ".") { - if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { + if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); } else { @@ -536,7 +536,7 @@ var ts; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { + if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { directoryComponents.length--; } for (var joinStartIndex = 0; joinStartIndex < pathComponents.length && joinStartIndex < directoryComponents.length; joinStartIndex++) { @@ -1416,6 +1416,9 @@ var ts; Preserve_new_lines_when_emitting_code: { code: 6057, category: ts.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: ts.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: ts.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: ts.DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, + NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE" }, + Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -1844,7 +1847,7 @@ var ts; } collecting = true; if (result && result.length) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } continue; case 9: @@ -1890,7 +1893,7 @@ var ts; default: if (ch > 127 && (isWhiteSpace(ch) || isLineBreak(ch))) { if (result && result.length && isLineBreak(ch)) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } pos++; continue; @@ -2770,6 +2773,16 @@ var ts; paramType: ts.Diagnostics.KIND, error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_or_umd }, + { + name: "newLine", + type: { + "crlf": 0, + "lf": 1 + }, + description: ts.Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + paramType: ts.Diagnostics.NEWLINE, + error: ts.Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF + }, { name: "noEmit", type: "boolean", @@ -3769,7 +3782,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function hasRestParameters(s) { - return s.parameters.length > 0 && s.parameters[s.parameters.length - 1].dotDotDotToken !== undefined; + return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; } ts.hasRestParameters = hasRestParameters; function isLiteralKind(kind) { @@ -4197,7 +4210,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; + linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); } } } @@ -4266,8 +4279,8 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function shouldEmitToOwnFile(sourceFile, compilerOptions) { if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.fileName, ".js")) { - return true; + if ((isExternalModule(sourceFile) || !compilerOptions.out)) { + return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -5842,7 +5855,7 @@ var ts; templateSpans.pos = getNodePos(); do { templateSpans.push(parseTemplateSpan()); - } while (templateSpans[templateSpans.length - 1].literal.kind === 12); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 12); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); @@ -11499,7 +11512,7 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); if (type.flags & 4096 && type.target === globalArrayType) { return type.typeArguments[0]; } @@ -13593,7 +13606,7 @@ var ts; } if (indexOfParameter === (func.parameters.length - 1) && funcHasRestParameters && contextualSignature.hasRestParameter && func.parameters.length >= contextualSignature.parameters.length) { - return getTypeOfSymbol(contextualSignature.parameters[contextualSignature.parameters.length - 1]); + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } } @@ -14653,9 +14666,9 @@ var ts; links.type = instantiateType(getTypeAtPosition(context, i), mapper); } if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) { - var parameter = signature.parameters[signature.parameters.length - 1]; + var parameter = ts.lastOrUndefined(signature.parameters); var links = getSymbolLinks(parameter); - links.type = instantiateType(getTypeOfSymbol(context.parameters[context.parameters.length - 1]), mapper); + links.type = instantiateType(getTypeOfSymbol(ts.lastOrUndefined(context.parameters)), mapper); } } function getReturnTypeFromBody(func, contextualMapper) { @@ -19034,7 +19047,7 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== elements[elements.length - 1]) { + if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } if (node.name.kind === 152 || node.name.kind === 151) { @@ -20820,7 +20833,7 @@ var ts; var sourceMapNameIndexMap = {}; var sourceMapNameIndices = []; function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; + return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; } var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan = { @@ -23296,11 +23309,11 @@ var ts; emitNodeWithoutSourceMap(memberName); } } - function getInitializedProperties(node, static) { + function getInitializedProperties(node, isStatic) { var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 && static === ((member.flags & 128) !== 0) && member.initializer) { + if (member.kind === 133 && isStatic === ((member.flags & 128) !== 0) && member.initializer) { properties.push(member); } } @@ -25208,10 +25221,10 @@ var ts; } } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } function getLeadingCommentsWithoutDetachedComments() { - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -25292,12 +25305,12 @@ var ts; lastComment = comment; }); if (detachedComments.length) { - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); + var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); if (nodeLine >= lastCommentLine + 2) { ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; + var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); } @@ -25338,6 +25351,8 @@ var ts; ts.ioReadTime = 0; ts.ioWriteTime = 0; ts.version = "1.5.0"; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -25408,6 +25423,9 @@ var ts; } } } + var newLine = options.newLine === 0 ? carriageReturnLineFeed : + options.newLine === 1 ? lineFeed : + ts.sys.newLine; return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -25415,7 +25433,7 @@ var ts; getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return ts.sys.newLine; } + getNewLine: function () { return newLine; } }; } ts.createCompilerHost = createCompilerHost; @@ -26136,13 +26154,13 @@ var ts; return textSpan(node); } case 224: - return spanInNode(node.parent.statements[node.parent.statements.length - 1]); + return spanInNode(ts.lastOrUndefined(node.parent.statements)); ; case 208: var caseBlock = node.parent; - var lastClause = caseBlock.clauses[caseBlock.clauses.length - 1]; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { - return spanInNode(lastClause.statements[lastClause.statements.length - 1]); + return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; default: @@ -27786,7 +27804,7 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last = children[children.length - 1]; + var last = ts.lastOrUndefined(children); if (last.kind === expectedLastToken) { return true; } @@ -28226,7 +28244,7 @@ var ts; if (isStarted) { if (trailingTrivia) { ts.Debug.assert(trailingTrivia.length !== 0); - wasNewLine = trailingTrivia[trailingTrivia.length - 1].kind === 4; + wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4; } else { wasNewLine = false; @@ -29468,6 +29486,8 @@ var ts; var previousRange; var previousParent; var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -29522,7 +29542,9 @@ var ts; } var delta = formatting.SmartIndenter.shouldIndentChildNode(node.kind, 0) ? options.IndentSize : 0; if (effectiveParentStartLine === startLine) { - indentation = parentDynamicIndentation.getIndentation(); + indentation = startLine === lastIndentedLine + ? indentationOnLastIndentedLine + : parentDynamicIndentation.getIndentation(); delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); } return { @@ -29732,7 +29754,6 @@ var ts; if (!ts.rangeContainsRange(originalRange, triviaItem)) { continue; } - var triviaStartLine = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos).line; switch (triviaItem.kind) { case 3: var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind); @@ -29755,6 +29776,8 @@ var ts; if (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) { var tokenIndentation = dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind); insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; } } formattingScanner.advance(); @@ -32554,22 +32577,6 @@ var ts; } return ScriptElementKind.unknown; } - function getTypeKind(type) { - var flags = type.getFlags(); - if (flags & 128) - return ScriptElementKind.enumElement; - if (flags & 1024) - return ScriptElementKind.classElement; - if (flags & 2048) - return ScriptElementKind.interfaceElement; - if (flags & 512) - return ScriptElementKind.typeParameterElement; - if (flags & 1048703) - return ScriptElementKind.primitiveType; - if (flags & 256) - return ScriptElementKind.primitiveType; - return ScriptElementKind.unknown; - } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) @@ -32933,6 +32940,59 @@ var ts; containerName: containerName }; } + function getDefinitionFromSymbol(symbol, node) { + var typeChecker = program.getTypeChecker(); + var result = []; + var declarations = symbol.getDeclarations(); + var symbolName = typeChecker.symbolToString(symbol); + var symbolKind = getSymbolKind(symbol, node); + var containerSymbol = symbol.parent; + var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (isNewExpressionTarget(location) || location.kind === 114) { + if (symbol.flags & 32) { + var classDeclaration = symbol.getDeclarations()[0]; + ts.Debug.assert(classDeclaration && classDeclaration.kind === 202); + return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 136) || + (!selectConstructors && (d.kind === 201 || d.kind === 135 || d.kind === 134))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); @@ -32982,56 +33042,37 @@ var ts; var shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName); }); } - var result = []; - var declarations = symbol.getDeclarations(); - var symbolName = typeChecker.symbolToString(symbol); - var symbolKind = getSymbolKind(symbol, node); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); + return getDefinitionFromSymbol(symbol, node); + } + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isNewExpressionTarget(location) || location.kind === 114) { - if (symbol.flags & 32) { - var classDeclaration = symbol.getDeclarations()[0]; - ts.Debug.assert(classDeclaration && classDeclaration.kind === 202); - return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); - } - } - return false; + var typeChecker = program.getTypeChecker(); + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); - } - return false; + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { - var declarations = []; - var definition; - ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 136) || - (!selectConstructors && (d.kind === 201 || d.kind === 135 || d.kind === 134))) { - declarations.push(d); - if (d.body) - definition = d; + if (type.flags & 16384) { + var result = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + result.push.apply(result, getDefinitionFromSymbol(t.symbol, node)); } }); - if (definition) { - result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); - return true; - } - else if (declarations.length) { - result.push(createDefinitionInfo(declarations[declarations.length - 1], symbolKind, symbolName, containerName)); - return true; - } - return false; + return result; } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(type.symbol, node); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -34797,6 +34838,7 @@ var ts; getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, findReferences: findReferences, getOccurrencesAtPosition: getOccurrencesAtPosition, @@ -35300,6 +35342,7 @@ var ts; CommandNames.Rename = "rename"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; + CommandNames.TypeDefinition = "typeDefinition"; CommandNames.Unknown = "unknown"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); var Errors; @@ -35471,6 +35514,24 @@ var ts; end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) }); }); }; + Session.prototype.getTypeDefinition = function (line, offset, fileName) { + var file = ts.normalizePath(fileName); + var project = this.projectService.getProjectForFile(file); + if (!project) { + throw Errors.NoProject; + } + var compilerService = project.compilerService; + var position = compilerService.host.lineOffsetToPosition(file, line, offset); + var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); + if (!definitions) { + return undefined; + } + return definitions.map(function (def) { return ({ + file: def.fileName, + start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), + end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) + }); }); + }; Session.prototype.getOccurrences = function (line, offset, fileName) { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); @@ -35665,7 +35726,7 @@ var ts; IndentSize: formatOptions.IndentSize, TabSize: formatOptions.TabSize, NewLineCharacter: "\n", - ConvertTabsToSpaces: true + ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces }; var indentPosition = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); for (var i = 0, len = lineText.length; i < len; i++) { @@ -35927,6 +35988,11 @@ var ts; response = this.getDefinition(defArgs.line, defArgs.offset, defArgs.file); break; } + case CommandNames.TypeDefinition: { + var defArgs = request.arguments; + response = this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file); + break; + } case CommandNames.References: { var refArgs = request.arguments; response = this.getReferences(refArgs.line, refArgs.offset, refArgs.file); @@ -36654,6 +36720,7 @@ var ts; if (content !== undefined) { var indentSize; info = new ScriptInfo(this.host, fileName, content, openedByClient); + info.setFormatOptions(this.getFormatCodeOptions()); this.filenameToScriptInfo[fileName] = info; if (!info.isOpen) { info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); @@ -36670,7 +36737,7 @@ var ts; ProjectService.prototype.findConfigFile = function (searchPath) { while (true) { var fileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (ts.sys.fileExists(fileName)) { + if (this.host.fileExists(fileName)) { return fileName; } var parentPath = ts.getDirectoryPath(searchPath); @@ -36803,7 +36870,7 @@ var ts; var proj = this.createProject(configFilename, projectOptions); for (var i = 0, len = parsedCommandLine.fileNames.length; i < len; i++) { var rootFilename = parsedCommandLine.fileNames[i]; - if (ts.sys.fileExists(rootFilename)) { + if (this.host.fileExists(rootFilename)) { var info = this.openFile(rootFilename, clientFileName == rootFilename); proj.addRoot(info); } diff --git a/bin/typescript.d.ts b/bin/typescript.d.ts index 7cf08879eaa..3e765a33f01 100644 --- a/bin/typescript.d.ts +++ b/bin/typescript.d.ts @@ -1094,6 +1094,7 @@ declare module "typescript" { locale?: string; mapRoot?: string; module?: ModuleKind; + newLine?: NewLineKind; noEmit?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; @@ -1124,6 +1125,10 @@ declare module "typescript" { UMD = 3, System = 4, } + const enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } interface LineAndCharacter { line: number; character: number; @@ -1186,6 +1191,32 @@ declare module "typescript" { var sys: System; } declare module "typescript" { + interface ErrorCallback { + (message: DiagnosticMessage, length: number): void; + } + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scan(): SyntaxKind; + setText(text: string, start?: number, length?: number): void; + setOnError(onError: ErrorCallback): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + tryScan(callback: () => T): T; + } function tokenToString(t: SyntaxKind): string; function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; @@ -1195,6 +1226,8 @@ declare module "typescript" { function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; + /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare module "typescript" { function getDefaultLibFileName(options: CompilerOptions): string; @@ -1381,6 +1414,7 @@ declare module "typescript" { getRenameInfo(fileName: string, position: number): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; diff --git a/bin/typescript.js b/bin/typescript.js index 588078a9d94..ad70519a3fa 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -547,6 +547,11 @@ var ts; ModuleKind[ModuleKind["System"] = 4] = "System"; })(ts.ModuleKind || (ts.ModuleKind = {})); var ModuleKind = ts.ModuleKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(ts.NewLineKind || (ts.NewLineKind = {})); + var NewLineKind = ts.NewLineKind; (function (ScriptTarget) { ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; @@ -1137,7 +1142,7 @@ var ts; for (var _i = 0; _i < parts.length; _i++) { var part = parts[_i]; if (part !== ".") { - if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { + if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); } else { @@ -1244,7 +1249,7 @@ var ts; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { + if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.length--; @@ -2154,6 +2159,9 @@ var ts; Preserve_new_lines_when_emitting_code: { code: 6057, category: ts.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: ts.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: ts.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: ts.DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, + NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE" }, + Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -2652,7 +2660,7 @@ var ts; } collecting = true; if (result && result.length) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } continue; case 9 /* tab */: @@ -2698,7 +2706,7 @@ var ts; default: if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch) || isLineBreak(ch))) { if (result && result.length && isLineBreak(ch)) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } pos++; continue; @@ -2728,8 +2736,7 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; - // Creates a scanner over a (possibly unspecified) range of a piece of text. - /* @internal */ + /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ function createScanner(languageVersion, skipTrivia, text, onError, start, length) { var pos; // Current position (end position of text of current token) var end; // end of text @@ -4924,7 +4931,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function hasRestParameters(s) { - return s.parameters.length > 0 && s.parameters[s.parameters.length - 1].dotDotDotToken !== undefined; + return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; } ts.hasRestParameters = hasRestParameters; function isLiteralKind(kind) { @@ -5388,7 +5395,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; + linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); } } } @@ -5457,8 +5464,10 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function shouldEmitToOwnFile(sourceFile, compilerOptions) { if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.fileName, ".js")) { - return true; + if ((isExternalModule(sourceFile) || !compilerOptions.out)) { + // 1. in-browser single file compilation scenario + // 2. non .js file + return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -7465,7 +7474,7 @@ var ts; templateSpans.pos = getNodePos(); do { templateSpans.push(parseTemplateSpan()); - } while (templateSpans[templateSpans.length - 1].literal.kind === 12 /* TemplateMiddle */); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 12 /* TemplateMiddle */); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); @@ -13656,7 +13665,7 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } @@ -15965,7 +15974,7 @@ var ts; // If last parameter is contextually rest parameter get its type if (indexOfParameter === (func.parameters.length - 1) && funcHasRestParameters && contextualSignature.hasRestParameter && func.parameters.length >= contextualSignature.parameters.length) { - return getTypeOfSymbol(contextualSignature.parameters[contextualSignature.parameters.length - 1]); + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } } @@ -17366,9 +17375,9 @@ var ts; links.type = instantiateType(getTypeAtPosition(context, i), mapper); } if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) { - var parameter = signature.parameters[signature.parameters.length - 1]; + var parameter = ts.lastOrUndefined(signature.parameters); var links = getSymbolLinks(parameter); - links.type = instantiateType(getTypeOfSymbol(context.parameters[context.parameters.length - 1]), mapper); + links.type = instantiateType(getTypeOfSymbol(ts.lastOrUndefined(context.parameters)), mapper); } } function getReturnTypeFromBody(func, contextualMapper) { @@ -22381,7 +22390,7 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== elements[elements.length - 1]) { + if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } if (node.name.kind === 152 /* ArrayBindingPattern */ || node.name.kind === 151 /* ObjectBindingPattern */) { @@ -24373,7 +24382,7 @@ var ts; var sourceMapNameIndexMap = {}; var sourceMapNameIndices = []; function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; + return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; } // Last recorded and encoded spans var lastRecordedSourceMapSpan; @@ -27145,11 +27154,11 @@ var ts; emitNodeWithoutSourceMap(memberName); } } - function getInitializedProperties(node, static) { + function getInitializedProperties(node, isStatic) { var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 /* PropertyDeclaration */ && static === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { + if (member.kind === 133 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { properties.push(member); } } @@ -29368,11 +29377,11 @@ var ts; } } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -29473,13 +29482,13 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); + var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; + var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); } @@ -29521,6 +29530,8 @@ var ts; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ ts.version = "1.5.0"; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -29594,6 +29605,9 @@ var ts; } } } + var newLine = options.newLine === 0 /* CarriageReturnLineFeed */ ? carriageReturnLineFeed : + options.newLine === 1 /* LineFeed */ ? lineFeed : + ts.sys.newLine; return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -29601,7 +29615,7 @@ var ts; getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return ts.sys.newLine; } + getNewLine: function () { return newLine; } }; } ts.createCompilerHost = createCompilerHost; @@ -30119,6 +30133,16 @@ var ts; paramType: ts.Diagnostics.KIND, error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_or_umd }, + { + name: "newLine", + type: { + "crlf": 0 /* CarriageReturnLineFeed */, + "lf": 1 /* LineFeed */ + }, + description: ts.Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + paramType: ts.Diagnostics.NEWLINE, + error: ts.Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF + }, { name: "noEmit", type: "boolean", @@ -32529,7 +32553,7 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last = children[children.length - 1]; + var last = ts.lastOrUndefined(children); if (last.kind === expectedLastToken) { return true; } @@ -33023,7 +33047,7 @@ var ts; if (isStarted) { if (trailingTrivia) { ts.Debug.assert(trailingTrivia.length !== 0); - wasNewLine = trailingTrivia[trailingTrivia.length - 1].kind === 4 /* NewLineTrivia */; + wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; } else { wasNewLine = false; @@ -34482,6 +34506,8 @@ var ts; var previousRange; var previousParent; var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -34551,7 +34577,9 @@ var ts; // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = parentDynamicIndentation.getIndentation(); + indentation = startLine === lastIndentedLine + ? indentationOnLastIndentedLine + : parentDynamicIndentation.getIndentation(); delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); } return { @@ -34799,7 +34827,6 @@ var ts; if (!ts.rangeContainsRange(originalRange, triviaItem)) { continue; } - var triviaStartLine = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos).line; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind); @@ -34823,6 +34850,8 @@ var ts; if (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) { var tokenIndentation = dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind); insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; } } formattingScanner.advance(); @@ -38055,22 +38084,6 @@ var ts; } return ScriptElementKind.unknown; } - function getTypeKind(type) { - var flags = type.getFlags(); - if (flags & 128 /* Enum */) - return ScriptElementKind.enumElement; - if (flags & 1024 /* Class */) - return ScriptElementKind.classElement; - if (flags & 2048 /* Interface */) - return ScriptElementKind.interfaceElement; - if (flags & 512 /* TypeParameter */) - return ScriptElementKind.typeParameterElement; - if (flags & 1048703 /* Intrinsic */) - return ScriptElementKind.primitiveType; - if (flags & 256 /* StringLiteral */) - return ScriptElementKind.primitiveType; - return ScriptElementKind.unknown; - } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) @@ -38453,6 +38466,62 @@ var ts; containerName: containerName }; } + function getDefinitionFromSymbol(symbol, node) { + var typeChecker = program.getTypeChecker(); + var result = []; + var declarations = symbol.getDeclarations(); + var symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = getSymbolKind(symbol, node); + var containerSymbol = symbol.parent; + var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + // Just add all the declarations. + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (isNewExpressionTarget(location) || location.kind === 114 /* ConstructorKeyword */) { + if (symbol.flags & 32 /* Class */) { + var classDeclaration = symbol.getDeclarations()[0]; + ts.Debug.assert(classDeclaration && classDeclaration.kind === 202 /* ClassDeclaration */); + return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 136 /* Constructor */) || + (!selectConstructors && (d.kind === 201 /* FunctionDeclaration */ || d.kind === 135 /* MethodDeclaration */ || d.kind === 134 /* MethodSignature */))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); @@ -38516,59 +38585,38 @@ var ts; var shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName); }); } - var result = []; - var declarations = symbol.getDeclarations(); - var symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol - var symbolKind = getSymbolKind(symbol, node); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); + return getDefinitionFromSymbol(symbol, node); + } + /// Goto type + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - // Applicable only if we are in a new expression, or we are on a constructor declaration - // and in either case the symbol has a construct signature definition, i.e. class - if (isNewExpressionTarget(location) || location.kind === 114 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - var classDeclaration = symbol.getDeclarations()[0]; - ts.Debug.assert(classDeclaration && classDeclaration.kind === 202 /* ClassDeclaration */); - return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); - } - } - return false; + var typeChecker = program.getTypeChecker(); + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); - } - return false; + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { - var declarations = []; - var definition; - ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 136 /* Constructor */) || - (!selectConstructors && (d.kind === 201 /* FunctionDeclaration */ || d.kind === 135 /* MethodDeclaration */ || d.kind === 134 /* MethodSignature */))) { - declarations.push(d); - if (d.body) - definition = d; + if (type.flags & 16384 /* Union */) { + var result = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + result.push.apply(result, getDefinitionFromSymbol(t.symbol, node)); } }); - if (definition) { - result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); - return true; - } - else if (declarations.length) { - result.push(createDefinitionInfo(declarations[declarations.length - 1], symbolKind, symbolName, containerName)); - return true; - } - return false; + return result; } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(type.symbol, node); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -40613,6 +40661,7 @@ var ts; getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, findReferences: findReferences, getOccurrencesAtPosition: getOccurrencesAtPosition, @@ -41498,14 +41547,14 @@ var ts; } // fall through. case 224 /* CatchClause */: - return spanInNode(node.parent.statements[node.parent.statements.length - 1]); + return spanInNode(ts.lastOrUndefined(node.parent.statements)); ; case 208 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; - var lastClause = caseBlock.clauses[caseBlock.clauses.length - 1]; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { - return spanInNode(lastClause.statements[lastClause.statements.length - 1]); + return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; // Default to parent node @@ -41909,6 +41958,17 @@ var ts; return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { + return _this.languageService.getTypeDefinitionAtPosition(fileName, position); + }); + }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { diff --git a/bin/typescriptServices.d.ts b/bin/typescriptServices.d.ts index 92427e18f24..3114c56b789 100644 --- a/bin/typescriptServices.d.ts +++ b/bin/typescriptServices.d.ts @@ -1094,6 +1094,7 @@ declare module ts { locale?: string; mapRoot?: string; module?: ModuleKind; + newLine?: NewLineKind; noEmit?: boolean; noEmitHelpers?: boolean; noEmitOnError?: boolean; @@ -1124,6 +1125,10 @@ declare module ts { UMD = 3, System = 4, } + const enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } interface LineAndCharacter { line: number; character: number; @@ -1186,6 +1191,32 @@ declare module ts { var sys: System; } declare module ts { + interface ErrorCallback { + (message: DiagnosticMessage, length: number): void; + } + interface Scanner { + getStartPos(): number; + getToken(): SyntaxKind; + getTextPos(): number; + getTokenPos(): number; + getTokenText(): string; + getTokenValue(): string; + hasExtendedUnicodeEscape(): boolean; + hasPrecedingLineBreak(): boolean; + isIdentifier(): boolean; + isReservedWord(): boolean; + isUnterminated(): boolean; + reScanGreaterToken(): SyntaxKind; + reScanSlashToken(): SyntaxKind; + reScanTemplateToken(): SyntaxKind; + scan(): SyntaxKind; + setText(text: string, start?: number, length?: number): void; + setOnError(onError: ErrorCallback): void; + setScriptTarget(scriptTarget: ScriptTarget): void; + setTextPos(textPos: number): void; + lookAhead(callback: () => T): T; + tryScan(callback: () => T): T; + } function tokenToString(t: SyntaxKind): string; function getPositionOfLineAndCharacter(sourceFile: SourceFile, line: number, character: number): number; function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter; @@ -1195,6 +1226,8 @@ declare module ts { function getTrailingCommentRanges(text: string, pos: number): CommentRange[]; function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean; function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean; + /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ + function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare module ts { function getDefaultLibFileName(options: CompilerOptions): string; @@ -1381,6 +1414,7 @@ declare module ts { getRenameInfo(fileName: string, position: number): RenameInfo; findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[]; getDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; + getTypeDefinitionAtPosition(fileName: string, position: number): DefinitionInfo[]; getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[]; findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 588078a9d94..ad70519a3fa 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -547,6 +547,11 @@ var ts; ModuleKind[ModuleKind["System"] = 4] = "System"; })(ts.ModuleKind || (ts.ModuleKind = {})); var ModuleKind = ts.ModuleKind; + (function (NewLineKind) { + NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed"; + NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed"; + })(ts.NewLineKind || (ts.NewLineKind = {})); + var NewLineKind = ts.NewLineKind; (function (ScriptTarget) { ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3"; ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5"; @@ -1137,7 +1142,7 @@ var ts; for (var _i = 0; _i < parts.length; _i++) { var part = parts[_i]; if (part !== ".") { - if (part === ".." && normalized.length > 0 && normalized[normalized.length - 1] !== "..") { + if (part === ".." && normalized.length > 0 && lastOrUndefined(normalized) !== "..") { normalized.pop(); } else { @@ -1244,7 +1249,7 @@ var ts; function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { var pathComponents = getNormalizedPathOrUrlComponents(relativeOrAbsolutePath, currentDirectory); var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); - if (directoryComponents.length > 1 && directoryComponents[directoryComponents.length - 1] === "") { + if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.length--; @@ -2154,6 +2159,9 @@ var ts; Preserve_new_lines_when_emitting_code: { code: 6057, category: ts.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: ts.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: ts.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: ts.DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." }, + NEWLINE: { code: 6061, category: ts.DiagnosticCategory.Message, key: "NEWLINE" }, + Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: ts.DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member '{0}' implicitly has an '{1}' type." }, @@ -2652,7 +2660,7 @@ var ts; } collecting = true; if (result && result.length) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } continue; case 9 /* tab */: @@ -2698,7 +2706,7 @@ var ts; default: if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpace(ch) || isLineBreak(ch))) { if (result && result.length && isLineBreak(ch)) { - result[result.length - 1].hasTrailingNewLine = true; + ts.lastOrUndefined(result).hasTrailingNewLine = true; } pos++; continue; @@ -2728,8 +2736,7 @@ var ts; ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion); } ts.isIdentifierPart = isIdentifierPart; - // Creates a scanner over a (possibly unspecified) range of a piece of text. - /* @internal */ + /** Creates a scanner over a (possibly unspecified) range of a piece of text. */ function createScanner(languageVersion, skipTrivia, text, onError, start, length) { var pos; // Current position (end position of text of current token) var end; // end of text @@ -4924,7 +4931,7 @@ var ts; } ts.hasQuestionToken = hasQuestionToken; function hasRestParameters(s) { - return s.parameters.length > 0 && s.parameters[s.parameters.length - 1].dotDotDotToken !== undefined; + return s.parameters.length > 0 && ts.lastOrUndefined(s.parameters).dotDotDotToken !== undefined; } ts.hasRestParameters = hasRestParameters; function isLiteralKind(kind) { @@ -5388,7 +5395,7 @@ var ts; var lineStartsOfS = ts.computeLineStarts(s); if (lineStartsOfS.length > 1) { lineCount = lineCount + lineStartsOfS.length - 1; - linePos = output.length - s.length + lineStartsOfS[lineStartsOfS.length - 1]; + linePos = output.length - s.length + ts.lastOrUndefined(lineStartsOfS); } } } @@ -5457,8 +5464,10 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function shouldEmitToOwnFile(sourceFile, compilerOptions) { if (!isDeclarationFile(sourceFile)) { - if ((isExternalModule(sourceFile) || !compilerOptions.out) && !ts.fileExtensionIs(sourceFile.fileName, ".js")) { - return true; + if ((isExternalModule(sourceFile) || !compilerOptions.out)) { + // 1. in-browser single file compilation scenario + // 2. non .js file + return compilerOptions.separateCompilation || !ts.fileExtensionIs(sourceFile.fileName, ".js"); } return false; } @@ -7465,7 +7474,7 @@ var ts; templateSpans.pos = getNodePos(); do { templateSpans.push(parseTemplateSpan()); - } while (templateSpans[templateSpans.length - 1].literal.kind === 12 /* TemplateMiddle */); + } while (ts.lastOrUndefined(templateSpans).literal.kind === 12 /* TemplateMiddle */); templateSpans.end = getNodeEnd(); template.templateSpans = templateSpans; return finishNode(template); @@ -13656,7 +13665,7 @@ var ts; } function getRestTypeOfSignature(signature) { if (signature.hasRestParameter) { - var type = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); + var type = getTypeOfSymbol(ts.lastOrUndefined(signature.parameters)); if (type.flags & 4096 /* Reference */ && type.target === globalArrayType) { return type.typeArguments[0]; } @@ -15965,7 +15974,7 @@ var ts; // If last parameter is contextually rest parameter get its type if (indexOfParameter === (func.parameters.length - 1) && funcHasRestParameters && contextualSignature.hasRestParameter && func.parameters.length >= contextualSignature.parameters.length) { - return getTypeOfSymbol(contextualSignature.parameters[contextualSignature.parameters.length - 1]); + return getTypeOfSymbol(ts.lastOrUndefined(contextualSignature.parameters)); } } } @@ -17366,9 +17375,9 @@ var ts; links.type = instantiateType(getTypeAtPosition(context, i), mapper); } if (signature.hasRestParameter && context.hasRestParameter && signature.parameters.length >= context.parameters.length) { - var parameter = signature.parameters[signature.parameters.length - 1]; + var parameter = ts.lastOrUndefined(signature.parameters); var links = getSymbolLinks(parameter); - links.type = instantiateType(getTypeOfSymbol(context.parameters[context.parameters.length - 1]), mapper); + links.type = instantiateType(getTypeOfSymbol(ts.lastOrUndefined(context.parameters)), mapper); } } function getReturnTypeFromBody(func, contextualMapper) { @@ -22381,7 +22390,7 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== elements[elements.length - 1]) { + if (node !== ts.lastOrUndefined(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_an_array_destructuring_pattern); } if (node.name.kind === 152 /* ArrayBindingPattern */ || node.name.kind === 151 /* ObjectBindingPattern */) { @@ -24373,7 +24382,7 @@ var ts; var sourceMapNameIndexMap = {}; var sourceMapNameIndices = []; function getSourceMapNameIndex() { - return sourceMapNameIndices.length ? sourceMapNameIndices[sourceMapNameIndices.length - 1] : -1; + return sourceMapNameIndices.length ? ts.lastOrUndefined(sourceMapNameIndices) : -1; } // Last recorded and encoded spans var lastRecordedSourceMapSpan; @@ -27145,11 +27154,11 @@ var ts; emitNodeWithoutSourceMap(memberName); } } - function getInitializedProperties(node, static) { + function getInitializedProperties(node, isStatic) { var properties = []; for (var _a = 0, _b = node.members; _a < _b.length; _a++) { var member = _b[_a]; - if (member.kind === 133 /* PropertyDeclaration */ && static === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { + if (member.kind === 133 /* PropertyDeclaration */ && isStatic === ((member.flags & 128 /* Static */) !== 0) && member.initializer) { properties.push(member); } } @@ -29368,11 +29377,11 @@ var ts; } } function hasDetachedComments(pos) { - return detachedCommentsInfo !== undefined && detachedCommentsInfo[detachedCommentsInfo.length - 1].nodePos === pos; + return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } function getLeadingCommentsWithoutDetachedComments() { // get the leading comments from detachedPos - var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, detachedCommentsInfo[detachedCommentsInfo.length - 1].detachedCommentEndPos); + var leadingComments = ts.getLeadingCommentRanges(currentSourceFile.text, ts.lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos); if (detachedCommentsInfo.length - 1) { detachedCommentsInfo.pop(); } @@ -29473,13 +29482,13 @@ var ts; // All comments look like they could have been part of the copyright header. Make // sure there is at least one blank line between it and the node. If not, it's not // a copyright header. - var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, detachedComments[detachedComments.length - 1].end); + var lastCommentLine = ts.getLineOfLocalPosition(currentSourceFile, ts.lastOrUndefined(detachedComments).end); var nodeLine = ts.getLineOfLocalPosition(currentSourceFile, ts.skipTrivia(currentSourceFile.text, node.pos)); if (nodeLine >= lastCommentLine + 2) { // Valid detachedComments ts.emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments); ts.emitComments(currentSourceFile, writer, detachedComments, true, newLine, writeComment); - var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: detachedComments[detachedComments.length - 1].end }; + var currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.lastOrUndefined(detachedComments).end }; if (detachedCommentsInfo) { detachedCommentsInfo.push(currentDetachedCommentInfo); } @@ -29521,6 +29530,8 @@ var ts; /* @internal */ ts.ioWriteTime = 0; /** The version of the TypeScript compiler release */ ts.version = "1.5.0"; + var carriageReturnLineFeed = "\r\n"; + var lineFeed = "\n"; function findConfigFile(searchPath) { var fileName = "tsconfig.json"; while (true) { @@ -29594,6 +29605,9 @@ var ts; } } } + var newLine = options.newLine === 0 /* CarriageReturnLineFeed */ ? carriageReturnLineFeed : + options.newLine === 1 /* LineFeed */ ? lineFeed : + ts.sys.newLine; return { getSourceFile: getSourceFile, getDefaultLibFileName: function (options) { return ts.combinePaths(ts.getDirectoryPath(ts.normalizePath(ts.sys.getExecutingFilePath())), ts.getDefaultLibFileName(options)); }, @@ -29601,7 +29615,7 @@ var ts; getCurrentDirectory: function () { return currentDirectory || (currentDirectory = ts.sys.getCurrentDirectory()); }, useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, - getNewLine: function () { return ts.sys.newLine; } + getNewLine: function () { return newLine; } }; } ts.createCompilerHost = createCompilerHost; @@ -30119,6 +30133,16 @@ var ts; paramType: ts.Diagnostics.KIND, error: ts.Diagnostics.Argument_for_module_option_must_be_commonjs_amd_system_or_umd }, + { + name: "newLine", + type: { + "crlf": 0 /* CarriageReturnLineFeed */, + "lf": 1 /* LineFeed */ + }, + description: ts.Diagnostics.Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix, + paramType: ts.Diagnostics.NEWLINE, + error: ts.Diagnostics.Argument_for_newLine_option_must_be_CRLF_or_LF + }, { name: "noEmit", type: "boolean", @@ -32529,7 +32553,7 @@ var ts; function nodeEndsWith(n, expectedLastToken, sourceFile) { var children = n.getChildren(sourceFile); if (children.length) { - var last = children[children.length - 1]; + var last = ts.lastOrUndefined(children); if (last.kind === expectedLastToken) { return true; } @@ -33023,7 +33047,7 @@ var ts; if (isStarted) { if (trailingTrivia) { ts.Debug.assert(trailingTrivia.length !== 0); - wasNewLine = trailingTrivia[trailingTrivia.length - 1].kind === 4 /* NewLineTrivia */; + wasNewLine = ts.lastOrUndefined(trailingTrivia).kind === 4 /* NewLineTrivia */; } else { wasNewLine = false; @@ -34482,6 +34506,8 @@ var ts; var previousRange; var previousParent; var previousRangeStartLine; + var lastIndentedLine; + var indentationOnLastIndentedLine; var edits = []; formattingScanner.advance(); if (formattingScanner.isOnToken()) { @@ -34551,7 +34577,9 @@ var ts; // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = parentDynamicIndentation.getIndentation(); + indentation = startLine === lastIndentedLine + ? indentationOnLastIndentedLine + : parentDynamicIndentation.getIndentation(); delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta() + delta); } return { @@ -34799,7 +34827,6 @@ var ts; if (!ts.rangeContainsRange(originalRange, triviaItem)) { continue; } - var triviaStartLine = sourceFile.getLineAndCharacterOfPosition(triviaItem.pos).line; switch (triviaItem.kind) { case 3 /* MultiLineCommentTrivia */: var commentIndentation = dynamicIndentation.getIndentationForComment(currentTokenInfo.token.kind); @@ -34823,6 +34850,8 @@ var ts; if (isTokenInRange && !rangeContainsError(currentTokenInfo.token)) { var tokenIndentation = dynamicIndentation.getIndentationForToken(tokenStart.line, currentTokenInfo.token.kind); insertIndentation(currentTokenInfo.token.pos, tokenIndentation, lineAdded); + lastIndentedLine = tokenStart.line; + indentationOnLastIndentedLine = tokenIndentation; } } formattingScanner.advance(); @@ -38055,22 +38084,6 @@ var ts; } return ScriptElementKind.unknown; } - function getTypeKind(type) { - var flags = type.getFlags(); - if (flags & 128 /* Enum */) - return ScriptElementKind.enumElement; - if (flags & 1024 /* Class */) - return ScriptElementKind.classElement; - if (flags & 2048 /* Interface */) - return ScriptElementKind.interfaceElement; - if (flags & 512 /* TypeParameter */) - return ScriptElementKind.typeParameterElement; - if (flags & 1048703 /* Intrinsic */) - return ScriptElementKind.primitiveType; - if (flags & 256 /* StringLiteral */) - return ScriptElementKind.primitiveType; - return ScriptElementKind.unknown; - } function getSymbolModifiers(symbol) { return symbol && symbol.declarations && symbol.declarations.length > 0 ? ts.getNodeModifiers(symbol.declarations[0]) @@ -38453,6 +38466,62 @@ var ts; containerName: containerName }; } + function getDefinitionFromSymbol(symbol, node) { + var typeChecker = program.getTypeChecker(); + var result = []; + var declarations = symbol.getDeclarations(); + var symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol + var symbolKind = getSymbolKind(symbol, node); + var containerSymbol = symbol.parent; + var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; + if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && + !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { + // Just add all the declarations. + ts.forEach(declarations, function (declaration) { + result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); + }); + } + return result; + function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + // Applicable only if we are in a new expression, or we are on a constructor declaration + // and in either case the symbol has a construct signature definition, i.e. class + if (isNewExpressionTarget(location) || location.kind === 114 /* ConstructorKeyword */) { + if (symbol.flags & 32 /* Class */) { + var classDeclaration = symbol.getDeclarations()[0]; + ts.Debug.assert(classDeclaration && classDeclaration.kind === 202 /* ClassDeclaration */); + return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); + } + } + return false; + } + function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { + if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { + return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); + } + return false; + } + function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + var declarations = []; + var definition; + ts.forEach(signatureDeclarations, function (d) { + if ((selectConstructors && d.kind === 136 /* Constructor */) || + (!selectConstructors && (d.kind === 201 /* FunctionDeclaration */ || d.kind === 135 /* MethodDeclaration */ || d.kind === 134 /* MethodSignature */))) { + declarations.push(d); + if (d.body) + definition = d; + } + }); + if (definition) { + result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); + return true; + } + else if (declarations.length) { + result.push(createDefinitionInfo(ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); + return true; + } + return false; + } + } /// Goto definition function getDefinitionAtPosition(fileName, position) { synchronizeHostData(); @@ -38516,59 +38585,38 @@ var ts; var shorthandContainerName = typeChecker.symbolToString(symbol.parent, node); return ts.map(shorthandDeclarations, function (declaration) { return createDefinitionInfo(declaration, shorthandSymbolKind, shorthandSymbolName, shorthandContainerName); }); } - var result = []; - var declarations = symbol.getDeclarations(); - var symbolName = typeChecker.symbolToString(symbol); // Do not get scoped name, just the name of the symbol - var symbolKind = getSymbolKind(symbol, node); - var containerSymbol = symbol.parent; - var containerName = containerSymbol ? typeChecker.symbolToString(containerSymbol, node) : ""; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); + return getDefinitionFromSymbol(symbol, node); + } + /// Goto type + function getTypeDefinitionAtPosition(fileName, position) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var node = ts.getTouchingPropertyName(sourceFile, position); + if (!node) { + return undefined; } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - // Applicable only if we are in a new expression, or we are on a constructor declaration - // and in either case the symbol has a construct signature definition, i.e. class - if (isNewExpressionTarget(location) || location.kind === 114 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - var classDeclaration = symbol.getDeclarations()[0]; - ts.Debug.assert(classDeclaration && classDeclaration.kind === 202 /* ClassDeclaration */); - return tryAddSignature(classDeclaration.members, true, symbolKind, symbolName, containerName, result); - } - } - return false; + var typeChecker = program.getTypeChecker(); + var symbol = typeChecker.getSymbolAtLocation(node); + if (!symbol) { + return undefined; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (isCallExpressionTarget(location) || isNewExpressionTarget(location) || isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); - } - return false; + var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + if (!type) { + return undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { - var declarations = []; - var definition; - ts.forEach(signatureDeclarations, function (d) { - if ((selectConstructors && d.kind === 136 /* Constructor */) || - (!selectConstructors && (d.kind === 201 /* FunctionDeclaration */ || d.kind === 135 /* MethodDeclaration */ || d.kind === 134 /* MethodSignature */))) { - declarations.push(d); - if (d.body) - definition = d; + if (type.flags & 16384 /* Union */) { + var result = []; + ts.forEach(type.types, function (t) { + if (t.symbol) { + result.push.apply(result, getDefinitionFromSymbol(t.symbol, node)); } }); - if (definition) { - result.push(createDefinitionInfo(definition, symbolKind, symbolName, containerName)); - return true; - } - else if (declarations.length) { - result.push(createDefinitionInfo(declarations[declarations.length - 1], symbolKind, symbolName, containerName)); - return true; - } - return false; + return result; } + if (!type.symbol) { + return undefined; + } + return getDefinitionFromSymbol(type.symbol, node); } function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); @@ -40613,6 +40661,7 @@ var ts; getSignatureHelpItems: getSignatureHelpItems, getQuickInfoAtPosition: getQuickInfoAtPosition, getDefinitionAtPosition: getDefinitionAtPosition, + getTypeDefinitionAtPosition: getTypeDefinitionAtPosition, getReferencesAtPosition: getReferencesAtPosition, findReferences: findReferences, getOccurrencesAtPosition: getOccurrencesAtPosition, @@ -41498,14 +41547,14 @@ var ts; } // fall through. case 224 /* CatchClause */: - return spanInNode(node.parent.statements[node.parent.statements.length - 1]); + return spanInNode(ts.lastOrUndefined(node.parent.statements)); ; case 208 /* CaseBlock */: // breakpoint in last statement of the last clause var caseBlock = node.parent; - var lastClause = caseBlock.clauses[caseBlock.clauses.length - 1]; + var lastClause = ts.lastOrUndefined(caseBlock.clauses); if (lastClause) { - return spanInNode(lastClause.statements[lastClause.statements.length - 1]); + return spanInNode(ts.lastOrUndefined(lastClause.statements)); } return undefined; // Default to parent node @@ -41909,6 +41958,17 @@ var ts; return _this.languageService.getDefinitionAtPosition(fileName, position); }); }; + /// GOTO Type + /** + * Computes the definition location of the type of the symbol + * at the requested position. + */ + LanguageServiceShimObject.prototype.getTypeDefinitionAtPosition = function (fileName, position) { + var _this = this; + return this.forwardJSONCall("getTypeDefinitionAtPosition('" + fileName + "', " + position + ")", function () { + return _this.languageService.getTypeDefinitionAtPosition(fileName, position); + }); + }; LanguageServiceShimObject.prototype.getRenameInfo = function (fileName, position) { var _this = this; return this.forwardJSONCall("getRenameInfo('" + fileName + "', " + position + ")", function () { From 884ca4edbc949a9a175c0e4a66567c694c4d8c43 Mon Sep 17 00:00:00 2001 From: Bryan Forbes Date: Tue, 5 May 2015 15:36:59 -0500 Subject: [PATCH 21/31] ProjectService passing incorrect object to parseConfigFile() The return signature of `readConfigFile()` changed in f8424d0b0c91a487a2c8cc226c89ffb359816b7b and the code using it in `ProjectService` was never updated to match. This lead to the language services attempting to parse an object that doesn't match what is expected and using the default compiler options instead of what is defined in `tsconfig.json`. Similarly, the return value of the closure in `getTSConfigFileInfo()` was never updated to match in both places it returns. --- src/server/editorServices.ts | 52 ++++++++++++++++++------------------ src/services/shims.ts | 26 +++++++++--------- 2 files changed, 39 insertions(+), 39 deletions(-) diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index dbf3ff3e51c..9c87a20c851 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -398,7 +398,7 @@ module ts.server { export class ProjectService { filenameToScriptInfo: ts.Map = {}; - // open, non-configured root files + // open, non-configured root files openFileRoots: ScriptInfo[] = []; // projects built from openFileRoots inferredProjects: Project[] = []; @@ -421,7 +421,7 @@ module ts.server { hostInfo: "Unknown host" } } - + getFormatCodeOptions(file?: string) { if (file) { var info = this.filenameToScriptInfo[file]; @@ -448,7 +448,7 @@ module ts.server { } } } - + log(msg: string, type = "Err") { this.psLogger.msg(msg, type); } @@ -457,17 +457,17 @@ module ts.server { if (args.file) { var info = this.filenameToScriptInfo[args.file]; if (info) { - info.setFormatOptions(args.formatOptions); + info.setFormatOptions(args.formatOptions); this.log("Host configuration update for file " + args.file, "Info"); } } else { if (args.hostInfo !== undefined) { this.hostConfiguration.hostInfo = args.hostInfo; - this.log("Host information " + args.hostInfo, "Info"); + this.log("Host information " + args.hostInfo, "Info"); } if (args.formatOptions) { - mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); + mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); this.log("Format host information updated", "Info"); } } @@ -487,7 +487,7 @@ module ts.server { fileDeletedInFilesystem(info: ScriptInfo) { this.psLogger.info(info.fileName + " deleted"); - + if (info.fileWatcher) { info.fileWatcher.close(); info.fileWatcher = undefined; @@ -537,7 +537,7 @@ module ts.server { } return false; } - + addOpenFile(info: ScriptInfo) { if (this.setConfiguredProjectRoot(info)) { this.openFileRootsConfigured.push(info); @@ -561,7 +561,7 @@ module ts.server { copyListRemovingItem(r.defaultProject, this.inferredProjects); // put r in referenced open file list this.openFilesReferenced.push(r); - // set default project of r to the new project + // set default project of r to the new project r.defaultProject = info.defaultProject; } else { @@ -694,7 +694,7 @@ module ts.server { this.openFilesReferenced = openFilesReferenced; // Then, loop through all of the open files that are project roots. - // For each root file, note the project that it roots. Then see if + // For each root file, note the project that it roots. Then see if // any other projects newly reference the file. If zero projects // newly reference the file, keep it as a root. If one or more // projects newly references the file, remove its project from the @@ -719,7 +719,7 @@ module ts.server { // Finally, if we found any open, referenced files that are no longer // referenced by their default project, treat them as newly opened - // by the editor. + // by the editor. for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { this.addOpenFile(unattachedOpenFiles[i]); } @@ -809,7 +809,7 @@ module ts.server { } else { this.log("Opened configuration file " + configFileName,"Info"); - this.configuredProjects.push(configResult.project); + this.configuredProjects.push(configResult.project); } } var info = this.openFile(fileName, true); @@ -901,22 +901,22 @@ module ts.server { } return false; } - + openConfigFile(configFilename: string, clientFileName?: string): ProjectOpenResult { configFilename = ts.normalizePath(configFilename); // file references will be relative to dirPath (or absolute) var dirPath = ts.getDirectoryPath(configFilename); - var rawConfig = ts.readConfigFile(configFilename); - if (!rawConfig) { - return { errorMsg: "tsconfig syntax error" }; + var rawConfig: { config?: ProjectOptions; error?: Diagnostic; } = ts.readConfigFile(configFilename); + if (rawConfig.error) { + return rawConfig.error; } else { - var parsedCommandLine = ts.parseConfigFile(rawConfig, ts.sys, dirPath); + var parsedCommandLine = ts.parseConfigFile(rawConfig.config, ts.sys, dirPath); if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { return { errorMsg: "tsconfig option errors" }; } else if (parsedCommandLine.fileNames) { - var projectOptions: ProjectOptions = { + var projectOptions: ProjectOptions = { files: parsedCommandLine.fileNames, compilerOptions: parsedCommandLine.options }; @@ -1040,7 +1040,7 @@ module ts.server { startPath: LineCollection[]; endBranch: LineCollection[] = []; branchNode: LineNode; - // path to current node + // path to current node stack: LineNode[]; state = CharRangeSection.Entire; lineCollectionAtBranch: LineCollection; @@ -1242,7 +1242,7 @@ module ts.server { } } - // text change information + // text change information class TextChange { constructor(public pos: number, public deleteLen: number, public insertedText?: string) { } @@ -1290,7 +1290,7 @@ module ts.server { if (cb) cb(); } - + // reload whole script, leaving no change history behind reload reload(script: string) { this.currentVersion++; @@ -1300,7 +1300,7 @@ module ts.server { snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); - // REVIEW: could use linked list + // REVIEW: could use linked list for (var i = this.minVersion; i < this.currentVersion; i++) { this.versions[i] = undefined; } @@ -1381,7 +1381,7 @@ module ts.server { return this.index.root.charCount(); } - // this requires linear space so don't hold on to these + // this requires linear space so don't hold on to these getLineStartPositions(): number[] { var starts: number[] = [-1]; var count = 1; @@ -1643,7 +1643,7 @@ module ts.server { } walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker) { - // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) + // assume (rangeStart < this.totalChars) && (rangeLength <= this.totalChars) var childIndex = 0; var child = this.children[0]; var childCharCount = child.charCount(); @@ -1729,7 +1729,7 @@ module ts.server { line: lineNumber, offset: charOffset } - } + } else if (childInfo.child.isLeaf()) { return { line: lineNumber, @@ -1917,4 +1917,4 @@ module ts.server { return 1; } } -} \ No newline at end of file +} diff --git a/src/services/shims.ts b/src/services/shims.ts index 906b8b59d3c..dc19b8eb79b 100644 --- a/src/services/shims.ts +++ b/src/services/shims.ts @@ -1,6 +1,6 @@ // // Copyright (c) Microsoft Corporation. All rights reserved. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -83,7 +83,7 @@ module ts { export interface Shim { dispose(dummy: any): void; } - + export interface LanguageServiceShim extends Shim { languageService: LanguageService; @@ -145,7 +145,7 @@ module ts { * { fileName: string; textSpan: { start: number; length: number}; isWriteAccess: boolean }[] */ getReferencesAtPosition(fileName: string, position: number): string; - + /** * Returns a JSON-encoded value of the type: * { definition: ; references: [] }[] @@ -162,8 +162,8 @@ module ts { /** * Returns a JSON-encoded value of the type: * { fileName: string; highlights: { start: number; length: number, isDefinition: boolean }[] }[] - * - * @param fileToSearch A JSON encoded string[] containing the file names that should be + * + * @param fileToSearch A JSON encoded string[] containing the file names that should be * considered when searching. */ getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; @@ -244,7 +244,7 @@ module ts { export class LanguageServiceShimHostAdapter implements LanguageServiceHost { private files: string[]; - + constructor(private shimHost: LanguageServiceShimHost) { } @@ -255,7 +255,7 @@ module ts { public trace(s: string): void { this.shimHost.trace(s); } - + public error(s: string): void { this.shimHost.error(s); } @@ -322,7 +322,7 @@ module ts { } } } - + export class CoreServicesShimHostAdapter implements ParseConfigHost { constructor(private shimHost: CoreServicesShimHost) { @@ -587,7 +587,7 @@ module ts { /** * Computes the definition location and file for the symbol - * at the requested position. + * at the requested position. */ public getDefinitionAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( @@ -601,7 +601,7 @@ module ts { /** * Computes the definition location of the type of the symbol - * at the requested position. + * at the requested position. */ public getTypeDefinitionAtPosition(fileName: string, position: number): string { return this.forwardJSONCall( @@ -684,8 +684,8 @@ module ts { /// COMPLETION LISTS /** - * Get a string based representation of the completions - * to provide at the given source position and providing a member completion + * Get a string based representation of the completions + * to provide at the given source position and providing a member completion * list if requested. */ public getCompletionsAtPosition(fileName: string, position: number) { @@ -883,7 +883,7 @@ module ts { return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: [realizeDiagnostics(configFile.errors, '\r\n')] }; }); } From 0c2ae8fc532fa93d895971176ff4f48ddc47868b Mon Sep 17 00:00:00 2001 From: Tingan Ho Date: Tue, 5 May 2015 23:37:31 +0800 Subject: [PATCH 22/31] Fixes iojs environment check issue --- src/harness/harness.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/harness/harness.ts b/src/harness/harness.ts index ee4e37c19f4..97d53a6b75e 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -45,10 +45,10 @@ module Utils { export function getExecutionEnvironment() { if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { return ExecutionEnvironment.CScript; - } else if (process && process.execPath && process.execPath.indexOf("node") !== -1) { - return ExecutionEnvironment.Node; - } else { + } else if (typeof window !== "undefined") { return ExecutionEnvironment.Browser; + } else { + return ExecutionEnvironment.Node; } } From 776f390786f1dc71236b4c124084a20da225d0ae Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 6 May 2015 20:28:03 +0900 Subject: [PATCH 23/31] PR feedback --- src/compiler/checker.ts | 15 +- ...nstanceOfByConstructorSignature.errors.txt | 438 +++++++++--------- ...rdsWithInstanceOfByConstructorSignature.js | 200 ++++---- ...rdsWithInstanceOfByConstructorSignature.ts | 20 +- 4 files changed, 334 insertions(+), 339 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c279786c686..eba6c954671 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -5368,22 +5368,17 @@ module ts { } } } - // Target type is type of constructor signiture + // Target type is type of construct signature let constructSignatures: Signature[]; if (rightType.flags & TypeFlags.Interface) { - constructSignatures = (rightType).declaredConstructSignatures; + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } else if (rightType.flags & TypeFlags.Anonymous) { - constructSignatures = (rightType).constructSignatures; + constructSignatures = getSignaturesOfType(rightType, SignatureKind.Construct); } - if (constructSignatures) { - let instanceType = getUnionType(map(constructSignatures, constructSignature => { - if (constructSignature.typeParameters && constructSignature.typeParameters.length !== 0) { - constructSignature = instantiateSignature(constructSignature, createTypeMapper(constructSignature.typeParameters, map(constructSignature.typeParameters, _ => anyType)), true) - } - return constructSignature.resolvedReturnType; - })); + if (constructSignatures && constructSignatures.length !== 0) { + let instanceType = getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))); // Pickup type from union types if (type.flags & TypeFlags.Union) { return getUnionTypeOfSubtypeConstituents(type, instanceType); diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt index 1816ef77fc2..b963b2c33ae 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.errors.txt @@ -1,220 +1,220 @@ -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(12,10): error TS2339: Property 'bar' does not exist on type 'A'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(33,5): error TS2322: Type 'string' is not assignable to type 'number'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(34,10): error TS2339: Property 'bar' does not exist on type 'B'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(63,10): error TS2339: Property 'bar2' does not exist on type 'C1'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(82,10): error TS2339: Property 'bar' does not exist on type 'D'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(109,10): error TS2339: Property 'bar2' does not exist on type 'E1'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(131,11): error TS2339: Property 'foo' does not exist on type 'string | F'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(132,11): error TS2339: Property 'bar' does not exist on type 'string | F'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(157,11): error TS2339: Property 'foo2' does not exist on type 'G1'. -tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(179,11): error TS2339: Property 'bar' does not exist on type 'H'. - - -==== tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts (10 errors) ==== - interface AConstructor { - new (): A; - } - interface A { - foo: string; - } - declare var A: AConstructor; - - var obj1: A | string; - if (obj1 instanceof A) { // narrowed to A. - obj1.foo; - obj1.bar; - ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'A'. - } - - var obj2: any; - if (obj2 instanceof A) { // can't type narrowing from any. - obj2.foo; - obj2.bar; - } - - // a construct signature with generics - interface BConstructor { - new (): B; - } - interface B { - foo: T; - } - declare var B: BConstructor; - - var obj3: B | string; - if (obj3 instanceof B) { // narrowed to B. - obj3.foo = 1; - obj3.foo = "str"; - ~~~~~~~~ -!!! error TS2322: Type 'string' is not assignable to type 'number'. - obj3.bar = "str"; - ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'B'. - } - - var obj4: any; - if (obj4 instanceof B) { // can't type narrowing from any. - obj4.foo = "str"; - obj4.foo = 1; - obj4.bar = "str"; - } - - // has multiple construct signature - interface CConstructor { - new (value: string): C1; - new (value: number): C2; - } - interface C1 { - foo: string; - bar1: number; - } - interface C2 { - foo: string; - bar2: number; - } - declare var C: CConstructor; - - var obj5: C1 | A; - if (obj5 instanceof C) { // narrowed to C1. - obj5.foo; - obj5.bar1; - obj5.bar2; - ~~~~ -!!! error TS2339: Property 'bar2' does not exist on type 'C1'. - } - - var obj6: any; - if (obj6 instanceof C) { // can't type narrowing from any. - obj6.foo; - obj6.bar1; - obj6.bar2; - } - - // with object type literal - interface D { - foo: string; - } - declare var D: { new (): D; }; - - var obj7: D | string; - if (obj7 instanceof D) { // narrowed to D. - obj7.foo; - obj7.bar; - ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'D'. - } - - var obj8: any; - if (obj8 instanceof D) { // can't type narrowing from any. - obj8.foo; - obj8.bar; - } - - // a construct signature that returns a union type - interface EConstructor { - new (): E1 | E2; - } - interface E1 { - foo: string; - bar1: number; - } - interface E2 { - foo: string; - bar2: number; - } - declare var E: EConstructor; - - var obj9: E1 | A; - if (obj9 instanceof E) { // narrowed to E1. - obj9.foo; - obj9.bar1; - obj9.bar2; - ~~~~ -!!! error TS2339: Property 'bar2' does not exist on type 'E1'. - } - - var obj10: any; - if (obj10 instanceof E) { // can't type narrowing from any. - obj10.foo; - obj10.bar1; - obj10.bar2; - } - - // a construct signature that returns any - interface FConstructor { - new (): any; - } - interface F { - foo: string; - bar: number; - } - declare var F: FConstructor; - - var obj11: F | string; - if (obj11 instanceof F) { // can't type narrowing, construct signiture returns any. - obj11.foo; - ~~~ -!!! error TS2339: Property 'foo' does not exist on type 'string | F'. - obj11.bar; - ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'string | F'. - } - - var obj12: any; - if (obj12 instanceof F) { // can't type narrowing from any. - obj12.foo; - obj12.bar; - } - - // a type with a prototype, it overrides the construct signiture - interface GConstructor { - prototype: G1; // high priority - new (): G2; // low priority - } - interface G1 { - foo1: number; - } - interface G2 { - foo2: boolean; - } - declare var G: GConstructor; - - var obj13: G1 | G2; - if (obj13 instanceof G) { // narrowed to G1. G1 is return type of prototype property. - obj13.foo1; - obj13.foo2; - ~~~~ -!!! error TS2339: Property 'foo2' does not exist on type 'G1'. - } - - var obj14: any; - if (obj14 instanceof G) { // can't type narrowing from any. - obj14.foo1; - obj14.foo2; - } - - // a type with a prototype that has any type - interface HConstructor { - prototype: any; // high priority, but any type is ignored. interface has implicit `prototype: any`. - new (): H; // low priority - } - interface H { - foo: number; - } - declare var H: HConstructor; - - var obj15: H | string; - if (obj15 instanceof H) { // narrowed to H. - obj15.foo; - obj15.bar; - ~~~ -!!! error TS2339: Property 'bar' does not exist on type 'H'. - } - - var obj16: any; - if (obj16 instanceof H) { // can't type narrowing from any. - obj16.foo1; - obj16.foo2; - } +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(12,10): error TS2339: Property 'bar' does not exist on type 'A'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(33,5): error TS2322: Type 'string' is not assignable to type 'number'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(34,10): error TS2339: Property 'bar' does not exist on type 'B'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(63,10): error TS2339: Property 'bar2' does not exist on type 'C1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(82,10): error TS2339: Property 'bar' does not exist on type 'D'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(109,10): error TS2339: Property 'bar2' does not exist on type 'E1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(131,11): error TS2339: Property 'foo' does not exist on type 'string | F'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(132,11): error TS2339: Property 'bar' does not exist on type 'string | F'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(157,11): error TS2339: Property 'foo2' does not exist on type 'G1'. +tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts(179,11): error TS2339: Property 'bar' does not exist on type 'H'. + + +==== tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts (10 errors) ==== + interface AConstructor { + new (): A; + } + interface A { + foo: string; + } + declare var A: AConstructor; + + var obj1: A | string; + if (obj1 instanceof A) { // narrowed to A. + obj1.foo; + obj1.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'A'. + } + + var obj2: any; + if (obj2 instanceof A) { // can't narrow type from 'any' + obj2.foo; + obj2.bar; + } + + // a construct signature with generics + interface BConstructor { + new (): B; + } + interface B { + foo: T; + } + declare var B: BConstructor; + + var obj3: B | string; + if (obj3 instanceof B) { // narrowed to B. + obj3.foo = 1; + obj3.foo = "str"; + ~~~~~~~~ +!!! error TS2322: Type 'string' is not assignable to type 'number'. + obj3.bar = "str"; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'B'. + } + + var obj4: any; + if (obj4 instanceof B) { // can't narrow type from 'any' + obj4.foo = "str"; + obj4.foo = 1; + obj4.bar = "str"; + } + + // has multiple construct signature + interface CConstructor { + new (value: string): C1; + new (value: number): C2; + } + interface C1 { + foo: string; + bar1: number; + } + interface C2 { + foo: string; + bar2: number; + } + declare var C: CConstructor; + + var obj5: C1 | A; + if (obj5 instanceof C) { // narrowed to C1. + obj5.foo; + obj5.bar1; + obj5.bar2; + ~~~~ +!!! error TS2339: Property 'bar2' does not exist on type 'C1'. + } + + var obj6: any; + if (obj6 instanceof C) { // can't narrow type from 'any' + obj6.foo; + obj6.bar1; + obj6.bar2; + } + + // with object type literal + interface D { + foo: string; + } + declare var D: { new (): D; }; + + var obj7: D | string; + if (obj7 instanceof D) { // narrowed to D. + obj7.foo; + obj7.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'D'. + } + + var obj8: any; + if (obj8 instanceof D) { // can't narrow type from 'any' + obj8.foo; + obj8.bar; + } + + // a construct signature that returns a union type + interface EConstructor { + new (): E1 | E2; + } + interface E1 { + foo: string; + bar1: number; + } + interface E2 { + foo: string; + bar2: number; + } + declare var E: EConstructor; + + var obj9: E1 | A; + if (obj9 instanceof E) { // narrowed to E1. + obj9.foo; + obj9.bar1; + obj9.bar2; + ~~~~ +!!! error TS2339: Property 'bar2' does not exist on type 'E1'. + } + + var obj10: any; + if (obj10 instanceof E) { // can't narrow type from 'any' + obj10.foo; + obj10.bar1; + obj10.bar2; + } + + // a construct signature that returns any + interface FConstructor { + new (): any; + } + interface F { + foo: string; + bar: number; + } + declare var F: FConstructor; + + var obj11: F | string; + if (obj11 instanceof F) { // can't type narrowing, construct signature returns any. + obj11.foo; + ~~~ +!!! error TS2339: Property 'foo' does not exist on type 'string | F'. + obj11.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'string | F'. + } + + var obj12: any; + if (obj12 instanceof F) { // can't narrow type from 'any' + obj12.foo; + obj12.bar; + } + + // a type with a prototype, it overrides the construct signature + interface GConstructor { + prototype: G1; // high priority + new (): G2; // low priority + } + interface G1 { + foo1: number; + } + interface G2 { + foo2: boolean; + } + declare var G: GConstructor; + + var obj13: G1 | G2; + if (obj13 instanceof G) { // narrowed to G1. G1 is return type of prototype property. + obj13.foo1; + obj13.foo2; + ~~~~ +!!! error TS2339: Property 'foo2' does not exist on type 'G1'. + } + + var obj14: any; + if (obj14 instanceof G) { // can't narrow type from 'any' + obj14.foo1; + obj14.foo2; + } + + // a type with a prototype that has any type + interface HConstructor { + prototype: any; // high priority, but any type is ignored. interface has implicit `prototype: any`. + new (): H; // low priority + } + interface H { + foo: number; + } + declare var H: HConstructor; + + var obj15: H | string; + if (obj15 instanceof H) { // narrowed to H. + obj15.foo; + obj15.bar; + ~~~ +!!! error TS2339: Property 'bar' does not exist on type 'H'. + } + + var obj16: any; + if (obj16 instanceof H) { // can't narrow type from 'any' + obj16.foo1; + obj16.foo2; + } \ No newline at end of file diff --git a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js index 395a5e96e05..e5b12bacb1f 100644 --- a/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js +++ b/tests/baselines/reference/typeGuardsWithInstanceOfByConstructorSignature.js @@ -1,4 +1,4 @@ -//// [typeGuardsWithInstanceOfByConstructorSignature.ts] +//// [typeGuardsWithInstanceOfByConstructorSignature.ts] interface AConstructor { new (): A; } @@ -14,7 +14,7 @@ if (obj1 instanceof A) { // narrowed to A. } var obj2: any; -if (obj2 instanceof A) { // can't type narrowing from any. +if (obj2 instanceof A) { // can't narrow type from 'any' obj2.foo; obj2.bar; } @@ -36,7 +36,7 @@ if (obj3 instanceof B) { // narrowed to B. } var obj4: any; -if (obj4 instanceof B) { // can't type narrowing from any. +if (obj4 instanceof B) { // can't narrow type from 'any' obj4.foo = "str"; obj4.foo = 1; obj4.bar = "str"; @@ -65,7 +65,7 @@ if (obj5 instanceof C) { // narrowed to C1. } var obj6: any; -if (obj6 instanceof C) { // can't type narrowing from any. +if (obj6 instanceof C) { // can't narrow type from 'any' obj6.foo; obj6.bar1; obj6.bar2; @@ -84,7 +84,7 @@ if (obj7 instanceof D) { // narrowed to D. } var obj8: any; -if (obj8 instanceof D) { // can't type narrowing from any. +if (obj8 instanceof D) { // can't narrow type from 'any' obj8.foo; obj8.bar; } @@ -111,7 +111,7 @@ if (obj9 instanceof E) { // narrowed to E1. } var obj10: any; -if (obj10 instanceof E) { // can't type narrowing from any. +if (obj10 instanceof E) { // can't narrow type from 'any' obj10.foo; obj10.bar1; obj10.bar2; @@ -128,18 +128,18 @@ interface F { declare var F: FConstructor; var obj11: F | string; -if (obj11 instanceof F) { // can't type narrowing, construct signiture returns any. +if (obj11 instanceof F) { // can't type narrowing, construct signature returns any. obj11.foo; obj11.bar; } var obj12: any; -if (obj12 instanceof F) { // can't type narrowing from any. +if (obj12 instanceof F) { // can't narrow type from 'any' obj12.foo; obj12.bar; } -// a type with a prototype, it overrides the construct signiture +// a type with a prototype, it overrides the construct signature interface GConstructor { prototype: G1; // high priority new (): G2; // low priority @@ -159,7 +159,7 @@ if (obj13 instanceof G) { // narrowed to G1. G1 is return type of prototype prop } var obj14: any; -if (obj14 instanceof G) { // can't type narrowing from any. +if (obj14 instanceof G) { // can't narrow type from 'any' obj14.foo1; obj14.foo2; } @@ -181,96 +181,96 @@ if (obj15 instanceof H) { // narrowed to H. } var obj16: any; -if (obj16 instanceof H) { // can't type narrowing from any. - obj16.foo1; - obj16.foo2; -} - - -//// [typeGuardsWithInstanceOfByConstructorSignature.js] -var obj1; -if (obj1 instanceof A) { - obj1.foo; - obj1.bar; -} -var obj2; -if (obj2 instanceof A) { - obj2.foo; - obj2.bar; -} -var obj3; -if (obj3 instanceof B) { - obj3.foo = 1; - obj3.foo = "str"; - obj3.bar = "str"; -} -var obj4; -if (obj4 instanceof B) { - obj4.foo = "str"; - obj4.foo = 1; - obj4.bar = "str"; -} -var obj5; -if (obj5 instanceof C) { - obj5.foo; - obj5.bar1; - obj5.bar2; -} -var obj6; -if (obj6 instanceof C) { - obj6.foo; - obj6.bar1; - obj6.bar2; -} -var obj7; -if (obj7 instanceof D) { - obj7.foo; - obj7.bar; -} -var obj8; -if (obj8 instanceof D) { - obj8.foo; - obj8.bar; -} -var obj9; -if (obj9 instanceof E) { - obj9.foo; - obj9.bar1; - obj9.bar2; -} -var obj10; -if (obj10 instanceof E) { - obj10.foo; - obj10.bar1; - obj10.bar2; -} -var obj11; -if (obj11 instanceof F) { - obj11.foo; - obj11.bar; -} -var obj12; -if (obj12 instanceof F) { - obj12.foo; - obj12.bar; -} -var obj13; -if (obj13 instanceof G) { - obj13.foo1; - obj13.foo2; -} -var obj14; -if (obj14 instanceof G) { - obj14.foo1; - obj14.foo2; -} -var obj15; -if (obj15 instanceof H) { - obj15.foo; - obj15.bar; -} -var obj16; -if (obj16 instanceof H) { +if (obj16 instanceof H) { // can't narrow type from 'any' obj16.foo1; obj16.foo2; } + + +//// [typeGuardsWithInstanceOfByConstructorSignature.js] +var obj1; +if (obj1 instanceof A) { + obj1.foo; + obj1.bar; +} +var obj2; +if (obj2 instanceof A) { + obj2.foo; + obj2.bar; +} +var obj3; +if (obj3 instanceof B) { + obj3.foo = 1; + obj3.foo = "str"; + obj3.bar = "str"; +} +var obj4; +if (obj4 instanceof B) { + obj4.foo = "str"; + obj4.foo = 1; + obj4.bar = "str"; +} +var obj5; +if (obj5 instanceof C) { + obj5.foo; + obj5.bar1; + obj5.bar2; +} +var obj6; +if (obj6 instanceof C) { + obj6.foo; + obj6.bar1; + obj6.bar2; +} +var obj7; +if (obj7 instanceof D) { + obj7.foo; + obj7.bar; +} +var obj8; +if (obj8 instanceof D) { + obj8.foo; + obj8.bar; +} +var obj9; +if (obj9 instanceof E) { + obj9.foo; + obj9.bar1; + obj9.bar2; +} +var obj10; +if (obj10 instanceof E) { + obj10.foo; + obj10.bar1; + obj10.bar2; +} +var obj11; +if (obj11 instanceof F) { + obj11.foo; + obj11.bar; +} +var obj12; +if (obj12 instanceof F) { + obj12.foo; + obj12.bar; +} +var obj13; +if (obj13 instanceof G) { + obj13.foo1; + obj13.foo2; +} +var obj14; +if (obj14 instanceof G) { + obj14.foo1; + obj14.foo2; +} +var obj15; +if (obj15 instanceof H) { + obj15.foo; + obj15.bar; +} +var obj16; +if (obj16 instanceof H) { + obj16.foo1; + obj16.foo2; +} diff --git a/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts b/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts index c432ceb2bda..fee92ff10ca 100644 --- a/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts +++ b/tests/cases/conformance/expressions/typeGuards/typeGuardsWithInstanceOfByConstructorSignature.ts @@ -13,7 +13,7 @@ if (obj1 instanceof A) { // narrowed to A. } var obj2: any; -if (obj2 instanceof A) { // can't type narrowing from any. +if (obj2 instanceof A) { // can't narrow type from 'any' obj2.foo; obj2.bar; } @@ -35,7 +35,7 @@ if (obj3 instanceof B) { // narrowed to B. } var obj4: any; -if (obj4 instanceof B) { // can't type narrowing from any. +if (obj4 instanceof B) { // can't narrow type from 'any' obj4.foo = "str"; obj4.foo = 1; obj4.bar = "str"; @@ -64,7 +64,7 @@ if (obj5 instanceof C) { // narrowed to C1. } var obj6: any; -if (obj6 instanceof C) { // can't type narrowing from any. +if (obj6 instanceof C) { // can't narrow type from 'any' obj6.foo; obj6.bar1; obj6.bar2; @@ -83,7 +83,7 @@ if (obj7 instanceof D) { // narrowed to D. } var obj8: any; -if (obj8 instanceof D) { // can't type narrowing from any. +if (obj8 instanceof D) { // can't narrow type from 'any' obj8.foo; obj8.bar; } @@ -110,7 +110,7 @@ if (obj9 instanceof E) { // narrowed to E1. } var obj10: any; -if (obj10 instanceof E) { // can't type narrowing from any. +if (obj10 instanceof E) { // can't narrow type from 'any' obj10.foo; obj10.bar1; obj10.bar2; @@ -127,18 +127,18 @@ interface F { declare var F: FConstructor; var obj11: F | string; -if (obj11 instanceof F) { // can't type narrowing, construct signiture returns any. +if (obj11 instanceof F) { // can't type narrowing, construct signature returns any. obj11.foo; obj11.bar; } var obj12: any; -if (obj12 instanceof F) { // can't type narrowing from any. +if (obj12 instanceof F) { // can't narrow type from 'any' obj12.foo; obj12.bar; } -// a type with a prototype, it overrides the construct signiture +// a type with a prototype, it overrides the construct signature interface GConstructor { prototype: G1; // high priority new (): G2; // low priority @@ -158,7 +158,7 @@ if (obj13 instanceof G) { // narrowed to G1. G1 is return type of prototype prop } var obj14: any; -if (obj14 instanceof G) { // can't type narrowing from any. +if (obj14 instanceof G) { // can't narrow type from 'any' obj14.foo1; obj14.foo2; } @@ -180,7 +180,7 @@ if (obj15 instanceof H) { // narrowed to H. } var obj16: any; -if (obj16 instanceof H) { // can't type narrowing from any. +if (obj16 instanceof H) { // can't narrow type from 'any' obj16.foo1; obj16.foo2; } From e43680de11335ce872efba4c2f8de84563b5e8bf Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 6 May 2015 10:13:32 -0700 Subject: [PATCH 24/31] show more clearly error message when found missing module name Conflicts: src/compiler/diagnosticInformationMap.generated.ts src/compiler/diagnosticMessages.json --- src/compiler/checker.ts | 8 +- .../diagnosticInformationMap.generated.ts | 1 + src/compiler/diagnosticMessages.json | 4 + .../reference/aliasErrors.errors.txt | 12 +- ...torWithIncompleteTypeAnnotation.errors.txt | 5 +- .../declareModifierOnImport1.errors.txt | 4 +- .../importedModuleAddToGlobal.errors.txt | 4 +- .../invalidImportAliasIdentifiers.errors.txt | 16 +- .../invalidInstantiatedModule.errors.txt | 4 +- ...tyAccessAndArrowFunctionIndent1.errors.txt | 4 +- .../reference/parser519458.errors.txt | 5 +- .../parserGenericsInTypeContexts1.errors.txt | 8 +- .../parserGenericsInTypeContexts2.errors.txt | 8 +- .../parserImportDeclaration1.errors.txt | 4 +- ...nfinishedTypeNameBeforeKeyword1.errors.txt | 4 +- .../parserVariableDeclaration3.errors.txt | 4 +- .../reference/parserharness.errors.txt | 168 +++++++++--------- .../reference/parserindenter.errors.txt | 16 +- .../parservoidInQualifiedName2.errors.txt | 4 +- .../primaryExpressionMods.errors.txt | 4 +- .../scannerImportDeclaration1.errors.txt | 4 +- .../strictModeReservedWord.errors.txt | 20 +-- ...eReservedWordInClassDeclaration.errors.txt | 12 +- .../reference/unknownSymbols2.errors.txt | 4 +- 24 files changed, 172 insertions(+), 155 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index f413110a34b..ce2d9150319 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -803,7 +803,13 @@ module ts { let symbol: Symbol; if (name.kind === SyntaxKind.Identifier) { - symbol = resolveName(name, (name).text, meaning, Diagnostics.Cannot_find_name_0, name); + let message: DiagnosticMessage; + if (meaning === SymbolFlags.Namespace) { + message = Diagnostics.Cannot_find_namespace_0; + } else { + message = Diagnostics.Cannot_find_name_0; + } + symbol = resolveName(name, (name).text, meaning, message, name); if (!symbol) { return undefined; } diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index 4eed4a85329..1f8edf8fee3 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -364,6 +364,7 @@ module ts { A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." }, A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, + Cannot_find_namespace_0: { code: 2503, category: DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index d7d1011ce7f..42eae83e269 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1444,6 +1444,10 @@ "category": "Error", "code": 2502 }, + "Cannot find namespace '{0}'.": { + "category": "Error", + "code": 2503 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", diff --git a/tests/baselines/reference/aliasErrors.errors.txt b/tests/baselines/reference/aliasErrors.errors.txt index ffc114f80e3..c74649618ba 100644 --- a/tests/baselines/reference/aliasErrors.errors.txt +++ b/tests/baselines/reference/aliasErrors.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/aliasErrors.ts(11,12): error TS2304: Cannot find name 'no'. -tests/cases/compiler/aliasErrors.ts(12,13): error TS2304: Cannot find name 'no'. +tests/cases/compiler/aliasErrors.ts(11,12): error TS2503: Cannot find namespace 'no'. +tests/cases/compiler/aliasErrors.ts(12,13): error TS2503: Cannot find namespace 'no'. tests/cases/compiler/aliasErrors.ts(13,12): error TS1003: Identifier expected. tests/cases/compiler/aliasErrors.ts(14,12): error TS1003: Identifier expected. tests/cases/compiler/aliasErrors.ts(15,12): error TS1003: Identifier expected. -tests/cases/compiler/aliasErrors.ts(16,12): error TS2304: Cannot find name 'undefined'. +tests/cases/compiler/aliasErrors.ts(16,12): error TS2503: Cannot find namespace 'undefined'. tests/cases/compiler/aliasErrors.ts(26,15): error TS2305: Module 'foo.bar.baz' has no exported member 'bar'. @@ -20,10 +20,10 @@ tests/cases/compiler/aliasErrors.ts(26,15): error TS2305: Module 'foo.bar.baz' h import m = no; ~~ -!!! error TS2304: Cannot find name 'no'. +!!! error TS2503: Cannot find namespace 'no'. import m2 = no.mod; ~~ -!!! error TS2304: Cannot find name 'no'. +!!! error TS2503: Cannot find namespace 'no'. import n = 5; ~ !!! error TS1003: Identifier expected. @@ -35,7 +35,7 @@ tests/cases/compiler/aliasErrors.ts(26,15): error TS2305: Module 'foo.bar.baz' h !!! error TS1003: Identifier expected. import r = undefined; ~~~~~~~~~ -!!! error TS2304: Cannot find name 'undefined'. +!!! error TS2503: Cannot find namespace 'undefined'. var p = new provide.Provide(); diff --git a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt index 5d607c8f5b2..2818793948f 100644 --- a/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt +++ b/tests/baselines/reference/constructorWithIncompleteTypeAnnotation.errors.txt @@ -1,4 +1,5 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2304: Cannot find name 'module'. +tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,13): error TS2503: Cannot find namespace 'module'. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(11,19): error TS1005: ';' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,35): error TS1005: ')' expected. tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(22,39): error TS2363: The right-hand side of an arithmetic operation must be of type 'any', 'number' or an enum type. @@ -82,7 +83,7 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(259,55): error T tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS1128: Declaration or statement expected. -==== tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts (82 errors) ==== +==== tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts (83 errors) ==== declare module "fs" { export class File { constructor(filename: string); @@ -96,6 +97,8 @@ tests/cases/compiler/constructorWithIncompleteTypeAnnotation.ts(261,1): error TS import fs = module("fs"); ~~~~~~ !!! error TS2304: Cannot find name 'module'. + ~~~~~~ +!!! error TS2503: Cannot find namespace 'module'. ~ !!! error TS1005: ';' expected. diff --git a/tests/baselines/reference/declareModifierOnImport1.errors.txt b/tests/baselines/reference/declareModifierOnImport1.errors.txt index 776f2c07bcb..7260a8e48f3 100644 --- a/tests/baselines/reference/declareModifierOnImport1.errors.txt +++ b/tests/baselines/reference/declareModifierOnImport1.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/declareModifierOnImport1.ts(1,1): error TS1079: A 'declare' modifier cannot be used with an import declaration. -tests/cases/compiler/declareModifierOnImport1.ts(1,20): error TS2304: Cannot find name 'b'. +tests/cases/compiler/declareModifierOnImport1.ts(1,20): error TS2503: Cannot find namespace 'b'. ==== tests/cases/compiler/declareModifierOnImport1.ts (2 errors) ==== @@ -7,4 +7,4 @@ tests/cases/compiler/declareModifierOnImport1.ts(1,20): error TS2304: Cannot fin ~~~~~~~ !!! error TS1079: A 'declare' modifier cannot be used with an import declaration. ~ -!!! error TS2304: Cannot find name 'b'. \ No newline at end of file +!!! error TS2503: Cannot find namespace 'b'. \ No newline at end of file diff --git a/tests/baselines/reference/importedModuleAddToGlobal.errors.txt b/tests/baselines/reference/importedModuleAddToGlobal.errors.txt index 8948c67f78b..aed680b89aa 100644 --- a/tests/baselines/reference/importedModuleAddToGlobal.errors.txt +++ b/tests/baselines/reference/importedModuleAddToGlobal.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/importedModuleAddToGlobal.ts(15,23): error TS2304: Cannot find name 'b'. +tests/cases/compiler/importedModuleAddToGlobal.ts(15,23): error TS2503: Cannot find namespace 'b'. ==== tests/cases/compiler/importedModuleAddToGlobal.ts (1 errors) ==== @@ -18,5 +18,5 @@ tests/cases/compiler/importedModuleAddToGlobal.ts(15,23): error TS2304: Cannot f import a = A; function hello(): b.B { return null; } ~ -!!! error TS2304: Cannot find name 'b'. +!!! error TS2503: Cannot find namespace 'b'. } \ No newline at end of file diff --git a/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt b/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt index 7794fb027d7..fb29c829947 100644 --- a/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt +++ b/tests/baselines/reference/invalidImportAliasIdentifiers.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(5,12): error TS2304: Cannot find name 'V'. -tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(11,12): error TS2304: Cannot find name 'C'. -tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(17,12): error TS2304: Cannot find name 'E'. -tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(23,12): error TS2304: Cannot find name 'I'. +tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(5,12): error TS2503: Cannot find namespace 'V'. +tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(11,12): error TS2503: Cannot find namespace 'C'. +tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(17,12): error TS2503: Cannot find namespace 'E'. +tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts(23,12): error TS2503: Cannot find namespace 'I'. ==== tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIdentifiers.ts (4 errors) ==== @@ -11,7 +11,7 @@ tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIde import v = V; ~ -!!! error TS2304: Cannot find name 'V'. +!!! error TS2503: Cannot find namespace 'V'. class C { name: string; @@ -19,7 +19,7 @@ tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIde import c = C; ~ -!!! error TS2304: Cannot find name 'C'. +!!! error TS2503: Cannot find namespace 'C'. enum E { Red, Blue @@ -27,7 +27,7 @@ tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIde import e = E; ~ -!!! error TS2304: Cannot find name 'E'. +!!! error TS2503: Cannot find namespace 'E'. interface I { id: number; @@ -35,5 +35,5 @@ tests/cases/conformance/internalModules/importDeclarations/invalidImportAliasIde import i = I; ~ -!!! error TS2304: Cannot find name 'I'. +!!! error TS2503: Cannot find namespace 'I'. \ No newline at end of file diff --git a/tests/baselines/reference/invalidInstantiatedModule.errors.txt b/tests/baselines/reference/invalidInstantiatedModule.errors.txt index 8bd7e6492c0..540f22f5951 100644 --- a/tests/baselines/reference/invalidInstantiatedModule.errors.txt +++ b/tests/baselines/reference/invalidInstantiatedModule.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/internalModules/moduleDeclarations/invalidInstantiatedModule.ts(2,18): error TS2300: Duplicate identifier 'Point'. tests/cases/conformance/internalModules/moduleDeclarations/invalidInstantiatedModule.ts(3,16): error TS2300: Duplicate identifier 'Point'. -tests/cases/conformance/internalModules/moduleDeclarations/invalidInstantiatedModule.ts(12,8): error TS2304: Cannot find name 'm'. +tests/cases/conformance/internalModules/moduleDeclarations/invalidInstantiatedModule.ts(12,8): error TS2503: Cannot find namespace 'm'. ==== tests/cases/conformance/internalModules/moduleDeclarations/invalidInstantiatedModule.ts (3 errors) ==== @@ -21,7 +21,7 @@ tests/cases/conformance/internalModules/moduleDeclarations/invalidInstantiatedMo var m = M2; var p: m.Point; // Error ~ -!!! error TS2304: Cannot find name 'm'. +!!! error TS2503: Cannot find namespace 'm'. \ No newline at end of file diff --git a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt index c85e7584139..14b7769d22f 100644 --- a/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt +++ b/tests/baselines/reference/multiLinePropertyAccessAndArrowFunctionIndent1.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(1,1): error TS1108: A 'return' statement can only be used within a function body. tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(2,18): error TS2304: Cannot find name 'Role'. -tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(4,26): error TS2304: Cannot find name 'ng'. +tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(4,26): error TS2503: Cannot find namespace 'ng'. ==== tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts (3 errors) ==== @@ -13,5 +13,5 @@ tests/cases/compiler/multiLinePropertyAccessAndArrowFunctionIndent1.ts(4,26): er this.roleService.add(role) .then((data: ng.IHttpPromiseCallbackArg) => data.data)); ~~ -!!! error TS2304: Cannot find name 'ng'. +!!! error TS2503: Cannot find namespace 'ng'. \ No newline at end of file diff --git a/tests/baselines/reference/parser519458.errors.txt b/tests/baselines/reference/parser519458.errors.txt index e618e38723f..66dae596b81 100644 --- a/tests/baselines/reference/parser519458.errors.txt +++ b/tests/baselines/reference/parser519458.errors.txt @@ -1,11 +1,14 @@ tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts(1,15): error TS2304: Cannot find name 'module'. +tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts(1,15): error TS2503: Cannot find namespace 'module'. tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts(1,21): error TS1005: ';' expected. -==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts (2 errors) ==== +==== tests/cases/conformance/parser/ecmascript5/RegressionTests/parser519458.ts (3 errors) ==== import rect = module("rect"); var bar = new rect.Rect(); ~~~~~~ !!! error TS2304: Cannot find name 'module'. + ~~~~~~ +!!! error TS2503: Cannot find namespace 'module'. ~ !!! error TS1005: ';' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt index 8b9304d9165..75652c829ee 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts1.errors.txt @@ -2,8 +2,8 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(1,33): error TS2304: Cannot find name 'B'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(4,9): error TS2315: Type 'C' is not generic. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(5,9): error TS2304: Cannot find name 'D'. -tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(6,9): error TS2304: Cannot find name 'E'. -tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(7,9): error TS2304: Cannot find name 'G'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(6,9): error TS2503: Cannot find namespace 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(7,9): error TS2503: Cannot find namespace 'G'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(8,9): error TS2304: Cannot find name 'K'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(11,16): error TS2304: Cannot find name 'E'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts1.ts(14,16): error TS2304: Cannot find name 'F'. @@ -26,10 +26,10 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts !!! error TS2304: Cannot find name 'D'. var v3: E.F; ~ -!!! error TS2304: Cannot find name 'E'. +!!! error TS2503: Cannot find namespace 'E'. var v3: G.H.I; ~ -!!! error TS2304: Cannot find name 'G'. +!!! error TS2503: Cannot find namespace 'G'. var v6: K[]; ~ !!! error TS2304: Cannot find name 'K'. diff --git a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt index 0ef716d1804..c365f461b7c 100644 --- a/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt +++ b/tests/baselines/reference/parserGenericsInTypeContexts2.errors.txt @@ -2,8 +2,8 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(1,45): error TS2304: Cannot find name 'B'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(4,9): error TS2315: Type 'C' is not generic. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(5,9): error TS2304: Cannot find name 'D'. -tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,9): error TS2304: Cannot find name 'E'. -tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,9): error TS2304: Cannot find name 'G'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(6,9): error TS2503: Cannot find namespace 'E'. +tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(7,9): error TS2503: Cannot find namespace 'G'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(8,9): error TS2304: Cannot find name 'K'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(11,16): error TS2304: Cannot find name 'E'. tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts2.ts(14,16): error TS2304: Cannot find name 'F'. @@ -26,10 +26,10 @@ tests/cases/conformance/parser/ecmascript5/Generics/parserGenericsInTypeContexts !!! error TS2304: Cannot find name 'D'. var v3: E.F, Y>>; ~ -!!! error TS2304: Cannot find name 'E'. +!!! error TS2503: Cannot find namespace 'E'. var v4: G.H.I, Y>>; ~ -!!! error TS2304: Cannot find name 'G'. +!!! error TS2503: Cannot find namespace 'G'. var v6: K, Y>>[]; ~ !!! error TS2304: Cannot find name 'K'. diff --git a/tests/baselines/reference/parserImportDeclaration1.errors.txt b/tests/baselines/reference/parserImportDeclaration1.errors.txt index ec3397cd196..099474d3d41 100644 --- a/tests/baselines/reference/parserImportDeclaration1.errors.txt +++ b/tests/baselines/reference/parserImportDeclaration1.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/parser/ecmascript5/parserImportDeclaration1.ts(1,21): error TS2304: Cannot find name 'TypeScriptServices'. +tests/cases/conformance/parser/ecmascript5/parserImportDeclaration1.ts(1,21): error TS2503: Cannot find namespace 'TypeScriptServices'. ==== tests/cases/conformance/parser/ecmascript5/parserImportDeclaration1.ts (1 errors) ==== import TypeScript = TypeScriptServices.TypeScript; ~~~~~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScriptServices'. \ No newline at end of file +!!! error TS2503: Cannot find namespace 'TypeScriptServices'. \ No newline at end of file diff --git a/tests/baselines/reference/parserUnfinishedTypeNameBeforeKeyword1.errors.txt b/tests/baselines/reference/parserUnfinishedTypeNameBeforeKeyword1.errors.txt index 569c960404c..7eed3dbe026 100644 --- a/tests/baselines/reference/parserUnfinishedTypeNameBeforeKeyword1.errors.txt +++ b/tests/baselines/reference/parserUnfinishedTypeNameBeforeKeyword1.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnfinishedTypeNameBeforeKeyword1.ts(1,8): error TS2304: Cannot find name 'TypeModule1'. +tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnfinishedTypeNameBeforeKeyword1.ts(1,8): error TS2503: Cannot find namespace 'TypeModule1'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnfinishedTypeNameBeforeKeyword1.ts(2,8): error TS1005: '=' expected. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnfinishedTypeNameBeforeKeyword1.ts(2,8): error TS2304: Cannot find name 'TypeModule2'. tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnfinishedTypeNameBeforeKeyword1.ts(2,20): error TS1005: ',' expected. @@ -7,7 +7,7 @@ tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnfinishedTypeNam ==== tests/cases/conformance/parser/ecmascript5/ErrorRecovery/parserUnfinishedTypeNameBeforeKeyword1.ts (4 errors) ==== var x: TypeModule1. ~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeModule1'. +!!! error TS2503: Cannot find namespace 'TypeModule1'. module TypeModule2 { ~~~~~~~~~~~ !!! error TS1005: '=' expected. diff --git a/tests/baselines/reference/parserVariableDeclaration3.errors.txt b/tests/baselines/reference/parserVariableDeclaration3.errors.txt index bb4e5eceaf6..a2130449f4b 100644 --- a/tests/baselines/reference/parserVariableDeclaration3.errors.txt +++ b/tests/baselines/reference/parserVariableDeclaration3.errors.txt @@ -1,6 +1,6 @@ tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration3.ts(2,23): error TS2304: Cannot find name 'Harness'. tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration3.ts(3,22): error TS2304: Cannot find name 'Harness'. -tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration3.ts(4,21): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration3.ts(4,21): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDeclaration3.ts(4,55): error TS2304: Cannot find name 'TypeScript'. @@ -14,7 +14,7 @@ tests/cases/conformance/parser/ecmascript5/VariableDeclarations/parserVariableDe !!! error TS2304: Cannot find name 'Harness'. , compiler = new TypeScript.TypeScriptCompiler(outerr) ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. , code; diff --git a/tests/baselines/reference/parserharness.errors.txt b/tests/baselines/reference/parserharness.errors.txt index 2452cd76a18..66afa3d010f 100644 --- a/tests/baselines/reference/parserharness.errors.txt +++ b/tests/baselines/reference/parserharness.errors.txt @@ -13,25 +13,25 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(351,17): e tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(354,17): error TS2304: Cannot find name 'errorHandlerStack'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(354,35): error TS2304: Cannot find name 'errorHandlerStack'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(691,50): error TS2304: Cannot find name 'ITextWriter'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(716,47): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(716,47): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(721,62): error TS2304: Cannot find name 'ITextWriter'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(724,29): error TS2304: Cannot find name 'ITextWriter'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(754,53): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(764,56): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(764,56): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(765,37): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(767,47): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,13): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(776,42): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(781,23): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(781,23): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(794,49): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(795,49): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,53): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,89): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,115): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,115): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(987,145): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(988,43): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(999,40): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1041,43): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(999,40): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1041,43): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1044,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1045,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1046,26): error TS2304: Cannot find name 'TypeScript'. @@ -44,69 +44,69 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1052,26): tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1053,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1055,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1058,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1059,34): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1059,34): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1061,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1064,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1065,34): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1065,34): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1067,26): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1070,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1071,34): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1071,34): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1073,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1074,34): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1074,34): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1076,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1077,34): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1077,34): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1079,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,35): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,74): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1107,173): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1176,132): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,35): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1080,74): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1107,173): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1176,132): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1193,29): error TS2304: Cannot find name 'WScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1256,126): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1257,25): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1263,31): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1256,126): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1257,25): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1263,31): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1280,45): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,124): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,209): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,142): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,227): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,124): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1286,209): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,142): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1294,227): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1302,43): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1304,39): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1307,38): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1311,45): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1321,21): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1340,38): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1344,165): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1345,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1426,25): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1340,38): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1344,165): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1345,26): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1426,25): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1430,9): error TS1128: Declaration or statement expected. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1430,17): error TS2304: Cannot find name 'optionRegex'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1440,29): error TS2304: Cannot find name 'optionRegex'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1461,23): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1461,23): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1466,36): error TS2304: Cannot find name 'optionRegex'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1484,21): error TS2304: Cannot find name 'optionRegex'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1548,57): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1548,57): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1571,32): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1582,59): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1582,59): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1591,24): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1600,24): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1604,42): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1605,21): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1705,38): error TS2304: Cannot find name 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1604,42): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1605,21): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1705,38): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1706,26): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,62): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,87): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,62): error TS2503: Cannot find namespace 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1713,87): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1714,30): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1724,34): error TS2304: Cannot find name 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1739,20): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1746,80): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1746,80): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1750,26): error TS2304: Cannot find name 'TypeScript'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1758,84): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1769,51): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,39): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,61): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1785,25): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,38): error TS2304: Cannot find name 'Services'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,68): error TS2304: Cannot find name 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1758,84): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1769,51): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,39): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1784,61): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1785,25): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,38): error TS2503: Cannot find namespace 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(1787,68): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): error TS2304: Cannot find name 'Diff'. @@ -858,7 +858,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): /** Mimics having multiple files, later concatenated to a single file. */ export class EmitterIOHost implements TypeScript.EmitterIOHost { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. private fileCollection = {}; @@ -914,7 +914,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): export function makeDefaultCompilerForTest(c?: TypeScript.TypeScriptCompiler) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var compiler = c || new TypeScript.TypeScriptCompiler(stderr); ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. @@ -941,7 +941,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var compiler: TypeScript.TypeScriptCompiler; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. recreate(); // pullUpdateUnit is sufficient if an existing unit is updated, if a new unit is added we need to do a full typecheck @@ -1157,7 +1157,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. var entries = new TypeScript.ScopeTraversal(compiler).getScopeEntries(enclosingScopeContext); @@ -1175,7 +1175,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): for (var m = 0; m < compiler.scripts.members.length; m++) { var script2 = compiler.scripts.members[m]; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. if (script2.locationInfo.filename !== 'lib.d.ts') { if (targetPosition > -1) { var tyInfo = compiler.pullGetTypeInfoAtPosition(targetPosition, script2); @@ -1219,7 +1219,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): private getTypeInfoName(ast : TypeScript.AST) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var name = ''; switch (ast.nodeType) { case TypeScript.NodeType.Name: // Type Name? @@ -1263,7 +1263,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2304: Cannot find name 'TypeScript'. name = (ast).text; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.QString: ~~~~~~~~~~ @@ -1275,7 +1275,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2304: Cannot find name 'TypeScript'. name = (ast).text; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.Return: ~~~~~~~~~~ @@ -1287,30 +1287,30 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): !!! error TS2304: Cannot find name 'TypeScript'. name = (ast).name.actualText; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.ModuleDeclaration: ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. name = (ast).name.actualText; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.ClassDeclaration: ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. name = (ast).name.actualText; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. break; case TypeScript.NodeType.FuncDecl: ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. name = !(ast).name ? "" : (ast).name.actualText; // name == null for lambdas ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. break; default: // TODO: is there a reason to mess with all the special cases above and not just do this (ie take whatever property is there and works?) @@ -1339,7 +1339,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): */ export function generateDeclFile(code: string, verifyNoDeclFile: boolean, unitName?: string, compilationContext?: Harness.Compiler.CompilationContext, references?: TypeScript.IFileReference[]): string { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. reset(); compiler.settings.generateDeclarationFiles = true; @@ -1410,7 +1410,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): /** @param fileResults an array of strings for the filename and an ITextWriter with its code */ constructor(public fileResults: { filename: string; file: WriterAggregator; }[], errorLines: string[], public scripts: TypeScript.Script[]) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var lines = []; fileResults.forEach(v => lines = lines.concat(v.file.lines)); this.code = lines.join("\n") @@ -1494,10 +1494,10 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): export function addUnit(code: string, unitName?: string, isResident?: boolean, isDeclareFile?: boolean, references?: TypeScript.IFileReference[]) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var script: TypeScript.Script = null; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var uName = unitName || '0' + (isDeclareFile ? '.d.ts' : '.ts'); for (var i = 0; i < compiler.units.length; i++) { @@ -1505,7 +1505,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): updateUnit(code, uName); script = compiler.scripts.members[i]; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. } } if (!script) { @@ -1532,9 +1532,9 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): export function compileFile(path: string, callback: (res: CompilerResult) => void , settingsCallback?: (settings?: TypeScript.CompilationSettings) => void , context?: CompilationContext, references?: TypeScript.IFileReference[]) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. path = switchToForwardSlashes(path); var filename = path.match(/[^\/]*$/)[0]; var code = readFile(path); @@ -1544,9 +1544,9 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): export function compileUnit(code: string, filename: string, callback: (res: CompilerResult) => void , settingsCallback?: (settings?: TypeScript.CompilationSettings) => void , context?: CompilationContext, references?: TypeScript.IFileReference[]) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. // not recursive function clone/* */(source: any, target: any) { for (var prop in source) { @@ -1604,16 +1604,16 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): export function emit(ioHost: TypeScript.EmitterIOHost, usePullEmitter?: boolean) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. compiler.emit(ioHost, usePullEmitter); } export function compileString(code: string, unitName: string, callback: (res: Compiler.CompilerResult) => void , context?: CompilationContext, references?: TypeScript.IFileReference[]) { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var scripts: TypeScript.Script[] = []; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. reset(); @@ -1696,7 +1696,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): originalFilePath: string; references: TypeScript.IFileReference[]; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. } // Regex for parsing options in the format "@Alpha: Value of any sort" @@ -1739,7 +1739,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): var currentFileName = null; var refs: TypeScript.IFileReference[] = []; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. for (var i = 0; i < lines.length; i++) { var line = lines[i]; @@ -1832,7 +1832,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): public version: number; public editRanges: { length: number; editRange: TypeScript.ScriptEditRange; }[] = []; ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. constructor(public name: string, public content: string, public isResident: boolean, public maxScriptVersions: number) { this.version = 1; @@ -1870,7 +1870,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): public getEditRangeSinceVersion(version: number): TypeScript.ScriptEditRange { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. if (this.version == version) { // No edits! return null; @@ -1898,10 +1898,10 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): export class TypeScriptLS implements Services.ILanguageServiceShimHost { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. private ls: Services.ILanguageServiceShim = null; ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. public scripts: ScriptInfo[] = []; public maxScriptVersions = 100; @@ -2003,7 +2003,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): */ public getLanguageService(): Services.ILanguageServiceShim { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. var ls = new Services.TypeScriptServicesFactory().createLanguageServiceShim(this); ~~~~~~~~ !!! error TS2304: Cannot find name 'Services'. @@ -2015,9 +2015,9 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): /** Parse file given its source text */ public parseSourceText(fileName: string, sourceText: TypeScript.ISourceText): TypeScript.Script { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var parser = new TypeScript.Parser(); ~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeScript'. @@ -2058,7 +2058,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): */ public positionToZeroBasedLineCol(fileName: string, position: number): TypeScript.ILineCol { ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. var script = this.ls.languageService.getScriptAST(fileName); assert.notNull(script); @@ -2074,7 +2074,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): /** Verify that applying edits to sourceFileName result in the content of the file baselineFileName */ public checkEdits(sourceFileName: string, baselineFileName: string, edits: Services.TextEdit[]) { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. var script = readFile(sourceFileName); var formattedScript = this.applyEdits(script, edits); var baseline = readFile(baselineFileName); @@ -2087,7 +2087,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): /** Apply an array of text edits to a string, and return the resulting string. */ public applyEdits(content: string, edits: Services.TextEdit[]): string { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. var result = content; edits = this.normalizeEdits(edits); @@ -2104,18 +2104,18 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserharness.ts(2030,32): /** Normalize an array of edits by removing overlapping entries and sorting entries on the minChar position. */ private normalizeEdits(edits: Services.TextEdit[]): Services.TextEdit[] { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. var result: Services.TextEdit[] = []; ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. function mapEdits(edits: Services.TextEdit[]): { edit: Services.TextEdit; index: number; }[] { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. var result = []; for (var i = 0; i < edits.length; i++) { result.push({ edit: edits[i], index: i }); diff --git a/tests/baselines/reference/parserindenter.errors.txt b/tests/baselines/reference/parserindenter.errors.txt index 3d8e5f7cc45..a332abab7bb 100644 --- a/tests/baselines/reference/parserindenter.errors.txt +++ b/tests/baselines/reference/parserindenter.errors.txt @@ -2,10 +2,10 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(16,1): er tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(20,38): error TS2304: Cannot find name 'ILineIndenationResolver'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(22,33): error TS2304: Cannot find name 'IndentationBag'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(24,42): error TS2304: Cannot find name 'Dictionary_int_int'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(27,28): error TS2304: Cannot find name 'TypeScript'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(27,28): error TS2503: Cannot find namespace 'TypeScript'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(28,26): error TS2304: Cannot find name 'ParseTree'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(29,30): error TS2304: Cannot find name 'ITextSnapshot'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(31,35): error TS2304: Cannot find name 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(31,35): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(32,32): error TS2304: Cannot find name 'TokenSpan'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(35,39): error TS2304: Cannot find name 'IndentationBag'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(37,48): error TS2304: Cannot find name 'Dictionary_int_int'. @@ -27,9 +27,9 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(152,51): tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(152,63): error TS2304: Cannot find name 'List_TextEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(153,30): error TS2304: Cannot find name 'List_TextEditInfo'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(155,32): error TS2304: Cannot find name 'AuthorTokenKind'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(182,79): error TS2304: Cannot find name 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(182,79): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(183,20): error TS2304: Cannot find name 'GetIndentSizeFromText'. -tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(186,67): error TS2304: Cannot find name 'Services'. +tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(186,67): error TS2503: Cannot find namespace 'Services'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(207,50): error TS2304: Cannot find name 'TokenSpan'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(207,67): error TS2304: Cannot find name 'ParseNode'. tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(207,79): error TS2304: Cannot find name 'IndentationInfo'. @@ -165,7 +165,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): constructor( public logger: TypeScript.ILogger, ~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScript'. +!!! error TS2503: Cannot find namespace 'TypeScript'. public tree: ParseTree, ~~~~~~~~~ !!! error TS2304: Cannot find name 'ParseTree'. @@ -175,7 +175,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): public languageHostIndentation: string, public editorOptions: Services.EditorOptions, ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. public firstToken: TokenSpan, ~~~~~~~~~ !!! error TS2304: Cannot find name 'TokenSpan'. @@ -370,7 +370,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): static GetIndentSizeFromIndentText(indentText: string, editorOptions: Services.EditorOptions): number { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. return GetIndentSizeFromText(indentText, editorOptions, /*includeNonIndentChars:*/ false); ~~~~~~~~~~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'GetIndentSizeFromText'. @@ -378,7 +378,7 @@ tests/cases/conformance/parser/ecmascript5/RealWorld/parserindenter.ts(736,38): static GetIndentSizeFromText(text: string, editorOptions: Services.EditorOptions, includeNonIndentChars: boolean): number { ~~~~~~~~ -!!! error TS2304: Cannot find name 'Services'. +!!! error TS2503: Cannot find namespace 'Services'. var indentSize = 0; for (var i = 0; i < text.length; i++) { diff --git a/tests/baselines/reference/parservoidInQualifiedName2.errors.txt b/tests/baselines/reference/parservoidInQualifiedName2.errors.txt index ad96679f0fd..7ca94a8989a 100644 --- a/tests/baselines/reference/parservoidInQualifiedName2.errors.txt +++ b/tests/baselines/reference/parservoidInQualifiedName2.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/parser/ecmascript5/parservoidInQualifiedName2.ts(1,9): error TS2304: Cannot find name 'x'. +tests/cases/conformance/parser/ecmascript5/parservoidInQualifiedName2.ts(1,9): error TS2503: Cannot find namespace 'x'. tests/cases/conformance/parser/ecmascript5/parservoidInQualifiedName2.ts(1,11): error TS1003: Identifier expected. tests/cases/conformance/parser/ecmascript5/parservoidInQualifiedName2.ts(1,15): error TS1109: Expression expected. @@ -6,7 +6,7 @@ tests/cases/conformance/parser/ecmascript5/parservoidInQualifiedName2.ts(1,15): ==== tests/cases/conformance/parser/ecmascript5/parservoidInQualifiedName2.ts (3 errors) ==== var v : x.void; ~ -!!! error TS2304: Cannot find name 'x'. +!!! error TS2503: Cannot find namespace 'x'. ~~~~ !!! error TS1003: Identifier expected. ~ diff --git a/tests/baselines/reference/primaryExpressionMods.errors.txt b/tests/baselines/reference/primaryExpressionMods.errors.txt index 8de3d60c27d..197970591eb 100644 --- a/tests/baselines/reference/primaryExpressionMods.errors.txt +++ b/tests/baselines/reference/primaryExpressionMods.errors.txt @@ -1,5 +1,5 @@ tests/cases/compiler/primaryExpressionMods.ts(7,8): error TS2304: Cannot find name 'M'. -tests/cases/compiler/primaryExpressionMods.ts(11,8): error TS2304: Cannot find name 'm'. +tests/cases/compiler/primaryExpressionMods.ts(11,8): error TS2503: Cannot find namespace 'm'. ==== tests/cases/compiler/primaryExpressionMods.ts (2 errors) ==== @@ -17,5 +17,5 @@ tests/cases/compiler/primaryExpressionMods.ts(11,8): error TS2304: Cannot find n var x2 = m.a; // Same as M.a var q: m.P; // Error ~ -!!! error TS2304: Cannot find name 'm'. +!!! error TS2503: Cannot find namespace 'm'. \ No newline at end of file diff --git a/tests/baselines/reference/scannerImportDeclaration1.errors.txt b/tests/baselines/reference/scannerImportDeclaration1.errors.txt index 243670c6854..d8378248d51 100644 --- a/tests/baselines/reference/scannerImportDeclaration1.errors.txt +++ b/tests/baselines/reference/scannerImportDeclaration1.errors.txt @@ -1,7 +1,7 @@ -tests/cases/conformance/scanner/ecmascript5/scannerImportDeclaration1.ts(1,21): error TS2304: Cannot find name 'TypeScriptServices'. +tests/cases/conformance/scanner/ecmascript5/scannerImportDeclaration1.ts(1,21): error TS2503: Cannot find namespace 'TypeScriptServices'. ==== tests/cases/conformance/scanner/ecmascript5/scannerImportDeclaration1.ts (1 errors) ==== import TypeScript = TypeScriptServices.TypeScript; ~~~~~~~~~~~~~~~~~~ -!!! error TS2304: Cannot find name 'TypeScriptServices'. \ No newline at end of file +!!! error TS2503: Cannot find namespace 'TypeScriptServices'. \ No newline at end of file diff --git a/tests/baselines/reference/strictModeReservedWord.errors.txt b/tests/baselines/reference/strictModeReservedWord.errors.txt index 9e76e36551d..9b7c0e03d0c 100644 --- a/tests/baselines/reference/strictModeReservedWord.errors.txt +++ b/tests/baselines/reference/strictModeReservedWord.errors.txt @@ -19,19 +19,19 @@ tests/cases/compiler/strictModeReservedWord.ts(13,28): error TS1212: Identifier tests/cases/compiler/strictModeReservedWord.ts(15,25): error TS9003: 'class' expressions are not currently supported. tests/cases/compiler/strictModeReservedWord.ts(17,9): error TS2300: Duplicate identifier 'b'. tests/cases/compiler/strictModeReservedWord.ts(17,12): error TS1215: Type expected. 'public' is a reserved word in strict mode -tests/cases/compiler/strictModeReservedWord.ts(17,12): error TS2304: Cannot find name 'public'. +tests/cases/compiler/strictModeReservedWord.ts(17,12): error TS2503: Cannot find namespace 'public'. tests/cases/compiler/strictModeReservedWord.ts(19,21): error TS1215: Type expected. 'private' is a reserved word in strict mode -tests/cases/compiler/strictModeReservedWord.ts(19,21): error TS2304: Cannot find name 'private'. +tests/cases/compiler/strictModeReservedWord.ts(19,21): error TS2503: Cannot find namespace 'private'. tests/cases/compiler/strictModeReservedWord.ts(20,22): error TS1215: Type expected. 'private' is a reserved word in strict mode -tests/cases/compiler/strictModeReservedWord.ts(20,22): error TS2304: Cannot find name 'private'. +tests/cases/compiler/strictModeReservedWord.ts(20,22): error TS2503: Cannot find namespace 'private'. tests/cases/compiler/strictModeReservedWord.ts(20,30): error TS1215: Type expected. 'package' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(21,22): error TS1215: Type expected. 'private' is a reserved word in strict mode -tests/cases/compiler/strictModeReservedWord.ts(21,22): error TS2304: Cannot find name 'private'. +tests/cases/compiler/strictModeReservedWord.ts(21,22): error TS2503: Cannot find namespace 'private'. tests/cases/compiler/strictModeReservedWord.ts(21,30): error TS1215: Type expected. 'package' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(21,38): error TS1215: Type expected. 'protected' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(22,9): error TS2300: Duplicate identifier 'b'. tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS1215: Type expected. 'interface' is a reserved word in strict mode -tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS2304: Cannot find name 'interface'. +tests/cases/compiler/strictModeReservedWord.ts(22,12): error TS2503: Cannot find namespace 'interface'. tests/cases/compiler/strictModeReservedWord.ts(22,22): error TS1215: Type expected. 'package' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(22,30): error TS1215: Type expected. 'implements' is a reserved word in strict mode tests/cases/compiler/strictModeReservedWord.ts(23,5): error TS2304: Cannot find name 'ublic'. @@ -100,25 +100,25 @@ tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invok ~~~~~~ !!! error TS1215: Type expected. 'public' is a reserved word in strict mode ~~~~~~ -!!! error TS2304: Cannot find name 'public'. +!!! error TS2503: Cannot find namespace 'public'. function foo(x: private.x) { } ~~~~~~~ !!! error TS1215: Type expected. 'private' is a reserved word in strict mode ~~~~~~~ -!!! error TS2304: Cannot find name 'private'. +!!! error TS2503: Cannot find namespace 'private'. function foo1(x: private.package.x) { } ~~~~~~~ !!! error TS1215: Type expected. 'private' is a reserved word in strict mode ~~~~~~~ -!!! error TS2304: Cannot find name 'private'. +!!! error TS2503: Cannot find namespace 'private'. ~~~~~~~ !!! error TS1215: Type expected. 'package' is a reserved word in strict mode function foo2(x: private.package.protected) { } ~~~~~~~ !!! error TS1215: Type expected. 'private' is a reserved word in strict mode ~~~~~~~ -!!! error TS2304: Cannot find name 'private'. +!!! error TS2503: Cannot find namespace 'private'. ~~~~~~~ !!! error TS1215: Type expected. 'package' is a reserved word in strict mode ~~~~~~~~~ @@ -129,7 +129,7 @@ tests/cases/compiler/strictModeReservedWord.ts(24,5): error TS2349: Cannot invok ~~~~~~~~~ !!! error TS1215: Type expected. 'interface' is a reserved word in strict mode ~~~~~~~~~ -!!! error TS2304: Cannot find name 'interface'. +!!! error TS2503: Cannot find namespace 'interface'. ~~~~~~~ !!! error TS1215: Type expected. 'package' is a reserved word in strict mode ~~~~~~~~~~ diff --git a/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt b/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt index b7876b1b849..43222495b9f 100644 --- a/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt +++ b/tests/baselines/reference/strictModeReservedWordInClassDeclaration.errors.txt @@ -15,13 +15,13 @@ tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(21,9): error TS tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(21,17): error TS1213: Identifier expected. 'private' is a reserved word in strict mode. Class definitions are automatically in strict mode. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(23,20): error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(25,20): error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. -tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(25,20): error TS2304: Cannot find name 'public'. +tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(25,20): error TS2503: Cannot find namespace 'public'. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(26,21): error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. -tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(26,21): error TS2304: Cannot find name 'public'. +tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(26,21): error TS2503: Cannot find namespace 'public'. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(27,17): error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(27,17): error TS2304: Cannot find name 'package'. tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(28,17): error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. -tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(28,17): error TS2304: Cannot find name 'package'. +tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(28,17): error TS2503: Cannot find namespace 'package'. ==== tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts (24 errors) ==== @@ -85,12 +85,12 @@ tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(28,17): error T ~~~~~~ !!! error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. ~~~~~~ -!!! error TS2304: Cannot find name 'public'. +!!! error TS2503: Cannot find namespace 'public'. class F1 implements public.private.implements { } ~~~~~~ !!! error TS1213: Identifier expected. 'public' is a reserved word in strict mode. Class definitions are automatically in strict mode. ~~~~~~ -!!! error TS2304: Cannot find name 'public'. +!!! error TS2503: Cannot find namespace 'public'. class G extends package { } ~~~~~~~ !!! error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. @@ -100,4 +100,4 @@ tests/cases/compiler/strictModeReservedWordInClassDeclaration.ts(28,17): error T ~~~~~~~ !!! error TS1213: Identifier expected. 'package' is a reserved word in strict mode. Class definitions are automatically in strict mode. ~~~~~~~ -!!! error TS2304: Cannot find name 'package'. \ No newline at end of file +!!! error TS2503: Cannot find namespace 'package'. \ No newline at end of file diff --git a/tests/baselines/reference/unknownSymbols2.errors.txt b/tests/baselines/reference/unknownSymbols2.errors.txt index e78b4a14b61..e85d3c2f3bc 100644 --- a/tests/baselines/reference/unknownSymbols2.errors.txt +++ b/tests/baselines/reference/unknownSymbols2.errors.txt @@ -7,7 +7,7 @@ tests/cases/compiler/unknownSymbols2.ts(15,13): error TS2304: Cannot find name ' tests/cases/compiler/unknownSymbols2.ts(16,14): error TS2304: Cannot find name 'qwerty'. tests/cases/compiler/unknownSymbols2.ts(22,19): error TS2304: Cannot find name 'asdf'. tests/cases/compiler/unknownSymbols2.ts(23,32): error TS2304: Cannot find name 'qwerty'. -tests/cases/compiler/unknownSymbols2.ts(29,16): error TS2304: Cannot find name 'asdf'. +tests/cases/compiler/unknownSymbols2.ts(29,16): error TS2503: Cannot find namespace 'asdf'. ==== tests/cases/compiler/unknownSymbols2.ts (10 errors) ==== @@ -59,5 +59,5 @@ tests/cases/compiler/unknownSymbols2.ts(29,16): error TS2304: Cannot find name ' import c = N; import d = asdf; ~~~~ -!!! error TS2304: Cannot find name 'asdf'. +!!! error TS2503: Cannot find namespace 'asdf'. } \ No newline at end of file From ee4a15c60207e2b14f313578bf54994cde187291 Mon Sep 17 00:00:00 2001 From: vvakame Date: Wed, 6 May 2015 22:49:52 +0900 Subject: [PATCH 25/31] PR feedback --- src/compiler/checker.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index ce2d9150319..f3604ab49ba 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -803,12 +803,8 @@ module ts { let symbol: Symbol; if (name.kind === SyntaxKind.Identifier) { - let message: DiagnosticMessage; - if (meaning === SymbolFlags.Namespace) { - message = Diagnostics.Cannot_find_namespace_0; - } else { - message = Diagnostics.Cannot_find_name_0; - } + let message = meaning === SymbolFlags.Namespace ? Diagnostics.Cannot_find_namespace_0 : Diagnostics.Cannot_find_name_0; + symbol = resolveName(name, (name).text, meaning, message, name); if (!symbol) { return undefined; From 61a404d3e5f3236b216c7cc2c87b5319ca414e91 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 6 May 2015 11:26:55 -0700 Subject: [PATCH 26/31] Update LKG --- bin/tsc.js | 136 ++++++++++++++++++--------------- bin/tsserver.js | 142 ++++++++++++++++++++--------------- bin/typescript.js | 153 +++++++++++++++++++++++--------------- bin/typescriptServices.js | 153 +++++++++++++++++++++++--------------- 4 files changed, 345 insertions(+), 239 deletions(-) diff --git a/bin/tsc.js b/bin/tsc.js index 4912544383a..8a47fd26443 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -1277,6 +1277,8 @@ var ts; An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." }, A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." }, A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, + Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1431,7 +1433,6 @@ var ts; Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 7021, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation." }, _0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, @@ -8583,7 +8584,6 @@ var ts; var undefinedType = createIntrinsicType(32 | 262144, "undefined"); var nullType = createIntrinsicType(64 | 262144, "null"); var unknownType = createIntrinsicType(1, "unknown"); - var resolvingType = createIntrinsicType(1, "__resolving__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -8613,6 +8613,8 @@ var ts; var emitExtends = false; var emitDecorate = false; var emitParam = false; + var resolutionTargets = []; + var resolutionResults = []; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -8832,9 +8834,9 @@ var ts; } else if (location.kind === 228 || (location.kind === 206 && location.name.kind === 8)) { - result = getSymbol(getSymbolOfNode(location).exports, "default", meaning & 8914931); + result = getSymbolOfNode(location).exports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (result && (result.flags & meaning) && localSymbol && localSymbol.name === name) { + if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; @@ -9163,7 +9165,8 @@ var ts; } var symbol; if (name.kind === 65) { - symbol = resolveName(name, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, name); + var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(name, name.text, meaning, message, name); if (!symbol) { return undefined; } @@ -10134,6 +10137,26 @@ var ts; }); } } + function pushTypeResolution(target) { + var i = 0; + var count = resolutionTargets.length; + while (i < count && resolutionTargets[i] !== target) { + i++; + } + if (i < count) { + do { + resolutionResults[i++] = false; + } while (i < count); + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + return true; + } + function popTypeResolution() { + resolutionTargets.pop(); + return resolutionResults.pop(); + } function getRootDeclaration(node) { while (node.kind === 153) { node = node.parent.parent; @@ -10311,20 +10334,23 @@ var ts; if (declaration.kind === 215) { return links.type = checkExpression(declaration.expression); } - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var diagnostic = symbol.valueDeclaration.type ? - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation : - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer; - error(symbol.valueDeclaration, diagnostic, symbolToString(symbol)); + if (!popTypeResolution()) { + if (symbol.valueDeclaration.type) { + type = unknownType; + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + else { + type = anyType; + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + } } + links.type = type; } return links.type; } @@ -10345,13 +10371,10 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - checkAndStoreTypeOfAccessors(symbol, links); - return links.type; - } - function checkAndStoreTypeOfAccessors(symbol, links) { - links = links || getSymbolLinks(symbol); if (!links.type) { - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var getter = ts.getDeclarationOfKind(symbol, 137); var setter = ts.getDeclarationOfKind(symbol, 138); var type; @@ -10376,17 +10399,16 @@ var ts; } } } - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 137); - error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 137); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } } + links.type = type; } + return links.type; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -10548,17 +10570,16 @@ var ts; function getDeclaredTypeOfTypeAlias(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - links.declaredType = resolvingType; + if (!pushTypeResolution(links)) { + return unknownType; + } var declaration = ts.getDeclarationOfKind(symbol, 204); var type = getTypeFromTypeNode(declaration.type); - if (links.declaredType === resolvingType) { - links.declaredType = type; + if (!popTypeResolution()) { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } - } - else if (links.declaredType === resolvingType) { - links.declaredType = unknownType; - var declaration = ts.getDeclarationOfKind(symbol, 204); - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + links.declaredType = type; } return links.declaredType; } @@ -11097,7 +11118,9 @@ var ts; } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { - signature.resolvedReturnType = resolvingType; + if (!pushTypeResolution(signature)) { + return unknownType; + } var type; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); @@ -11108,21 +11131,19 @@ var ts; else { type = getReturnTypeFromBody(signature.declaration); } - if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = type; - } - } - else if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = anyType; - if (compilerOptions.noImplicitAny) { - var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); - } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var declaration = signature.declaration; + if (declaration.name) { + error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + signature.resolvedReturnType = type; } return signature.resolvedReturnType; } @@ -14372,10 +14393,9 @@ var ts; if (isContextSensitive(node)) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } - if (!node.type) { - signature.resolvedReturnType = resolvingType; + if (!node.type && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, contextualMapper); - if (signature.resolvedReturnType === resolvingType) { + if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } } @@ -15156,7 +15176,7 @@ var ts; } } } - checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); + getTypeOfAccessors(getSymbolOfNode(node)); } checkFunctionLikeDeclaration(node); } diff --git a/bin/tsserver.js b/bin/tsserver.js index e492912a282..7538e43029a 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -1277,6 +1277,8 @@ var ts; An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." }, A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." }, A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, + Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -1431,7 +1433,6 @@ var ts; Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 7021, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation." }, _0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, @@ -8967,7 +8968,6 @@ var ts; var undefinedType = createIntrinsicType(32 | 262144, "undefined"); var nullType = createIntrinsicType(64 | 262144, "null"); var unknownType = createIntrinsicType(1, "unknown"); - var resolvingType = createIntrinsicType(1, "__resolving__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -8997,6 +8997,8 @@ var ts; var emitExtends = false; var emitDecorate = false; var emitParam = false; + var resolutionTargets = []; + var resolutionResults = []; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -9216,9 +9218,9 @@ var ts; } else if (location.kind === 228 || (location.kind === 206 && location.name.kind === 8)) { - result = getSymbol(getSymbolOfNode(location).exports, "default", meaning & 8914931); + result = getSymbolOfNode(location).exports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (result && (result.flags & meaning) && localSymbol && localSymbol.name === name) { + if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; @@ -9547,7 +9549,8 @@ var ts; } var symbol; if (name.kind === 65) { - symbol = resolveName(name, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, name); + var message = meaning === 1536 ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(name, name.text, meaning, message, name); if (!symbol) { return undefined; } @@ -10518,6 +10521,26 @@ var ts; }); } } + function pushTypeResolution(target) { + var i = 0; + var count = resolutionTargets.length; + while (i < count && resolutionTargets[i] !== target) { + i++; + } + if (i < count) { + do { + resolutionResults[i++] = false; + } while (i < count); + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + return true; + } + function popTypeResolution() { + resolutionTargets.pop(); + return resolutionResults.pop(); + } function getRootDeclaration(node) { while (node.kind === 153) { node = node.parent.parent; @@ -10695,20 +10718,23 @@ var ts; if (declaration.kind === 215) { return links.type = checkExpression(declaration.expression); } - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var diagnostic = symbol.valueDeclaration.type ? - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation : - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer; - error(symbol.valueDeclaration, diagnostic, symbolToString(symbol)); + if (!popTypeResolution()) { + if (symbol.valueDeclaration.type) { + type = unknownType; + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + else { + type = anyType; + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + } } + links.type = type; } return links.type; } @@ -10729,13 +10755,10 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - checkAndStoreTypeOfAccessors(symbol, links); - return links.type; - } - function checkAndStoreTypeOfAccessors(symbol, links) { - links = links || getSymbolLinks(symbol); if (!links.type) { - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var getter = ts.getDeclarationOfKind(symbol, 137); var setter = ts.getDeclarationOfKind(symbol, 138); var type; @@ -10760,17 +10783,16 @@ var ts; } } } - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 137); - error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 137); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } } + links.type = type; } + return links.type; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -10932,17 +10954,16 @@ var ts; function getDeclaredTypeOfTypeAlias(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - links.declaredType = resolvingType; + if (!pushTypeResolution(links)) { + return unknownType; + } var declaration = ts.getDeclarationOfKind(symbol, 204); var type = getTypeFromTypeNode(declaration.type); - if (links.declaredType === resolvingType) { - links.declaredType = type; + if (!popTypeResolution()) { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } - } - else if (links.declaredType === resolvingType) { - links.declaredType = unknownType; - var declaration = ts.getDeclarationOfKind(symbol, 204); - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + links.declaredType = type; } return links.declaredType; } @@ -11481,7 +11502,9 @@ var ts; } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { - signature.resolvedReturnType = resolvingType; + if (!pushTypeResolution(signature)) { + return unknownType; + } var type; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); @@ -11492,21 +11515,19 @@ var ts; else { type = getReturnTypeFromBody(signature.declaration); } - if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = type; - } - } - else if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = anyType; - if (compilerOptions.noImplicitAny) { - var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); - } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var declaration = signature.declaration; + if (declaration.name) { + error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + signature.resolvedReturnType = type; } return signature.resolvedReturnType; } @@ -14756,10 +14777,9 @@ var ts; if (isContextSensitive(node)) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } - if (!node.type) { - signature.resolvedReturnType = resolvingType; + if (!node.type && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, contextualMapper); - if (signature.resolvedReturnType === resolvingType) { + if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } } @@ -15540,7 +15560,7 @@ var ts; } } } - checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); + getTypeOfAccessors(getSymbolOfNode(node)); } checkFunctionLikeDeclaration(node); } @@ -36854,11 +36874,11 @@ var ts; configFilename = ts.normalizePath(configFilename); var dirPath = ts.getDirectoryPath(configFilename); var rawConfig = ts.readConfigFile(configFilename); - if (!rawConfig) { - return { errorMsg: "tsconfig syntax error" }; + if (rawConfig.error) { + return rawConfig.error; } else { - var parsedCommandLine = ts.parseConfigFile(rawConfig, ts.sys, dirPath); + var parsedCommandLine = ts.parseConfigFile(rawConfig.config, ts.sys, dirPath); if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) { return { errorMsg: "tsconfig option errors" }; } diff --git a/bin/typescript.js b/bin/typescript.js index ad70519a3fa..9cee921f435 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -2020,6 +2020,8 @@ var ts; An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." }, A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." }, A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, + Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2174,7 +2176,6 @@ var ts; Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 7021, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation." }, _0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, @@ -10804,7 +10805,6 @@ var ts; var undefinedType = createIntrinsicType(32 /* Undefined */ | 262144 /* ContainsUndefinedOrNull */, "undefined"); var nullType = createIntrinsicType(64 /* Null */ | 262144 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var resolvingType = createIntrinsicType(1 /* Any */, "__resolving__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -10834,6 +10834,8 @@ var ts; var emitExtends = false; var emitDecorate = false; var emitParam = false; + var resolutionTargets = []; + var resolutionResults = []; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -11063,9 +11065,9 @@ var ts; } else if (location.kind === 228 /* SourceFile */ || (location.kind === 206 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { - result = getSymbol(getSymbolOfNode(location).exports, "default", meaning & 8914931 /* ModuleMember */); + result = getSymbolOfNode(location).exports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (result && (result.flags & meaning) && localSymbol && localSymbol.name === name) { + if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; @@ -11481,7 +11483,8 @@ var ts; } var symbol; if (name.kind === 65 /* Identifier */) { - symbol = resolveName(name, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, name); + var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(name, name.text, meaning, message, name); if (!symbol) { return undefined; } @@ -12573,6 +12576,35 @@ var ts; }); } } + // Push an entry on the type resolution stack. If an entry with the given target is not already on the stack, + // a new entry with that target and an associated result value of true is pushed on the stack, and the value + // true is returned. Otherwise, a circularity has occurred and the result values of the existing entry and + // all entries pushed after it are changed to false, and the value false is returned. The target object provides + // a unique identity for a particular type resolution result: Symbol instances are used to track resolution of + // SymbolLinks.type, SymbolLinks instances are used to track resolution of SymbolLinks.declaredType, and + // Signature instances are used to track resolution of Signature.resolvedReturnType. + function pushTypeResolution(target) { + var i = 0; + var count = resolutionTargets.length; + while (i < count && resolutionTargets[i] !== target) { + i++; + } + if (i < count) { + do { + resolutionResults[i++] = false; + } while (i < count); + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + return true; + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + return resolutionResults.pop(); + } function getRootDeclaration(node) { while (node.kind === 153 /* BindingElement */) { node = node.parent.parent; @@ -12815,20 +12847,25 @@ var ts; return links.type = checkExpression(declaration.expression); } // Handle variable, parameter or property - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var diagnostic = symbol.valueDeclaration.type ? - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation : - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer; - error(symbol.valueDeclaration, diagnostic, symbolToString(symbol)); + if (!popTypeResolution()) { + if (symbol.valueDeclaration.type) { + // Variable has type annotation that circularly references the variable itself + type = unknownType; + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + else { + // Variable has initializer that circularly references the variable itself + type = anyType; + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + } } + links.type = type; } return links.type; } @@ -12849,13 +12886,10 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - checkAndStoreTypeOfAccessors(symbol, links); - return links.type; - } - function checkAndStoreTypeOfAccessors(symbol, links) { - links = links || getSymbolLinks(symbol); if (!links.type) { - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var getter = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 138 /* SetAccessor */); var type; @@ -12883,17 +12917,16 @@ var ts; } } } - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); - error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } } + links.type = type; } + return links.type; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -13058,17 +13091,18 @@ var ts; function getDeclaredTypeOfTypeAlias(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - links.declaredType = resolvingType; + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(links)) { + return unknownType; + } var declaration = ts.getDeclarationOfKind(symbol, 204 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); - if (links.declaredType === resolvingType) { - links.declaredType = type; + if (!popTypeResolution()) { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } - } - else if (links.declaredType === resolvingType) { - links.declaredType = unknownType; - var declaration = ts.getDeclarationOfKind(symbol, 204 /* TypeAliasDeclaration */); - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + links.declaredType = type; } return links.declaredType; } @@ -13634,7 +13668,9 @@ var ts; } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { - signature.resolvedReturnType = resolvingType; + if (!pushTypeResolution(signature)) { + return unknownType; + } var type; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); @@ -13645,21 +13681,19 @@ var ts; else { type = getReturnTypeFromBody(signature.declaration); } - if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = type; - } - } - else if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = anyType; - if (compilerOptions.noImplicitAny) { - var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); - } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var declaration = signature.declaration; + if (declaration.name) { + error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + signature.resolvedReturnType = type; } return signature.resolvedReturnType; } @@ -17486,10 +17520,9 @@ var ts; if (isContextSensitive(node)) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } - if (!node.type) { - signature.resolvedReturnType = resolvingType; + if (!node.type && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, contextualMapper); - if (signature.resolvedReturnType === resolvingType) { + if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } } @@ -18405,7 +18438,7 @@ var ts; } } } - checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); + getTypeOfAccessors(getSymbolOfNode(node)); } checkFunctionLikeDeclaration(node); } @@ -41620,7 +41653,7 @@ var ts; })(ts || (ts = {})); // // Copyright (c) Microsoft Corporation. All rights reserved. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -42190,7 +42223,7 @@ var ts; return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: [realizeDiagnostics(configFile.errors, '\r\n')] }; }); }; diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index ad70519a3fa..9cee921f435 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -2020,6 +2020,8 @@ var ts; An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2499, category: ts.DiagnosticCategory.Error, key: "An interface can only extend an identifier/qualified-name with optional type arguments." }, A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments: { code: 2500, category: ts.DiagnosticCategory.Error, key: "A class can only implement an identifier/qualified-name with optional type arguments." }, A_rest_element_cannot_contain_a_binding_pattern: { code: 2501, category: ts.DiagnosticCategory.Error, key: "A rest element cannot contain a binding pattern." }, + _0_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 2502, category: ts.DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own type annotation." }, + Cannot_find_namespace_0: { code: 2503, category: ts.DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." }, Import_declaration_0_is_using_private_name_1: { code: 4000, category: ts.DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." }, Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." }, Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: ts.DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." }, @@ -2174,7 +2176,6 @@ var ts; Object_literal_s_property_0_implicitly_has_an_1_type: { code: 7018, category: ts.DiagnosticCategory.Error, key: "Object literal's property '{0}' implicitly has an '{1}' type." }, Rest_parameter_0_implicitly_has_an_any_type: { code: 7019, category: ts.DiagnosticCategory.Error, key: "Rest parameter '{0}' implicitly has an 'any[]' type." }, Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type: { code: 7020, category: ts.DiagnosticCategory.Error, key: "Call signature, which lacks return-type annotation, implicitly has an 'any' return type." }, - _0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation: { code: 7021, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is referenced directly or indirectly in its own type annotation." }, _0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer: { code: 7022, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has type 'any' because it is does not have a type annotation and is referenced directly or indirectly in its own initializer." }, _0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: ts.DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: ts.DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." }, @@ -10804,7 +10805,6 @@ var ts; var undefinedType = createIntrinsicType(32 /* Undefined */ | 262144 /* ContainsUndefinedOrNull */, "undefined"); var nullType = createIntrinsicType(64 /* Null */ | 262144 /* ContainsUndefinedOrNull */, "null"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); - var resolvingType = createIntrinsicType(1 /* Any */, "__resolving__"); var emptyObjectType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); var noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); @@ -10834,6 +10834,8 @@ var ts; var emitExtends = false; var emitDecorate = false; var emitParam = false; + var resolutionTargets = []; + var resolutionResults = []; var mergedSymbols = []; var symbolLinks = []; var nodeLinks = []; @@ -11063,9 +11065,9 @@ var ts; } else if (location.kind === 228 /* SourceFile */ || (location.kind === 206 /* ModuleDeclaration */ && location.name.kind === 8 /* StringLiteral */)) { - result = getSymbol(getSymbolOfNode(location).exports, "default", meaning & 8914931 /* ModuleMember */); + result = getSymbolOfNode(location).exports["default"]; var localSymbol = ts.getLocalSymbolForExportDefault(result); - if (result && (result.flags & meaning) && localSymbol && localSymbol.name === name) { + if (result && localSymbol && (result.flags & meaning) && localSymbol.name === name) { break loop; } result = undefined; @@ -11481,7 +11483,8 @@ var ts; } var symbol; if (name.kind === 65 /* Identifier */) { - symbol = resolveName(name, name.text, meaning, ts.Diagnostics.Cannot_find_name_0, name); + var message = meaning === 1536 /* Namespace */ ? ts.Diagnostics.Cannot_find_namespace_0 : ts.Diagnostics.Cannot_find_name_0; + symbol = resolveName(name, name.text, meaning, message, name); if (!symbol) { return undefined; } @@ -12573,6 +12576,35 @@ var ts; }); } } + // Push an entry on the type resolution stack. If an entry with the given target is not already on the stack, + // a new entry with that target and an associated result value of true is pushed on the stack, and the value + // true is returned. Otherwise, a circularity has occurred and the result values of the existing entry and + // all entries pushed after it are changed to false, and the value false is returned. The target object provides + // a unique identity for a particular type resolution result: Symbol instances are used to track resolution of + // SymbolLinks.type, SymbolLinks instances are used to track resolution of SymbolLinks.declaredType, and + // Signature instances are used to track resolution of Signature.resolvedReturnType. + function pushTypeResolution(target) { + var i = 0; + var count = resolutionTargets.length; + while (i < count && resolutionTargets[i] !== target) { + i++; + } + if (i < count) { + do { + resolutionResults[i++] = false; + } while (i < count); + return false; + } + resolutionTargets.push(target); + resolutionResults.push(true); + return true; + } + // Pop an entry from the type resolution stack and return its associated result value. The result value will + // be true if no circularities were detected, or false if a circularity was found. + function popTypeResolution() { + resolutionTargets.pop(); + return resolutionResults.pop(); + } function getRootDeclaration(node) { while (node.kind === 153 /* BindingElement */) { node = node.parent.parent; @@ -12815,20 +12847,25 @@ var ts; return links.type = checkExpression(declaration.expression); } // Handle variable, parameter or property - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var type = getWidenedTypeForVariableLikeDeclaration(declaration, true); - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var diagnostic = symbol.valueDeclaration.type ? - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_referenced_directly_or_indirectly_in_its_own_type_annotation : - ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer; - error(symbol.valueDeclaration, diagnostic, symbolToString(symbol)); + if (!popTypeResolution()) { + if (symbol.valueDeclaration.type) { + // Variable has type annotation that circularly references the variable itself + type = unknownType; + error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol)); + } + else { + // Variable has initializer that circularly references the variable itself + type = anyType; + if (compilerOptions.noImplicitAny) { + error(symbol.valueDeclaration, ts.Diagnostics._0_implicitly_has_type_any_because_it_is_does_not_have_a_type_annotation_and_is_referenced_directly_or_indirectly_in_its_own_initializer, symbolToString(symbol)); + } + } } + links.type = type; } return links.type; } @@ -12849,13 +12886,10 @@ var ts; } function getTypeOfAccessors(symbol) { var links = getSymbolLinks(symbol); - checkAndStoreTypeOfAccessors(symbol, links); - return links.type; - } - function checkAndStoreTypeOfAccessors(symbol, links) { - links = links || getSymbolLinks(symbol); if (!links.type) { - links.type = resolvingType; + if (!pushTypeResolution(symbol)) { + return unknownType; + } var getter = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); var setter = ts.getDeclarationOfKind(symbol, 138 /* SetAccessor */); var type; @@ -12883,17 +12917,16 @@ var ts; } } } - if (links.type === resolvingType) { - links.type = type; - } - } - else if (links.type === resolvingType) { - links.type = anyType; - if (compilerOptions.noImplicitAny) { - var getter = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); - error(getter, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var getter_1 = ts.getDeclarationOfKind(symbol, 137 /* GetAccessor */); + error(getter_1, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, symbolToString(symbol)); + } } + links.type = type; } + return links.type; } function getTypeOfFuncClassEnumModule(symbol) { var links = getSymbolLinks(symbol); @@ -13058,17 +13091,18 @@ var ts; function getDeclaredTypeOfTypeAlias(symbol) { var links = getSymbolLinks(symbol); if (!links.declaredType) { - links.declaredType = resolvingType; + // Note that we use the links object as the target here because the symbol object is used as the unique + // identity for resolution of the 'type' property in SymbolLinks. + if (!pushTypeResolution(links)) { + return unknownType; + } var declaration = ts.getDeclarationOfKind(symbol, 204 /* TypeAliasDeclaration */); var type = getTypeFromTypeNode(declaration.type); - if (links.declaredType === resolvingType) { - links.declaredType = type; + if (!popTypeResolution()) { + type = unknownType; + error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); } - } - else if (links.declaredType === resolvingType) { - links.declaredType = unknownType; - var declaration = ts.getDeclarationOfKind(symbol, 204 /* TypeAliasDeclaration */); - error(declaration.name, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol)); + links.declaredType = type; } return links.declaredType; } @@ -13634,7 +13668,9 @@ var ts; } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { - signature.resolvedReturnType = resolvingType; + if (!pushTypeResolution(signature)) { + return unknownType; + } var type; if (signature.target) { type = instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper); @@ -13645,21 +13681,19 @@ var ts; else { type = getReturnTypeFromBody(signature.declaration); } - if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = type; - } - } - else if (signature.resolvedReturnType === resolvingType) { - signature.resolvedReturnType = anyType; - if (compilerOptions.noImplicitAny) { - var declaration = signature.declaration; - if (declaration.name) { - error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); - } - else { - error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + if (!popTypeResolution()) { + type = anyType; + if (compilerOptions.noImplicitAny) { + var declaration = signature.declaration; + if (declaration.name) { + error(declaration.name, ts.Diagnostics._0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions, ts.declarationNameToString(declaration.name)); + } + else { + error(declaration, ts.Diagnostics.Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions); + } } } + signature.resolvedReturnType = type; } return signature.resolvedReturnType; } @@ -17486,10 +17520,9 @@ var ts; if (isContextSensitive(node)) { assignContextualParameterTypes(signature, contextualSignature, contextualMapper || identityMapper); } - if (!node.type) { - signature.resolvedReturnType = resolvingType; + if (!node.type && !signature.resolvedReturnType) { var returnType = getReturnTypeFromBody(node, contextualMapper); - if (signature.resolvedReturnType === resolvingType) { + if (!signature.resolvedReturnType) { signature.resolvedReturnType = returnType; } } @@ -18405,7 +18438,7 @@ var ts; } } } - checkAndStoreTypeOfAccessors(getSymbolOfNode(node)); + getTypeOfAccessors(getSymbolOfNode(node)); } checkFunctionLikeDeclaration(node); } @@ -41620,7 +41653,7 @@ var ts; })(ts || (ts = {})); // // Copyright (c) Microsoft Corporation. All rights reserved. -// +// // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at @@ -42190,7 +42223,7 @@ var ts; return { options: configFile.options, files: configFile.fileNames, - errors: realizeDiagnostics(configFile.errors, '\r\n') + errors: [realizeDiagnostics(configFile.errors, '\r\n')] }; }); }; From 0a28a3ec80c9b5e4f5bb5590598ba86ade2d1b02 Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Wed, 6 May 2015 13:05:12 -0700 Subject: [PATCH 27/31] Remove getUnionTypeOfSubtypeConstituents --- src/compiler/checker.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index a3ce22bbed1..4c5712299da 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3634,10 +3634,6 @@ module ts { return type; } - function getUnionTypeOfSubtypeConstituents(source: UnionType, target: Type): Type { - return getUnionType(filter(source.types, t => isTypeSubtypeOf(t, target))); - } - function getReducedTypeOfUnionType(type: UnionType): Type { // If union type was created without subtype reduction, perform the deferred reduction now if (!type.reducedType) { @@ -5399,7 +5395,7 @@ module ts { } // If the current type is a union type, remove all constituents that aren't subtypes of the target. if (type.flags & TypeFlags.Union) { - return getUnionTypeOfSubtypeConstituents(type, targetType); + return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, targetType))); } } } @@ -5416,7 +5412,7 @@ module ts { let instanceType = getUnionType(map(constructSignatures, signature => getReturnTypeOfSignature(getErasedSignature(signature)))); // Pickup type from union types if (type.flags & TypeFlags.Union) { - return getUnionTypeOfSubtypeConstituents(type, instanceType); + return getUnionType(filter((type).types, t => isTypeSubtypeOf(t, instanceType))); } return instanceType; } From 498f315256b7e2d041c398ee25bbce08f2d5d1f9 Mon Sep 17 00:00:00 2001 From: Jason Freeman Date: Wed, 6 May 2015 15:53:01 -0700 Subject: [PATCH 28/31] Fix typing for Promises so that a void error callback doesn't mess up inference --- src/lib/es6.d.ts | 2 + .../reference/promiseVoidErrorCallback.js | 43 +++++++++ .../promiseVoidErrorCallback.symbols | 75 ++++++++++++++++ .../reference/promiseVoidErrorCallback.types | 89 +++++++++++++++++++ .../compiler/promiseVoidErrorCallback.ts | 28 ++++++ 5 files changed, 237 insertions(+) create mode 100644 tests/baselines/reference/promiseVoidErrorCallback.js create mode 100644 tests/baselines/reference/promiseVoidErrorCallback.symbols create mode 100644 tests/baselines/reference/promiseVoidErrorCallback.types create mode 100644 tests/cases/compiler/promiseVoidErrorCallback.ts diff --git a/src/lib/es6.d.ts b/src/lib/es6.d.ts index fb0c64f8495..dc082c8f0a6 100644 --- a/src/lib/es6.d.ts +++ b/src/lib/es6.d.ts @@ -3580,6 +3580,7 @@ interface PromiseLike { * @returns A Promise for the completion of which ever callback is executed. */ then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): PromiseLike; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): PromiseLike; } /** @@ -3593,6 +3594,7 @@ interface Promise { * @returns A Promise for the completion of which ever callback is executed. */ then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; + then(onfulfilled?: (value: T) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; /** * Attaches a callback for only the rejection of the Promise. diff --git a/tests/baselines/reference/promiseVoidErrorCallback.js b/tests/baselines/reference/promiseVoidErrorCallback.js new file mode 100644 index 00000000000..a9aa0f1b5d0 --- /dev/null +++ b/tests/baselines/reference/promiseVoidErrorCallback.js @@ -0,0 +1,43 @@ +//// [promiseVoidErrorCallback.ts] +interface T1 { + __t1: string; +} + +interface T2 { + __t2: string; +} + +interface T3 { + __t3: string; +} + +function f1(): Promise { + return Promise.resolve({ __t1: "foo_t1" }); +} + +function f2(x: T1): T2 { + return { __t2: x.__t1 + ":foo_21" }; +} + +var x3 = f1() + .then(f2, (e: Error) => { + throw e; +}) + .then((x: T2) => { + return { __t3: x.__t2 + "bar" }; +}); + +//// [promiseVoidErrorCallback.js] +function f1() { + return Promise.resolve({ __t1: "foo_t1" }); +} +function f2(x) { + return { __t2: x.__t1 + ":foo_21" }; +} +var x3 = f1() + .then(f2, (e) => { + throw e; +}) + .then((x) => { + return { __t3: x.__t2 + "bar" }; +}); diff --git a/tests/baselines/reference/promiseVoidErrorCallback.symbols b/tests/baselines/reference/promiseVoidErrorCallback.symbols new file mode 100644 index 00000000000..78faacdb1f1 --- /dev/null +++ b/tests/baselines/reference/promiseVoidErrorCallback.symbols @@ -0,0 +1,75 @@ +=== tests/cases/compiler/promiseVoidErrorCallback.ts === +interface T1 { +>T1 : Symbol(T1, Decl(promiseVoidErrorCallback.ts, 0, 0)) + + __t1: string; +>__t1 : Symbol(__t1, Decl(promiseVoidErrorCallback.ts, 0, 14)) +} + +interface T2 { +>T2 : Symbol(T2, Decl(promiseVoidErrorCallback.ts, 2, 1)) + + __t2: string; +>__t2 : Symbol(__t2, Decl(promiseVoidErrorCallback.ts, 4, 14)) +} + +interface T3 { +>T3 : Symbol(T3, Decl(promiseVoidErrorCallback.ts, 6, 1)) + + __t3: string; +>__t3 : Symbol(__t3, Decl(promiseVoidErrorCallback.ts, 8, 14)) +} + +function f1(): Promise { +>f1 : Symbol(f1, Decl(promiseVoidErrorCallback.ts, 10, 1)) +>Promise : Symbol(Promise, Decl(lib.d.ts, 4769, 1), Decl(lib.d.ts, 4854, 11)) +>T1 : Symbol(T1, Decl(promiseVoidErrorCallback.ts, 0, 0)) + + return Promise.resolve({ __t1: "foo_t1" }); +>Promise.resolve : Symbol(PromiseConstructor.resolve, Decl(lib.d.ts, 4836, 39), Decl(lib.d.ts, 4843, 54)) +>Promise : Symbol(Promise, Decl(lib.d.ts, 4769, 1), Decl(lib.d.ts, 4854, 11)) +>resolve : Symbol(PromiseConstructor.resolve, Decl(lib.d.ts, 4836, 39), Decl(lib.d.ts, 4843, 54)) +>__t1 : Symbol(__t1, Decl(promiseVoidErrorCallback.ts, 13, 28)) +} + +function f2(x: T1): T2 { +>f2 : Symbol(f2, Decl(promiseVoidErrorCallback.ts, 14, 1)) +>x : Symbol(x, Decl(promiseVoidErrorCallback.ts, 16, 12)) +>T1 : Symbol(T1, Decl(promiseVoidErrorCallback.ts, 0, 0)) +>T2 : Symbol(T2, Decl(promiseVoidErrorCallback.ts, 2, 1)) + + return { __t2: x.__t1 + ":foo_21" }; +>__t2 : Symbol(__t2, Decl(promiseVoidErrorCallback.ts, 17, 12)) +>x.__t1 : Symbol(T1.__t1, Decl(promiseVoidErrorCallback.ts, 0, 14)) +>x : Symbol(x, Decl(promiseVoidErrorCallback.ts, 16, 12)) +>__t1 : Symbol(T1.__t1, Decl(promiseVoidErrorCallback.ts, 0, 14)) +} + +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, 4774, 22), Decl(lib.d.ts, 4781, 158)) +>f1() .then : Symbol(Promise.then, Decl(lib.d.ts, 4774, 22), Decl(lib.d.ts, 4781, 158)) +>f1 : Symbol(f1, Decl(promiseVoidErrorCallback.ts, 10, 1)) + + .then(f2, (e: Error) => { +>then : Symbol(Promise.then, Decl(lib.d.ts, 4774, 22), Decl(lib.d.ts, 4781, 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)) + + throw e; +>e : Symbol(e, Decl(promiseVoidErrorCallback.ts, 21, 15)) + +}) + .then((x: T2) => { +>then : Symbol(Promise.then, Decl(lib.d.ts, 4774, 22), Decl(lib.d.ts, 4781, 158)) +>x : Symbol(x, Decl(promiseVoidErrorCallback.ts, 24, 11)) +>T2 : Symbol(T2, Decl(promiseVoidErrorCallback.ts, 2, 1)) + + return { __t3: x.__t2 + "bar" }; +>__t3 : Symbol(__t3, Decl(promiseVoidErrorCallback.ts, 25, 12)) +>x.__t2 : Symbol(T2.__t2, Decl(promiseVoidErrorCallback.ts, 4, 14)) +>x : Symbol(x, Decl(promiseVoidErrorCallback.ts, 24, 11)) +>__t2 : Symbol(T2.__t2, Decl(promiseVoidErrorCallback.ts, 4, 14)) + +}); diff --git a/tests/baselines/reference/promiseVoidErrorCallback.types b/tests/baselines/reference/promiseVoidErrorCallback.types new file mode 100644 index 00000000000..82b248f64bd --- /dev/null +++ b/tests/baselines/reference/promiseVoidErrorCallback.types @@ -0,0 +1,89 @@ +=== tests/cases/compiler/promiseVoidErrorCallback.ts === +interface T1 { +>T1 : T1 + + __t1: string; +>__t1 : string +} + +interface T2 { +>T2 : T2 + + __t2: string; +>__t2 : string +} + +interface T3 { +>T3 : T3 + + __t3: string; +>__t3 : string +} + +function f1(): Promise { +>f1 : () => Promise +>Promise : Promise +>T1 : T1 + + return Promise.resolve({ __t1: "foo_t1" }); +>Promise.resolve({ __t1: "foo_t1" }) : Promise<{ __t1: string; }> +>Promise.resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>Promise : PromiseConstructor +>resolve : { (value: T | PromiseLike): Promise; (): Promise; } +>{ __t1: "foo_t1" } : { __t1: string; } +>__t1 : string +>"foo_t1" : string +} + +function f2(x: T1): T2 { +>f2 : (x: T1) => T2 +>x : T1 +>T1 : T1 +>T2 : T2 + + return { __t2: x.__t1 + ":foo_21" }; +>{ __t2: x.__t1 + ":foo_21" } : { __t2: string; } +>__t2 : string +>x.__t1 + ":foo_21" : string +>x.__t1 : string +>x : T1 +>__t1 : string +>":foo_21" : string +} + +var x3 = f1() +>x3 : Promise<{ __t3: string; }> +>f1() .then(f2, (e: Error) => { throw e;}) .then((x: T2) => { return { __t3: x.__t2 + "bar" };}) : Promise<{ __t3: string; }> +>f1() .then(f2, (e: Error) => { throw e;}) .then : { (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>f1() .then(f2, (e: Error) => { throw e;}) : Promise +>f1() .then : { (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>f1() : Promise +>f1 : () => Promise + + .then(f2, (e: Error) => { +>then : { (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T1) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>f2 : (x: T1) => T2 +>(e: Error) => { throw e;} : (e: Error) => void +>e : Error +>Error : Error + + throw e; +>e : Error + +}) + .then((x: T2) => { +>then : { (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => TResult | PromiseLike): Promise; (onfulfilled?: (value: T2) => TResult | PromiseLike, onrejected?: (reason: any) => void): Promise; } +>(x: T2) => { return { __t3: x.__t2 + "bar" };} : (x: T2) => { __t3: string; } +>x : T2 +>T2 : T2 + + return { __t3: x.__t2 + "bar" }; +>{ __t3: x.__t2 + "bar" } : { __t3: string; } +>__t3 : string +>x.__t2 + "bar" : string +>x.__t2 : string +>x : T2 +>__t2 : string +>"bar" : string + +}); diff --git a/tests/cases/compiler/promiseVoidErrorCallback.ts b/tests/cases/compiler/promiseVoidErrorCallback.ts new file mode 100644 index 00000000000..3169288f79a --- /dev/null +++ b/tests/cases/compiler/promiseVoidErrorCallback.ts @@ -0,0 +1,28 @@ +//@target: ES6 +interface T1 { + __t1: string; +} + +interface T2 { + __t2: string; +} + +interface T3 { + __t3: string; +} + +function f1(): Promise { + return Promise.resolve({ __t1: "foo_t1" }); +} + +function f2(x: T1): T2 { + return { __t2: x.__t1 + ":foo_21" }; +} + +var x3 = f1() + .then(f2, (e: Error) => { + throw e; +}) + .then((x: T2) => { + return { __t3: x.__t2 + "bar" }; +}); \ No newline at end of file From a33bb6bb199a26529e99419cf4d1dc9159c188dc Mon Sep 17 00:00:00 2001 From: Vladimir Matveev Date: Wed, 6 May 2015 16:00:50 -0700 Subject: [PATCH 29/31] use canonical file name when asking the host if file exists --- src/services/services.ts | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/services/services.ts b/src/services/services.ts index 1333f2a13cb..ede6fb8ca7b 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -1632,7 +1632,7 @@ module ts { private fileNameToEntry: Map; private _compilationSettings: CompilerOptions; - constructor(private host: LanguageServiceHost) { + constructor(private host: LanguageServiceHost, private getCanonicalFileName: (fileName: string) => string) { // script id => script index this.fileNameToEntry = {}; @@ -1650,6 +1650,10 @@ module ts { return this._compilationSettings; } + private normalizeFileName(fileName: string): string { + return this.getCanonicalFileName(normalizeSlashes(fileName)); + } + private createEntry(fileName: string) { let entry: HostFileInformation; let scriptSnapshot = this.host.getScriptSnapshot(fileName); @@ -1661,15 +1665,15 @@ module ts { }; } - return this.fileNameToEntry[normalizeSlashes(fileName)] = entry; + return this.fileNameToEntry[this.normalizeFileName(fileName)] = entry; } - public getEntry(fileName: string): HostFileInformation { - return lookUp(this.fileNameToEntry, normalizeSlashes(fileName)); + private getEntry(fileName: string): HostFileInformation { + return lookUp(this.fileNameToEntry, this.normalizeFileName(fileName)); } - public contains(fileName: string): boolean { - return hasProperty(this.fileNameToEntry, normalizeSlashes(fileName)); + private contains(fileName: string): boolean { + return hasProperty(this.fileNameToEntry, this.normalizeFileName(fileName)); } public getOrCreateEntry(fileName: string): HostFileInformation { @@ -1684,8 +1688,10 @@ module ts { let fileNames: string[] = []; forEachKey(this.fileNameToEntry, key => { - if (hasProperty(this.fileNameToEntry, key) && this.fileNameToEntry[key]) - fileNames.push(key); + let entry = this.getEntry(key); + if (entry) { + fileNames.push(entry.hostFileName); + } }); return fileNames; @@ -2387,7 +2393,7 @@ module ts { function synchronizeHostData(): void { // Get a fresh cache of the host information - let hostCache = new HostCache(host); + let hostCache = new HostCache(host, getCanonicalFileName); // If the program is already up-to-date, we can reuse it if (programUpToDate()) { @@ -2408,7 +2414,7 @@ module ts { let newProgram = createProgram(hostCache.getRootFileNames(), newSettings, { getSourceFile: getOrCreateSourceFile, getCancellationToken: () => cancellationToken, - getCanonicalFileName: (fileName) => useCaseSensitivefileNames ? fileName : fileName.toLowerCase(), + getCanonicalFileName, useCaseSensitiveFileNames: () => useCaseSensitivefileNames, getNewLine: () => host.getNewLine ? host.getNewLine() : "\r\n", getDefaultLibFileName: (options) => host.getDefaultLibFileName(options), From 7acc48875780ba4e59f28434db95943adb2875ce Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 6 May 2015 17:23:04 -0700 Subject: [PATCH 30/31] Removed Object.defineProperty for function name --- src/compiler/emitter.ts | 11 ++--------- .../reference/decoratedClassFromExternalModule.js | 1 - 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 5a9a654ce60..6d5146a6801 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -3898,6 +3898,8 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { emitToken(SyntaxKind.CloseBraceToken, node.members.end); scopeEmitEnd(); + // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. + // For a decorated class, we need to assign its name (if it has one). This is because we emit // the class as a class expression to avoid the double-binding of the identifier: // @@ -3907,15 +3909,6 @@ var __param = (this && this.__param) || function (paramIndex, decorator) { // if (thisNodeIsDecorated) { write(";"); - if (node.name) { - writeLine(); - write("Object.defineProperty("); - emitDeclarationName(node); - write(", \"name\", { value: \""); - emitDeclarationName(node); - write("\", configurable: true });"); - writeLine(); - } } // Emit static property assignment. Because classDeclaration is lexically evaluated, diff --git a/tests/baselines/reference/decoratedClassFromExternalModule.js b/tests/baselines/reference/decoratedClassFromExternalModule.js index 36cffbb6677..163a4a094b4 100644 --- a/tests/baselines/reference/decoratedClassFromExternalModule.js +++ b/tests/baselines/reference/decoratedClassFromExternalModule.js @@ -21,7 +21,6 @@ var __decorate = (this && this.__decorate) || function (decorators, target, key, function decorate() { } let Decorated = class { }; -Object.defineProperty(Decorated, "name", { value: "Decorated", configurable: true }); Decorated = __decorate([ decorate ], Decorated); From 6be18f821eb0543de0d8a32f026a504780d4fbd3 Mon Sep 17 00:00:00 2001 From: Ron Buckton Date: Wed, 6 May 2015 17:30:41 -0700 Subject: [PATCH 31/31] Updated LKG --- bin/tsc.js | 38 +++++++++++++++++++-------------- bin/tsserver.js | 38 +++++++++++++++++++-------------- bin/typescript.js | 45 +++++++++++++++++++++++---------------- bin/typescriptServices.js | 45 +++++++++++++++++++++++---------------- 4 files changed, 98 insertions(+), 68 deletions(-) diff --git a/bin/tsc.js b/bin/tsc.js index 8a47fd26443..2bde9314b4d 100644 --- a/bin/tsc.js +++ b/bin/tsc.js @@ -13005,15 +13005,30 @@ var ts; return type; } var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (!prototypeProperty) { - return type; + if (prototypeProperty) { + var targetType = getTypeOfSymbol(prototypeProperty); + if (targetType !== anyType) { + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 16384) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + } + } } - var targetType = getTypeOfSymbol(prototypeProperty); - if (isTypeSubtypeOf(targetType, type)) { - return targetType; + var constructSignatures; + if (rightType.flags & 2048) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + else if (rightType.flags & 32768) { + constructSignatures = getSignaturesOfType(rightType, 1); + } + if (constructSignatures && constructSignatures.length !== 0) { + var instanceType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + if (type.flags & 16384) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, instanceType); })); + } + return instanceType; } return type; } @@ -23260,15 +23275,6 @@ var ts; scopeEmitEnd(); if (thisNodeIsDecorated) { write(";"); - if (node.name) { - writeLine(); - write("Object.defineProperty("); - emitDeclarationName(node); - write(", \"name\", { value: \""); - emitDeclarationName(node); - write("\", configurable: true });"); - writeLine(); - } } if (isClassExpressionWithStaticProperties) { for (var _a = 0; _a < staticProperties.length; _a++) { diff --git a/bin/tsserver.js b/bin/tsserver.js index 7538e43029a..1707ef70411 100644 --- a/bin/tsserver.js +++ b/bin/tsserver.js @@ -13389,15 +13389,30 @@ var ts; return type; } var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (!prototypeProperty) { - return type; + if (prototypeProperty) { + var targetType = getTypeOfSymbol(prototypeProperty); + if (targetType !== anyType) { + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + if (type.flags & 16384) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + } + } } - var targetType = getTypeOfSymbol(prototypeProperty); - if (isTypeSubtypeOf(targetType, type)) { - return targetType; + var constructSignatures; + if (rightType.flags & 2048) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - if (type.flags & 16384) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + else if (rightType.flags & 32768) { + constructSignatures = getSignaturesOfType(rightType, 1); + } + if (constructSignatures && constructSignatures.length !== 0) { + var instanceType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + if (type.flags & 16384) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, instanceType); })); + } + return instanceType; } return type; } @@ -23644,15 +23659,6 @@ var ts; scopeEmitEnd(); if (thisNodeIsDecorated) { write(";"); - if (node.name) { - writeLine(); - write("Object.defineProperty("); - emitDeclarationName(node); - write(", \"name\", { value: \""); - emitDeclarationName(node); - write("\", configurable: true });"); - writeLine(); - } } if (isClassExpressionWithStaticProperties) { for (var _a = 0; _a < staticProperties.length; _a++) { diff --git a/bin/typescript.js b/bin/typescript.js index 9cee921f435..ba375bc4096 100644 --- a/bin/typescript.js +++ b/bin/typescript.js @@ -15732,17 +15732,34 @@ var ts; } // Target type is type of prototype property var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (!prototypeProperty) { - return type; + if (prototypeProperty) { + var targetType = getTypeOfSymbol(prototypeProperty); + if (targetType !== anyType) { + // Narrow to the target type if it's a subtype of the current type + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + // If the current type is a union type, remove all constituents that aren't subtypes of the target. + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + } + } } - var targetType = getTypeOfSymbol(prototypeProperty); - // Narrow to target type if it is a subtype of current type - if (isTypeSubtypeOf(targetType, type)) { - return targetType; + // Target type is type of construct signature + var constructSignatures; + if (rightType.flags & 2048 /* Interface */) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - // If current type is a union type, remove all constituents that aren't subtypes of target type - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + else if (rightType.flags & 32768 /* Anonymous */) { + constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + } + if (constructSignatures && constructSignatures.length !== 0) { + var instanceType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + // Pickup type from union types + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, instanceType); })); + } + return instanceType; } return type; } @@ -27577,6 +27594,7 @@ var ts; writeLine(); emitToken(15 /* CloseBraceToken */, node.members.end); scopeEmitEnd(); + // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. // For a decorated class, we need to assign its name (if it has one). This is because we emit // the class as a class expression to avoid the double-binding of the identifier: // @@ -27586,15 +27604,6 @@ var ts; // if (thisNodeIsDecorated) { write(";"); - if (node.name) { - writeLine(); - write("Object.defineProperty("); - emitDeclarationName(node); - write(", \"name\", { value: \""); - emitDeclarationName(node); - write("\", configurable: true });"); - writeLine(); - } } // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration diff --git a/bin/typescriptServices.js b/bin/typescriptServices.js index 9cee921f435..ba375bc4096 100644 --- a/bin/typescriptServices.js +++ b/bin/typescriptServices.js @@ -15732,17 +15732,34 @@ var ts; } // Target type is type of prototype property var prototypeProperty = getPropertyOfType(rightType, "prototype"); - if (!prototypeProperty) { - return type; + if (prototypeProperty) { + var targetType = getTypeOfSymbol(prototypeProperty); + if (targetType !== anyType) { + // Narrow to the target type if it's a subtype of the current type + if (isTypeSubtypeOf(targetType, type)) { + return targetType; + } + // If the current type is a union type, remove all constituents that aren't subtypes of the target. + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + } + } } - var targetType = getTypeOfSymbol(prototypeProperty); - // Narrow to target type if it is a subtype of current type - if (isTypeSubtypeOf(targetType, type)) { - return targetType; + // Target type is type of construct signature + var constructSignatures; + if (rightType.flags & 2048 /* Interface */) { + constructSignatures = resolveDeclaredMembers(rightType).declaredConstructSignatures; } - // If current type is a union type, remove all constituents that aren't subtypes of target type - if (type.flags & 16384 /* Union */) { - return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, targetType); })); + else if (rightType.flags & 32768 /* Anonymous */) { + constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */); + } + if (constructSignatures && constructSignatures.length !== 0) { + var instanceType = getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })); + // Pickup type from union types + if (type.flags & 16384 /* Union */) { + return getUnionType(ts.filter(type.types, function (t) { return isTypeSubtypeOf(t, instanceType); })); + } + return instanceType; } return type; } @@ -27577,6 +27594,7 @@ var ts; writeLine(); emitToken(15 /* CloseBraceToken */, node.members.end); scopeEmitEnd(); + // TODO(rbuckton): Need to go back to `let _a = class C {}` approach, removing the defineProperty call for now. // For a decorated class, we need to assign its name (if it has one). This is because we emit // the class as a class expression to avoid the double-binding of the identifier: // @@ -27586,15 +27604,6 @@ var ts; // if (thisNodeIsDecorated) { write(";"); - if (node.name) { - writeLine(); - write("Object.defineProperty("); - emitDeclarationName(node); - write(", \"name\", { value: \""); - emitDeclarationName(node); - write("\", configurable: true });"); - writeLine(); - } } // Emit static property assignment. Because classDeclaration is lexically evaluated, // it is safe to emit static property assignment after classDeclaration