diff --git a/.gitignore b/.gitignore index 3147b8e8724..58a45545939 100644 --- a/.gitignore +++ b/.gitignore @@ -25,6 +25,7 @@ tests/baselines/reference/projectOutput/* tests/baselines/local/projectOutput/* tests/services/baselines/prototyping/local/* tests/services/browser/typescriptServices.js +scripts/configureNightly.js scripts/processDiagnosticMessages.d.ts scripts/processDiagnosticMessages.js scripts/importDefinitelyTypedTests.js diff --git a/AUTHORS.md b/AUTHORS.md new file mode 100644 index 00000000000..0ade4c31221 --- /dev/null +++ b/AUTHORS.md @@ -0,0 +1,70 @@ +TypeScript is authored by: + +* Adam Freidin +* Ahmad Farid +* Anders Hejlsberg +* Arnav Singh +* Arthur Ozga +* Basarat Ali Syed +* Ben Duffield +* Bill Ticehurst +* Bryan Forbes +* Caitlin Potter +* Chris Bubernak +* Colby Russell +* Colin Snover +* Cyrus Najmabadi +* Dan Quirk +* Daniel Rosenwasser +* David Li +* Dick van den Brink +* Dirk Bäumer +* Frank Wallis +* Gabriel Isenberg +* Gilad Peleg +* Guillaume Salles +* Harald Niesche +* Ingvar Stepanyan +* Ivo Gabe de Wolff +* James Whitney +* Jason Freeman +* Jason Ramsay +* Jed Mao +* Johannes Rieken +* Jonathan Bond-Caron +* Jonathan Park +* Jonathan Turner +* Josh Kalderimis +* Kagami Sascha Rosylight +* Keith Mashinter +* Kenji Imamula +* Lorant Pinter +* Masahiro Wakame +* Max Deepfield +* Micah Zoltu +* Mohamed Hegazy +* Oleg Mihailik +* Oleksandr Chekhovskyi +* Paul van Brenk +* Pedro Maltez +* Philip Bulley +* piloopin +* Ron Buckton +* Ryan Cavanaugh +* Sheetal Nandi +* Shengping Zhong +* Shyyko Serhiy +* Simon Hürlimann +* Solal Pirelli +* Stan Thomas +* Steve Lucco +* Tien Hoanhtien +* Tingan Ho +* togru +* Tomas Grubliauskas +* TruongSinh Tran-Nguyen +* Vladimir Matveev +* Wesley Wigham +* Yui Tanglertsampan +* Zev Spitz +* Zhengbo Li \ No newline at end of file diff --git a/Jakefile.js b/Jakefile.js index bd5074b43d6..8fbefe1b2cc 100644 --- a/Jakefile.js +++ b/Jakefile.js @@ -138,6 +138,7 @@ var harnessSources = harnessCoreSources.concat([ "services/documentRegistry.ts", "services/preProcessFile.ts", "services/patternMatcher.ts", + "session.ts", "versionCache.ts", "convertToBase64.ts", "transpile.ts" @@ -313,7 +314,7 @@ var processDiagnosticMessagesTs = path.join(scriptsDirectory, "processDiagnostic var diagnosticMessagesJson = path.join(compilerDirectory, "diagnosticMessages.json"); var diagnosticInfoMapTs = path.join(compilerDirectory, "diagnosticInformationMap.generated.ts"); -file(processDiagnosticMessagesTs) +file(processDiagnosticMessagesTs); // processDiagnosticMessages script compileFile(processDiagnosticMessagesJs, @@ -338,12 +339,50 @@ file(diagnosticInfoMapTs, [processDiagnosticMessagesJs, diagnosticMessagesJson], complete(); }); ex.run(); -}, {async: true}) +}, {async: true}); desc("Generates a diagnostic file in TypeScript based on an input JSON file"); -task("generate-diagnostics", [diagnosticInfoMapTs]) +task("generate-diagnostics", [diagnosticInfoMapTs]); +// Publish nightly +var configureNightlyJs = path.join(scriptsDirectory, "configureNightly.js"); +var configureNightlyTs = path.join(scriptsDirectory, "configureNightly.ts"); +var packageJson = "package.json"; +var programTs = path.join(compilerDirectory, "program.ts"); + +file(configureNightlyTs); + +compileFile(/*outfile*/configureNightlyJs, + /*sources*/ [configureNightlyTs], + /*prereqs*/ [configureNightlyTs], + /*prefixes*/ [], + /*useBuiltCompiler*/ false, + /*noOutFile*/ false, + /*generateDeclarations*/ false, + /*outDir*/ undefined, + /*preserveConstEnums*/ undefined, + /*keepComments*/ false, + /*noResolve*/ false, + /*stripInternal*/ false); + +task("setDebugMode", function() { + useDebugMode = true; +}); + +task("configure-nightly", [configureNightlyJs], function() { + var cmd = "node " + configureNightlyJs + " " + packageJson + " " + programTs; + console.log(cmd); + exec(cmd); +}, { async: true }); + +desc("Configure, build, test, and publish the nightly release."); +task("publish-nightly", ["configure-nightly", "LKG", "clean", "setDebugMode", "runtests"], function () { + var cmd = "npm publish --tag next"; + console.log(cmd); + exec(cmd); +}); + // Local target to build the compiler and services var tscFile = path.join(builtLocalDirectory, compilerFilename); compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false); @@ -440,11 +479,11 @@ file(specMd, [word2mdJs, specWord], function () { child_process.exec(cmd, function () { complete(); }); -}, {async: true}) +}, {async: true}); desc("Generates a Markdown version of the Language Specification"); -task("generate-spec", [specMd]) +task("generate-spec", [specMd]); // Makes a new LKG. This target does not build anything, but errors if not all the outputs are present in the built/local directory @@ -576,7 +615,7 @@ task("runtests", ["tests", builtLocalDirectory], function() { exec(cmd, deleteTemporaryProjectOutput); }, {async: true}); -desc("Generates code coverage data via instanbul") +desc("Generates code coverage data via instanbul"); task("generate-code-coverage", ["tests", builtLocalDirectory], function () { var cmd = 'istanbul cover node_modules/mocha/bin/_mocha -- -R min -t ' + testTimeout + ' ' + run; console.log(cmd); @@ -619,7 +658,7 @@ task("runtests-browser", ["tests", "browserify", builtLocalDirectory], function( function getDiffTool() { var program = process.env['DIFF'] if (!program) { - fail("Add the 'DIFF' environment variable to the path of the program you want to use.") + fail("Add the 'DIFF' environment variable to the path of the program you want to use."); } return program; } @@ -628,14 +667,14 @@ function getDiffTool() { desc("Diffs the compiler baselines using the diff tool specified by the 'DIFF' environment variable"); task('diff', function () { var cmd = '"' + getDiffTool() + '" ' + refBaseline + ' ' + localBaseline; - console.log(cmd) + console.log(cmd); exec(cmd); }, {async: true}); desc("Diffs the RWC baselines using the diff tool specified by the 'DIFF' environment variable"); task('diff-rwc', function () { var cmd = '"' + getDiffTool() + '" ' + refRwcBaseline + ' ' + localRwcBaseline; - console.log(cmd) + console.log(cmd); exec(cmd); }, {async: true}); @@ -736,9 +775,9 @@ task("lint", [], function() { function failure(f) { return function() { console.log('FAILURE: Please fix linting errors in ' + f + '\n') }}; var lintTargets = compilerSources.concat(harnessCoreSources); - for(var i in lintTargets) { + for (var i in lintTargets) { var f = lintTargets[i]; - var cmd = 'tslint -f ' + f; + var cmd = 'tslint -c tslint.json ' + f; exec(cmd, success(f), failure(f)); } }, { async: true }); diff --git a/README.md b/README.md index 57dfe06c67c..c8bc5936c24 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,19 @@ [TypeScript](http://www.typescriptlang.org/) is a language for application-scale JavaScript. TypeScript adds optional types, classes, and modules to JavaScript. TypeScript supports tools for large-scale JavaScript applications for any browser, for any host, on any OS. TypeScript compiles to readable, standards-based JavaScript. Try it out at the [playground](http://www.typescriptlang.org/Playground), and stay up to date via [our blog](http://blogs.msdn.com/typescript) and [twitter account](https://twitter.com/typescriptlang). +## Installing + +For the latest stable version: + +``` +npm install -g typescript +``` + +For our nightly builds: + +``` +npm install -g typescript@next +``` ## Contribute @@ -63,7 +76,8 @@ jake runtests # Run tests using the built compiler and test infrastructu # Use host= or tests=. jake runtests-browser # Runs the tests using the built run.js file. Syntax is jake runtests. Optional parameters 'host=', 'tests=[regex], reporter=[list|spec|json|]'. -jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests. +jake baseline-accept # This replaces the baseline test results with the results obtained from jake runtests. +jake lint # Runs tslint on the TypeScript source. jake -T # List the above commands. ``` diff --git a/package.json b/package.json index 70ada6fef15..c8b30f9de1c 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "typescript", "author": "Microsoft Corp.", "homepage": "http://typescriptlang.org/", - "version": "1.5.3", + "version": "1.6.0", "license": "Apache-2.0", "description": "TypeScript is a language for application scale JavaScript development", "keywords": [ diff --git a/scripts/configureNightly.ts b/scripts/configureNightly.ts new file mode 100644 index 00000000000..640f330b376 --- /dev/null +++ b/scripts/configureNightly.ts @@ -0,0 +1,73 @@ +/// + +/** + * A minimal description for a parsed package.json object. + */ +interface PackageJson { + name: string; + version: string; + keywords: string[]; +} + +function main(): void { + const sys = ts.sys; + if (sys.args.length < 2) { + sys.write("Usage:" + sys.newLine) + sys.write("\tnode configureNightly.js " + sys.newLine); + return; + } + + // Acquire the version from the package.json file and modify it appropriately. + const packageJsonFilePath = ts.normalizePath(sys.args[0]); + const packageJsonContents = sys.readFile(packageJsonFilePath); + const packageJsonValue: PackageJson = JSON.parse(packageJsonContents); + + const nightlyVersion = getNightlyVersionString(packageJsonValue.version); + + // Modify the package.json structure + packageJsonValue.version = nightlyVersion; + + // Acquire and modify the source file that exposes the version string. + const tsFilePath = ts.normalizePath(sys.args[1]); + const tsFileContents = sys.readFile(tsFilePath); + const versionAssignmentRegExp = /export\s+const\s+version\s+=\s+".*";/; + const modifiedTsFileContents = tsFileContents.replace(versionAssignmentRegExp, `export const version = "${nightlyVersion}";`); + + // Ensure we are actually changing something - the user probably wants to know that the update failed. + if (tsFileContents === modifiedTsFileContents) { + let err = `\n '${tsFilePath}' was not updated while configuring for a nightly publish.\n `; + + if (tsFileContents.match(versionAssignmentRegExp)) { + err += `Ensure that you have not already run this script; otherwise, erase your changes using 'git checkout -- "${tsFilePath}"'.`; + } + else { + err += `The file seems to no longer have a string matching '${versionAssignmentRegExp}'.`; + } + + throw err + "\n"; + } + + // Finally write the changes to disk. + sys.writeFile(packageJsonFilePath, JSON.stringify(packageJsonValue, /*replacer:*/ undefined, /*space:*/ 4)) + sys.writeFile(tsFilePath, modifiedTsFileContents); +} + +function getNightlyVersionString(versionString: string): string { + // If the version string already contains "-nightly", + // then get the base string and update based on that. + const dashNightlyPos = versionString.indexOf("-dev"); + if (dashNightlyPos >= 0) { + versionString = versionString.slice(0, dashNightlyPos); + } + + // We're going to append a representation of the current time at the end of the current version. + // String.prototype.toISOString() returns a 24-character string formatted as 'YYYY-MM-DDTHH:mm:ss.sssZ', + // but we'd prefer to just remove separators and limit ourselves to YYYYMMDD. + // UTC time will always be implicit here. + const now = new Date(); + const timeStr = now.toISOString().replace(/:|T|\.|-/g, "").slice(0, 8); + + return `${versionString}-dev.${timeStr}`; +} + +main(); \ No newline at end of file diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index c09b069bee6..44266402607 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -68,6 +68,7 @@ namespace ts { getPropertyOfType, getSignaturesOfType, getIndexTypeOfType, + getBaseTypes, getReturnTypeOfSignature, getSymbolsInScope, getSymbolAtLocation, @@ -90,7 +91,8 @@ namespace ts { getExportsOfModule: getExportsOfModuleAsArray, getJsxElementAttributesType, - getJsxIntrinsicTagNames + getJsxIntrinsicTagNames, + isOptionalParameter }; let unknownSymbol = createSymbol(SymbolFlags.Property | SymbolFlags.Transient, "unknown"); @@ -112,6 +114,10 @@ namespace ts { emptyGenericType.instantiations = {}; let anyFunctionType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); + // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated + // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes. + anyFunctionType.flags |= TypeFlags.ContainsAnyFunctionType; + let noConstraintType = createAnonymousType(undefined, emptySymbols, emptyArray, emptyArray, undefined, undefined); let anySignature = createSignature(undefined, undefined, emptyArray, anyType, undefined, 0, false, false); @@ -1993,15 +1999,15 @@ namespace ts { } return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay + buildSymbolDisplay, + buildTypeDisplay, + buildTypeParameterDisplay, + buildParameterDisplay, + buildDisplayForParametersAndDelimiters, + buildDisplayForTypeParametersAndDelimiters, + buildTypeParameterDisplayFromSymbol, + buildSignatureDisplay, + buildReturnTypeDisplay }); } @@ -3516,7 +3522,19 @@ namespace ts { } function isOptionalParameter(node: ParameterDeclaration) { - return hasQuestionToken(node) || !!node.initializer; + if (hasQuestionToken(node)) { + return true; + } + + if (node.initializer) { + let signatureDeclaration = node.parent; + let signature = getSignatureFromDeclaration(signatureDeclaration); + let parameterIndex = signatureDeclaration.parameters.indexOf(node); + Debug.assert(parameterIndex >= 0); + return parameterIndex >= signature.minArgumentCount; + } + + return false; } function getSignatureFromDeclaration(declaration: SignatureDeclaration): Signature { @@ -3534,11 +3552,16 @@ namespace ts { if (param.type && param.type.kind === SyntaxKind.StringLiteral) { hasStringLiterals = true; } - if (minArgumentCount < 0) { - if (param.initializer || param.questionToken || param.dotDotDotToken) { + + if (param.initializer || param.questionToken || param.dotDotDotToken) { + if (minArgumentCount < 0) { minArgumentCount = i; } } + else { + // If we see any required parameters, it means the prior ones were not in fact optional. + minArgumentCount = -1; + } } if (minArgumentCount < 0) { @@ -3756,22 +3779,23 @@ namespace ts { } } - // This function is used to propagate widening flags when creating new object types references and union types. - // It is only necessary to do so if a constituent type might be the undefined type, the null type, or the type - // of an object literal (since those types have widening related information we need to track). - function getWideningFlagsOfTypes(types: Type[]): TypeFlags { + // This function is used to propagate certain flags when creating new object type references and union types. + // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type + // of an object literal or the anyFunctionType. This is because there are operations in the type checker + // that care about the presence of such types at arbitrary depth in a containing type. + function getPropagatingFlagsOfTypes(types: Type[]): TypeFlags { let result: TypeFlags = 0; for (let type of types) { result |= type.flags; } - return result & TypeFlags.RequiresWidening; + return result & TypeFlags.PropagatingFlags; } function createTypeReference(target: GenericType, typeArguments: Type[]): TypeReference { let id = getTypeListId(typeArguments); let type = target.instantiations[id]; if (!type) { - let flags = TypeFlags.Reference | getWideningFlagsOfTypes(typeArguments); + let flags = TypeFlags.Reference | getPropagatingFlagsOfTypes(typeArguments); type = target.instantiations[id] = createObjectType(flags, target.symbol); type.target = target; type.typeArguments = typeArguments; @@ -4025,7 +4049,7 @@ namespace ts { let id = getTypeListId(elementTypes); let type = tupleTypes[id]; if (!type) { - type = tupleTypes[id] = createObjectType(TypeFlags.Tuple | getWideningFlagsOfTypes(elementTypes)); + type = tupleTypes[id] = createObjectType(TypeFlags.Tuple | getPropagatingFlagsOfTypes(elementTypes)); type.elementTypes = elementTypes; } return type; @@ -4174,7 +4198,7 @@ namespace ts { let id = getTypeListId(typeSet); let type = unionTypes[id]; if (!type) { - type = unionTypes[id] = createObjectType(TypeFlags.Union | getWideningFlagsOfTypes(typeSet)); + type = unionTypes[id] = createObjectType(TypeFlags.Union | getPropagatingFlagsOfTypes(typeSet)); type.types = typeSet; } return type; @@ -4208,7 +4232,7 @@ namespace ts { let id = getTypeListId(typeSet); let type = intersectionTypes[id]; if (!type) { - type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | getWideningFlagsOfTypes(typeSet)); + type = intersectionTypes[id] = createObjectType(TypeFlags.Intersection | getPropagatingFlagsOfTypes(typeSet)); type.types = typeSet; } return type; @@ -4363,11 +4387,11 @@ namespace ts { return getInferredType(context, i); } } - return t; + return t; }; mapper.context = context; - return mapper; + return mapper; } function identityMapper(type: Type): Type { @@ -5655,11 +5679,17 @@ namespace ts { } function inferFromTypes(source: Type, target: Type) { - if (source === anyFunctionType) { - return; - } if (target.flags & TypeFlags.TypeParameter) { - // If target is a type parameter, make an inference + // If target is a type parameter, make an inference, unless the source type contains + // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions). + // Because the anyFunctionType is internal, it should not be exposed to the user by adding + // it as an inference candidate. Hopefully, a better candidate will come along that does + // not contain anyFunctionType when we come back to this argument for its second round + // of inference. + if (source.flags & TypeFlags.ContainsAnyFunctionType) { + return; + } + let typeParameters = context.typeParameters; for (let i = 0; i < typeParameters.length; i++) { if (target === typeParameters[i]) { @@ -7092,7 +7122,7 @@ namespace ts { let stringIndexType = getIndexType(IndexKind.String); let numberIndexType = getIndexType(IndexKind.Number); let result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexType, numberIndexType); - result.flags |= TypeFlags.ObjectLiteral | TypeFlags.FreshObjectLiteral | TypeFlags.ContainsObjectLiteral | (typeFlags & TypeFlags.ContainsUndefinedOrNull); + result.flags |= TypeFlags.ObjectLiteral | TypeFlags.FreshObjectLiteral | TypeFlags.ContainsObjectLiteral | (typeFlags & TypeFlags.PropagatingFlags); return result; function getIndexType(kind: IndexKind) { @@ -7323,10 +7353,9 @@ namespace ts { * For example, in the element , the element instance type is `MyClass` (not `typeof MyClass`). */ function getJsxElementInstanceType(node: JsxOpeningLikeElement) { - if (!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement)) { - // There is no such thing as an instance type for a non-class element - return undefined; - } + // There is no such thing as an instance type for a non-class element. This + // line shouldn't be hit. + Debug.assert(!!(getNodeLinks(node).jsxFlags & JsxFlags.ClassElement), 'Should not call getJsxElementInstanceType on non-class Element'); let classSymbol = getJsxElementTagSymbol(node); if (classSymbol === unknownSymbol) { @@ -7349,16 +7378,11 @@ namespace ts { if (signatures.length === 0) { // We found no signatures at all, which is an error error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName)); - return undefined; + return unknownType; } } - // Check that the constructor/factory returns an object type - let returnType = getUnionType(signatures.map(s => getReturnTypeOfSignature(s))); - if (!isTypeAny(returnType) && !(returnType.flags & TypeFlags.ObjectType)) { - error(node.tagName, Diagnostics.The_return_type_of_a_JSX_element_constructor_must_return_an_object_type); - return undefined; - } + let returnType = getUnionType(signatures.map(getReturnTypeOfSignature)); // Issue an error if this return type isn't assignable to JSX.ElementClass let elemClassType = getJsxGlobalElementClassType(); @@ -7419,7 +7443,7 @@ namespace ts { let elemInstanceType = getJsxElementInstanceType(node); if (isTypeAny(elemInstanceType)) { - return links.resolvedJsxType = anyType; + return links.resolvedJsxType = elemInstanceType; } let propsName = getJsxElementPropertiesName(); @@ -10436,10 +10460,19 @@ namespace ts { // TS 1.0 spec (April 2014): 8.3.2 // Constructors of classes with no extends clause may not contain super calls, whereas // constructors of derived classes must contain at least one super call somewhere in their function body. - if (getClassExtendsHeritageClauseElement(node.parent)) { + let containingClassDecl = node.parent; + if (getClassExtendsHeritageClauseElement(containingClassDecl)) { + let containingClassSymbol = getSymbolOfNode(containingClassDecl); + let containingClassInstanceType = getDeclaredTypeOfSymbol(containingClassSymbol); + let baseConstructorType = getBaseConstructorTypeOfClass(containingClassInstanceType); if (containsSuperCall(node.body)) { - // The first statement in the body of a constructor must be a super call if both of the following are true: + if (baseConstructorType === nullType) { + error(node, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null); + } + + // The first statement in the body of a constructor (excluding prologue directives) must be a super call + // if both of the following are true: // - The containing class is a derived class. // - The constructor declares parameter properties // or the containing class declares instance member variables with initializers. @@ -10447,18 +10480,30 @@ namespace ts { forEach((node.parent).members, isInstancePropertyWithInitializer) || forEach(node.parameters, p => p.flags & (NodeFlags.Public | NodeFlags.Private | NodeFlags.Protected)); + // Skip past any prologue directives to find the first statement + // to ensure that it was a super call. if (superCallShouldBeFirst) { let statements = (node.body).statements; - if (!statements.length || statements[0].kind !== SyntaxKind.ExpressionStatement || !isSuperCallExpression((statements[0]).expression)) { - error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + let superCallStatement: ExpressionStatement; + for (let statement of statements) { + if (statement.kind === SyntaxKind.ExpressionStatement && isSuperCallExpression((statement).expression)) { + superCallStatement = statement; + break; + } + if (!isPrologueDirective(statement)) { + break; + } } + if (!superCallStatement) { + error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_when_a_class_contains_initialized_properties_or_has_parameter_properties); + } else { // In such a required super call, it is a compile-time error for argument expressions to reference this. - markThisReferencesAsErrors((statements[0]).expression); + markThisReferencesAsErrors(superCallStatement.expression); } } } - else { + else if (baseConstructorType !== nullType) { error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call); } } @@ -10849,9 +10894,6 @@ namespace ts { return; } - // Exports should be checked only if enclosing module contains both exported and non exported declarations. - // In case if all declarations are non-exported check is unnecessary. - // if localSymbol is defined on node then node itself is exported - check is required let symbol = node.localSymbol; if (!symbol) { @@ -10871,27 +10913,45 @@ namespace ts { // we use SymbolFlags.ExportValue, SymbolFlags.ExportType and SymbolFlags.ExportNamespace // to denote disjoint declarationSpaces (without making new enum type). - let exportedDeclarationSpaces: SymbolFlags = 0; - let nonExportedDeclarationSpaces: SymbolFlags = 0; - forEach(symbol.declarations, d => { + let exportedDeclarationSpaces = SymbolFlags.None; + let nonExportedDeclarationSpaces = SymbolFlags.None; + let defaultExportedDeclarationSpaces = SymbolFlags.None; + for (let d of symbol.declarations) { let declarationSpaces = getDeclarationSpaces(d); - if (getEffectiveDeclarationFlags(d, NodeFlags.Export)) { - exportedDeclarationSpaces |= declarationSpaces; + let effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, NodeFlags.Export | NodeFlags.Default); + + if (effectiveDeclarationFlags & NodeFlags.Export) { + if (effectiveDeclarationFlags & NodeFlags.Default) { + defaultExportedDeclarationSpaces |= declarationSpaces; + } + else { + exportedDeclarationSpaces |= declarationSpaces; + } } else { nonExportedDeclarationSpaces |= declarationSpaces; } - }); + } - let commonDeclarationSpace = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + // Spaces for anyting not declared a 'default export'. + let nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces; + + let commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces; + let commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces; - if (commonDeclarationSpace) { + if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) { // declaration spaces for exported and non-exported declarations intersect - forEach(symbol.declarations, d => { - if (getDeclarationSpaces(d) & commonDeclarationSpace) { + for (let d of symbol.declarations) { + let declarationSpaces = getDeclarationSpaces(d); + + // Only error on the declarations that conributed to the intersecting spaces. + if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) { + error(d.name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(d.name)); + } + else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) { error(d.name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(d.name)); } - }); + } } function getDeclarationSpaces(d: Declaration): SymbolFlags { @@ -12736,28 +12796,7 @@ namespace ts { } let initializer = member.initializer; if (initializer) { - autoValue = getConstantValueForEnumMemberInitializer(initializer); - if (autoValue === undefined) { - if (enumIsConst) { - error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); - } - else if (!ambient) { - // Only here do we need to check that the initializer is assignable to the enum type. - // If it is a constant value (not undefined), it is syntactically constrained to be a number. - // Also, we do not need to check this for ambients because there is already - // a syntax error if it is not a constant. - checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); - } - } - else if (enumIsConst) { - if (isNaN(autoValue)) { - error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); - } - else if (!isFinite(autoValue)) { - error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); - } - } - + autoValue = computeConstantValueForEnumMemberInitializer(initializer, enumType, enumIsConst, ambient); } else if (ambient && !enumIsConst) { autoValue = undefined; @@ -12771,8 +12810,36 @@ namespace ts { nodeLinks.flags |= NodeCheckFlags.EnumValuesComputed; } - function getConstantValueForEnumMemberInitializer(initializer: Expression): number { - return evalConstant(initializer); + function computeConstantValueForEnumMemberInitializer(initializer: Expression, enumType: Type, enumIsConst: boolean, ambient: boolean): number { + // Controls if error should be reported after evaluation of constant value is completed + // Can be false if another more precise error was already reported during evaluation. + let reportError = true; + let value = evalConstant(initializer); + + if (reportError) { + if (value === undefined) { + if (enumIsConst) { + error(initializer, Diagnostics.In_const_enum_declarations_member_initializer_must_be_constant_expression); + } + else if (!ambient) { + // Only here do we need to check that the initializer is assignable to the enum type. + // If it is a constant value (not undefined), it is syntactically constrained to be a number. + // Also, we do not need to check this for ambients because there is already + // a syntax error if it is not a constant. + checkTypeAssignableTo(checkExpression(initializer), enumType, initializer, /*headMessage*/ undefined); + } + } + else if (enumIsConst) { + if (isNaN(value)) { + error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN); + } + else if (!isFinite(value)) { + error(initializer, Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value); + } + } + } + + return value; function evalConstant(e: Node): number { switch (e.kind) { @@ -12881,6 +12948,8 @@ namespace ts { // illegal case: forward reference if (!isDefinedBefore(propertyDecl, member)) { + reportError = false; + error(e, Diagnostics.A_member_initializer_in_a_const_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_const_enums); return undefined; } @@ -14362,6 +14431,7 @@ namespace ts { getBlockScopedVariableId, getReferencedValueDeclaration, getTypeReferenceSerializationKind, + isOptionalParameter }; } @@ -14757,17 +14827,15 @@ namespace ts { return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer); } } - else if (parameter.questionToken || parameter.initializer) { + else if (parameter.questionToken) { seenOptionalParameter = true; - if (parameter.questionToken && parameter.initializer) { + if (parameter.initializer) { return grammarErrorOnNode(parameter.name, Diagnostics.Parameter_cannot_have_question_mark_and_initializer); } } - else { - if (seenOptionalParameter) { - return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); - } + else if (seenOptionalParameter && !parameter.initializer) { + return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter); } } } diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts index 6c0803f8761..63d71b0339e 100644 --- a/src/compiler/declarationEmitter.ts +++ b/src/compiler/declarationEmitter.ts @@ -1371,7 +1371,7 @@ namespace ts { else { writeTextOfNode(currentSourceFile, node.name); } - if (node.initializer || hasQuestionToken(node)) { + if (resolver.isOptionalParameter(node)) { write("?"); } decreaseIndent(); diff --git a/src/compiler/diagnosticInformationMap.generated.ts b/src/compiler/diagnosticInformationMap.generated.ts index b91399e8ee1..5ccc0a0db9b 100644 --- a/src/compiler/diagnosticInformationMap.generated.ts +++ b/src/compiler/diagnosticInformationMap.generated.ts @@ -294,7 +294,7 @@ namespace ts { Multiple_constructor_implementations_are_not_allowed: { code: 2392, category: DiagnosticCategory.Error, key: "Multiple constructor implementations are not allowed." }, Duplicate_function_implementation: { code: 2393, category: DiagnosticCategory.Error, key: "Duplicate function implementation." }, Overload_signature_is_not_compatible_with_function_implementation: { code: 2394, category: DiagnosticCategory.Error, key: "Overload signature is not compatible with function implementation." }, - Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration {0} must be all exported or all local." }, + Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local: { code: 2395, category: DiagnosticCategory.Error, key: "Individual declarations in merged declaration '{0}' must be all exported or all local." }, Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters: { code: 2396, category: DiagnosticCategory.Error, key: "Duplicate identifier 'arguments'. Compiler uses 'arguments' to initialize rest parameters." }, Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference: { code: 2399, category: DiagnosticCategory.Error, key: "Duplicate identifier '_this'. Compiler uses variable declaration '_this' to capture 'this' reference." }, Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference: { code: 2400, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '_this' that compiler uses to capture 'this' reference." }, @@ -425,6 +425,8 @@ namespace ts { JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" }, The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" }, Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" }, + A_member_initializer_in_a_const_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_const_enums: { code: 2651, category: DiagnosticCategory.Error, key: "A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums." }, + Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: { code: 2652, category: DiagnosticCategory.Error, key: "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead." }, 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}'." }, @@ -509,7 +511,6 @@ namespace ts { Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'out' or 'outDir'." }, Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: DiagnosticCategory.Error, key: "Option 'noEmit' cannot be specified with option 'declaration'." }, Option_project_cannot_be_mixed_with_source_files_on_a_command_line: { code: 5042, category: DiagnosticCategory.Error, key: "Option 'project' cannot be mixed with source files on a command line." }, - Option_sourceMap_cannot_be_specified_with_option_isolatedModules: { code: 5043, category: DiagnosticCategory.Error, key: "Option 'sourceMap' cannot be specified with option 'isolatedModules'." }, Option_declaration_cannot_be_specified_with_option_isolatedModules: { code: 5044, category: DiagnosticCategory.Error, key: "Option 'declaration' cannot be specified with option 'isolatedModules'." }, Option_noEmitOnError_cannot_be_specified_with_option_isolatedModules: { code: 5045, category: DiagnosticCategory.Error, key: "Option 'noEmitOnError' cannot be specified with option 'isolatedModules'." }, Option_out_cannot_be_specified_with_option_isolatedModules: { code: 5046, category: DiagnosticCategory.Error, key: "Option 'out' cannot be specified with option 'isolatedModules'." }, @@ -614,5 +615,6 @@ namespace ts { Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." }, JSX_attribute_expected: { code: 17003, category: DiagnosticCategory.Error, key: "JSX attribute expected." }, Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." }, + A_constructor_cannot_contain_a_super_call_when_its_class_extends_null: { code: 17005, category: DiagnosticCategory.Error, key: "A constructor cannot contain a 'super' call when its class extends 'null'" }, }; } \ No newline at end of file diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index 9fda73740ba..e138e2ddac4 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -1,4 +1,4 @@ -{ + { "Unterminated string literal.": { "category": "Error", "code": 1002 @@ -1165,7 +1165,7 @@ "category": "Error", "code": 2394 }, - "Individual declarations in merged declaration {0} must be all exported or all local.": { + "Individual declarations in merged declaration '{0}' must be all exported or all local.": { "category": "Error", "code": 2395 }, @@ -1689,6 +1689,14 @@ "category": "Error", "code": 2650 }, + "A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums.": { + "category": "Error", + "code": 2651 + }, + "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead.": { + "category": "Error", + "code": 2652 + }, "Import declaration '{0}' is using private name '{1}'.": { "category": "Error", "code": 4000 @@ -2025,10 +2033,6 @@ "category": "Error", "code": 5042 }, - "Option 'sourceMap' cannot be specified with option 'isolatedModules'.": { - "category": "Error", - "code": 5043 - }, "Option 'declaration' cannot be specified with option 'isolatedModules'.": { "category": "Error", "code": 5044 @@ -2449,5 +2453,9 @@ "Cannot use JSX unless the '--jsx' flag is provided.": { "category": "Error", "code": 17004 + }, + "A constructor cannot contain a 'super' call when its class extends 'null'": { + "category": "Error", + "code": 17005 } } diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index d55e5ec9464..b1a0c1fff5b 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -6842,6 +6842,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi return leadingComments; } + /** + * Removes all but the pinned or triple slash comments. + * @param ranges The array to be filtered + * @param onlyPinnedOrTripleSlashComments whether the filtering should be performed. + */ function filterComments(ranges: CommentRange[], onlyPinnedOrTripleSlashComments: boolean): CommentRange[] { // If we're removing comments, then we want to strip out all but the pinned or // triple slash comments. diff --git a/src/compiler/program.ts b/src/compiler/program.ts index 5ce4846b43b..4b1f10eb649 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -8,7 +8,7 @@ namespace ts { /* @internal */ export let ioWriteTime = 0; /** The version of the TypeScript compiler release */ - export const version = "1.5.3"; + export const version = "1.6.0"; export function findConfigFile(searchPath: string): string { let fileName = "tsconfig.json"; @@ -341,7 +341,7 @@ namespace ts { }); } - function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { + function getDeclarationDiagnosticsForFile(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] { return runWithCancellationToken(() => { if (!isDeclarationFile(sourceFile)) { let resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken); @@ -350,7 +350,7 @@ namespace ts { return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile); } }); - } + } function getOptionsDiagnostics(): Diagnostic[] { let allDiagnostics: Diagnostic[] = []; @@ -602,10 +602,6 @@ namespace ts { function verifyCompilerOptions() { if (options.isolatedModules) { - if (options.sourceMap) { - diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_sourceMap_cannot_be_specified_with_option_isolatedModules)); - } - if (options.declaration) { diagnostics.add(createCompilerDiagnostic(Diagnostics.Option_declaration_cannot_be_specified_with_option_isolatedModules)); } diff --git a/src/compiler/tsc.ts b/src/compiler/tsc.ts index a657cc8c314..6872c4c876e 100644 --- a/src/compiler/tsc.ts +++ b/src/compiler/tsc.ts @@ -3,7 +3,7 @@ namespace ts { export interface SourceFile { - fileWatcher: FileWatcher; + fileWatcher?: FileWatcher; } /** diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 8d5596c6f64..c5d7f879c25 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -1404,6 +1404,7 @@ namespace ts { getPropertyOfType(type: Type, propertyName: string): Symbol; getSignaturesOfType(type: Type, kind: SignatureKind): Signature[]; getIndexTypeOfType(type: Type, kind: IndexKind): Type; + getBaseTypes(type: InterfaceType): ObjectType[]; getReturnTypeOfSignature(signature: Signature): Type; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; @@ -1430,6 +1431,7 @@ namespace ts { getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type; getJsxIntrinsicTagNames(): Symbol[]; + isOptionalParameter(node: ParameterDeclaration): boolean; // Should not be called directly. Should only be accessed through the Program instance. /* @internal */ getDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1573,7 +1575,8 @@ namespace ts { getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; getBlockScopedVariableId(node: Identifier): number; getReferencedValueDeclaration(reference: Identifier): Declaration; - getTypeReferenceSerializationKind(node: TypeReferenceNode): TypeReferenceSerializationKind; + getTypeReferenceSerializationKind(node: TypeReferenceNode): TypeReferenceSerializationKind; + isOptionalParameter(node: ParameterDeclaration): boolean; } export const enum SymbolFlags { @@ -1767,7 +1770,9 @@ namespace ts { ContainsUndefinedOrNull = 0x00200000, // Type is or contains Undefined or Null type /* @internal */ ContainsObjectLiteral = 0x00400000, // Type is or contains object literal type - ESSymbol = 0x00800000, // Type of symbol primitive introduced in ES6 + /* @internal */ + ContainsAnyFunctionType = 0x00800000, // Type is or contains object literal type + ESSymbol = 0x01000000, // Type of symbol primitive introduced in ES6 /* @internal */ Intrinsic = Any | String | Number | Boolean | ESSymbol | Void | Undefined | Null, @@ -1776,10 +1781,12 @@ namespace ts { StringLike = String | StringLiteral, NumberLike = Number | Enum, ObjectType = Class | Interface | Reference | Tuple | Anonymous, - UnionOrIntersection = Union | Intersection, + UnionOrIntersection = Union | Intersection, StructuredType = ObjectType | Union | Intersection, + /* @internal */ + RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral, /* @internal */ - RequiresWidening = ContainsUndefinedOrNull | ContainsObjectLiteral + PropagatingFlags = ContainsUndefinedOrNull | ContainsObjectLiteral | ContainsAnyFunctionType } // Properties common to all types @@ -1808,7 +1815,9 @@ namespace ts { typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic) outerTypeParameters: TypeParameter[]; // Outer type parameters (undefined if none) localTypeParameters: TypeParameter[]; // Local type parameters (undefined if none) + /* @internal */ resolvedBaseConstructorType?: Type; // Resolved base constructor type of class + /* @internal */ resolvedBaseTypes: ObjectType[]; // Resolved base types } diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 56eb2415cf9..312a3666757 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -988,15 +988,13 @@ namespace ts { if (node) { switch (node.kind) { case SyntaxKind.Parameter: - return (node).questionToken !== undefined; case SyntaxKind.MethodDeclaration: case SyntaxKind.MethodSignature: - return (node).questionToken !== undefined; case SyntaxKind.ShorthandPropertyAssignment: case SyntaxKind.PropertyAssignment: case SyntaxKind.PropertyDeclaration: case SyntaxKind.PropertySignature: - return (node).questionToken !== undefined; + return (node).questionToken !== undefined; } } diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index 02ca17cefd7..272f4c1c1dd 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -1875,7 +1875,7 @@ module FourSlash { } } - private verifyProjectInfo(expected: string[]) { + public verifyProjectInfo(expected: string[]) { if (this.testType === FourSlashTestType.Server) { let actual = (this.languageService).getProjectInfo( this.activeFile.fileName, @@ -2057,11 +2057,8 @@ module FourSlash { return result; } - public verifGetScriptLexicalStructureListContains( - name: string, - kind: string, - markerPosition?: number) { - this.taoInvalidReason = 'verifGetScriptLexicalStructureListContains impossible'; + public verifyGetScriptLexicalStructureListContains(name: string, kind: string) { + this.taoInvalidReason = 'verifyGetScriptLexicalStructureListContains impossible'; let items = this.languageService.getNavigationBarItems(this.activeFile.fileName); @@ -2263,7 +2260,7 @@ module FourSlash { return 'line ' + (pos.line + 1) + ', col ' + pos.character; } - private getMarkerByName(markerName: string) { + public getMarkerByName(markerName: string) { let markerPos = this.testData.markerPositions[markerName]; if (markerPos === undefined) { let markerNames: string[] = []; @@ -2738,4 +2735,4 @@ module FourSlash { fileName: fileName }; } -} +} \ No newline at end of file diff --git a/src/harness/harness.ts b/src/harness/harness.ts index 17aa0dd325c..b6c10071cb1 100644 --- a/src/harness/harness.ts +++ b/src/harness/harness.ts @@ -29,6 +29,7 @@ var Buffer: BufferConstructor = require('buffer').Buffer; // this will work in the browser via browserify var _chai: typeof chai = require('chai'); var assert: typeof _chai.assert = _chai.assert; +var expect: typeof _chai.expect = _chai.expect; declare var __dirname: string; // Node-specific var global = Function("return this").call(null); diff --git a/src/server/session.ts b/src/server/session.ts index d2ac429aa3c..9a5cee32264 100644 --- a/src/server/session.ts +++ b/src/server/session.ts @@ -109,13 +109,13 @@ namespace ts.server { } export class Session { - projectService: ProjectService; - pendingOperation = false; - fileHash: ts.Map = {}; - nextFileId = 1; - errorTimer: any; /*NodeJS.Timer | number*/ - immediateId: any; - changeSeq = 0; + protected projectService: ProjectService; + private pendingOperation = false; + private fileHash: ts.Map = {}; + private nextFileId = 1; + private errorTimer: any; /*NodeJS.Timer | number*/ + private immediateId: any; + private changeSeq = 0; constructor( private host: ServerHost, @@ -129,7 +129,7 @@ namespace ts.server { }); } - handleEvent(eventName: string, project: Project, fileName: string) { + private handleEvent(eventName: string, project: Project, fileName: string) { if (eventName == "context") { this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); this.updateErrorCheck([{ fileName, project }], this.changeSeq, @@ -137,7 +137,7 @@ namespace ts.server { } } - logError(err: Error, cmd: string) { + public logError(err: Error, cmd: string) { var typedErr = err; var msg = "Exception on executing command " + cmd; if (typedErr.message) { @@ -149,11 +149,11 @@ namespace ts.server { this.projectService.log(msg); } - sendLineToClient(line: string) { + private sendLineToClient(line: string) { this.host.write(line + this.host.newLine); } - send(msg: protocol.Message) { + public send(msg: protocol.Message) { var json = JSON.stringify(msg); if (this.logger.isVerbose()) { this.logger.info(msg.type + ": " + json); @@ -162,7 +162,7 @@ namespace ts.server { '\r\n\r\n' + json); } - event(info: any, eventName: string) { + public event(info: any, eventName: string) { var ev: protocol.Event = { seq: 0, type: "event", @@ -172,7 +172,7 @@ namespace ts.server { this.send(ev); } - response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) { + private response(info: any, cmdName: string, reqSeq = 0, errorMsg?: string) { var res: protocol.Response = { seq: 0, type: "response", @@ -189,11 +189,11 @@ namespace ts.server { this.send(res); } - output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) { + public output(body: any, commandName: string, requestSequence = 0, errorMessage?: string) { this.response(body, commandName, requestSequence, errorMessage); } - semanticCheck(file: string, project: Project) { + private semanticCheck(file: string, project: Project) { try { var diags = project.compilerService.languageService.getSemanticDiagnostics(file); @@ -207,7 +207,7 @@ namespace ts.server { } } - syntacticCheck(file: string, project: Project) { + private syntacticCheck(file: string, project: Project) { try { var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); if (diags) { @@ -220,12 +220,12 @@ namespace ts.server { } } - errorCheck(file: string, project: Project) { + private errorCheck(file: string, project: Project) { this.syntacticCheck(file, project); this.semanticCheck(file, project); } - updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) { + private updateProjectStructure(seq: number, matchSeq: (seq: number) => boolean, ms = 1500) { setTimeout(() => { if (matchSeq(seq)) { this.projectService.updateProjectStructure(); @@ -233,7 +233,7 @@ namespace ts.server { }, ms); } - updateErrorCheck(checkList: PendingErrorCheck[], seq: number, + private updateErrorCheck(checkList: PendingErrorCheck[], seq: number, matchSeq: (seq: number) => boolean, ms = 1500, followMs = 200) { if (followMs > ms) { followMs = ms; @@ -269,7 +269,7 @@ namespace ts.server { } } - getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { + private getDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -291,7 +291,7 @@ namespace ts.server { })); } - getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { + private getTypeDefinition(line: number, offset: number, fileName: string): protocol.FileSpan[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -313,7 +313,7 @@ namespace ts.server { })); } - getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[]{ + private getOccurrences(line: number, offset: number, fileName: string): protocol.OccurrencesResponseItem[]{ fileName = ts.normalizePath(fileName); let project = this.projectService.getProjectForFile(fileName); @@ -343,7 +343,7 @@ namespace ts.server { }); } - getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo { + private getProjectInfo(fileName: string, needFileNameList: boolean): protocol.ProjectInfo { fileName = ts.normalizePath(fileName) let project = this.projectService.getProjectForFile(fileName) @@ -358,7 +358,7 @@ namespace ts.server { return projectInfo; } - getRenameLocations(line: number, offset: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody { + private getRenameLocations(line: number, offset: number, fileName: string,findInComments: boolean, findInStrings: boolean): protocol.RenameResponseBody { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -426,7 +426,7 @@ namespace ts.server { return { info: renameInfo, locs: bakedRenameLocs }; } - getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody { + private getReferences(line: number, offset: number, fileName: string): protocol.ReferencesResponseBody { // TODO: get all projects for this file; report refs for all projects deleting duplicates // can avoid duplicates by eliminating same ref file from subsequent projects var file = ts.normalizePath(fileName); @@ -473,12 +473,12 @@ namespace ts.server { }; } - openClientFile(fileName: string) { + private openClientFile(fileName: string) { var file = ts.normalizePath(fileName); this.projectService.openClientFile(file); } - getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody { + private getQuickInfo(line: number, offset: number, fileName: string): protocol.QuickInfoResponseBody { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -504,7 +504,7 @@ namespace ts.server { }; } - getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] { + private getFormattingEditsForRange(line: number, offset: number, endLine: number, endOffset: number, fileName: string): protocol.CodeEdit[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -531,7 +531,7 @@ namespace ts.server { }); } - getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] { + private getFormattingEditsAfterKeystroke(line: number, offset: number, key: string, fileName: string): protocol.CodeEdit[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); @@ -607,7 +607,7 @@ namespace ts.server { }); } - getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] { + private getCompletions(line: number, offset: number, prefix: string, fileName: string): protocol.CompletionEntry[] { if (!prefix) { prefix = ""; } @@ -633,7 +633,7 @@ namespace ts.server { }, []).sort((a, b) => a.name.localeCompare(b.name)); } - getCompletionEntryDetails(line: number, offset: number, + private getCompletionEntryDetails(line: number, offset: number, entryNames: string[], fileName: string): protocol.CompletionEntryDetails[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); @@ -653,7 +653,7 @@ namespace ts.server { }, []); } - getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems { + private getSignatureHelpItems(line: number, offset: number, fileName: string): protocol.SignatureHelpItems { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -682,7 +682,7 @@ namespace ts.server { return result; } - getDiagnostics(delay: number, fileNames: string[]) { + private getDiagnostics(delay: number, fileNames: string[]) { var checkList = fileNames.reduce((accum: PendingErrorCheck[], fileName: string) => { fileName = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(fileName); @@ -697,7 +697,7 @@ namespace ts.server { } } - change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) { + private change(line: number, offset: number, endLine: number, endOffset: number, insertString: string, fileName: string) { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (project) { @@ -712,7 +712,7 @@ namespace ts.server { } } - reload(fileName: string, tempFileName: string, reqSeq = 0) { + private reload(fileName: string, tempFileName: string, reqSeq = 0) { var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); var project = this.projectService.getProjectForFile(file); @@ -725,7 +725,7 @@ namespace ts.server { } } - saveToTmp(fileName: string, tempFileName: string) { + private saveToTmp(fileName: string, tempFileName: string) { var file = ts.normalizePath(fileName); var tmpfile = ts.normalizePath(tempFileName); @@ -735,12 +735,12 @@ namespace ts.server { } } - closeClientFile(fileName: string) { + private closeClientFile(fileName: string) { var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); } - decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] { + private decorateNavigationBarItem(project: Project, fileName: string, items: ts.NavigationBarItem[]): protocol.NavigationBarItem[] { if (!items) { return undefined; } @@ -759,7 +759,7 @@ namespace ts.server { })); } - getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] { + private getNavigationBarItems(fileName: string): protocol.NavigationBarItem[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -775,7 +775,7 @@ namespace ts.server { return this.decorateNavigationBarItem(project, fileName, items); } - getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] { + private getNavigateToItems(searchValue: string, fileName: string, maxResultCount?: number): protocol.NavtoItem[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); if (!project) { @@ -814,7 +814,7 @@ namespace ts.server { }); } - getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] { + private getBraceMatching(line: number, offset: number, fileName: string): protocol.TextSpan[] { var file = ts.normalizePath(fileName); var project = this.projectService.getProjectForFile(file); @@ -836,7 +836,7 @@ namespace ts.server { })); } - exit() { + public exit() { } private handlers : Map<(request: protocol.Request) => {response?: any, responseRequired?: boolean}> = { @@ -942,14 +942,14 @@ namespace ts.server { return {response: this.getProjectInfo(file, needFileNameList), responseRequired: true}; }, }; - addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) { + public addProtocolHandler(command: string, handler: (request: protocol.Request) => {response?: any, responseRequired: boolean}) { if (this.handlers[command]) { throw new Error(`Protocol handler already exists for command "${command}"`); } this.handlers[command] = handler; } - executeCommand(request: protocol.Request) : {response?: any, responseRequired?: boolean} { + public executeCommand(request: protocol.Request) : {response?: any, responseRequired?: boolean} { var handler = this.handlers[request.command]; if (handler) { return handler(request); @@ -960,7 +960,7 @@ namespace ts.server { } } - onMessage(message: string) { + public onMessage(message: string) { if (this.logger.isVerbose()) { this.logger.info("request: " + message); var start = this.hrtime(); diff --git a/src/services/services.ts b/src/services/services.ts index 16f5b0b91fe..8e670268498 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -48,6 +48,7 @@ namespace ts { getConstructSignatures(): Signature[]; getStringIndexType(): Type; getNumberIndexType(): Type; + getBaseTypes(): ObjectType[] } export interface Signature { @@ -260,26 +261,25 @@ namespace ts { } public getFirstToken(sourceFile?: SourceFile): Node { - let children = this.getChildren(); - for (let child of children) { - if (child.kind < SyntaxKind.FirstNode) { - return child; - } - - return child.getFirstToken(sourceFile); + let children = this.getChildren(sourceFile); + if (!children.length) { + return undefined; } + + let child = children[0]; + + return child.kind < SyntaxKind.FirstNode ? child : child.getFirstToken(sourceFile); } public getLastToken(sourceFile?: SourceFile): Node { let children = this.getChildren(sourceFile); - for (let i = children.length - 1; i >= 0; i--) { - let child = children[i]; - if (child.kind < SyntaxKind.FirstNode) { - return child; - } - return child.getLastToken(sourceFile); + let child = lastOrUndefined(children); + if (!child) { + return undefined; } + + return child.kind < SyntaxKind.FirstNode ? child : child.getLastToken(sourceFile); } } @@ -682,6 +682,11 @@ namespace ts { getNumberIndexType(): Type { return this.checker.getIndexTypeOfType(this, IndexKind.Number); } + getBaseTypes(): ObjectType[] { + return this.flags & (TypeFlags.Class | TypeFlags.Interface) + ? this.checker.getBaseTypes(this) + : undefined; + } } class SignatureObject implements Signature { @@ -1754,18 +1759,31 @@ namespace ts { sourceFile.version = version; sourceFile.scriptSnapshot = scriptSnapshot; } - + + export interface TranspileOptions { + compilerOptions?: CompilerOptions; + fileName?: string; + reportDiagnostics?: boolean; + moduleName?: string; + } + + export interface TranspileOutput { + outputText: string; + diagnostics?: Diagnostic[]; + sourceMapText?: string; + } + /* * This function will compile source text from 'input' argument using specified compiler options. * If not options are provided - it will use a set of default compiler options. - * Extra compiler options that will unconditionally be used bu this function are: + * Extra compiler options that will unconditionally be used by this function are: * - isolatedModules = true * - allowNonTsExtensions = true * - noLib = true * - noResolve = true - */ - export function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string { - let options = compilerOptions ? clone(compilerOptions) : getDefaultCompilerOptions(); + */ + export function transpileModule(input: string, transpileOptions?: TranspileOptions): TranspileOutput { + let options = transpileOptions.compilerOptions ? clone(transpileOptions.compilerOptions) : getDefaultCompilerOptions(); options.isolatedModules = true; @@ -1781,23 +1799,30 @@ namespace ts { options.noResolve = true; // Parse - let inputFileName = fileName || "module.ts"; + let inputFileName = transpileOptions.fileName || "module.ts"; let sourceFile = createSourceFile(inputFileName, input, options.target); - if (moduleName) { - sourceFile.moduleName = moduleName; + if (transpileOptions.moduleName) { + sourceFile.moduleName = transpileOptions.moduleName; } let newLine = getNewLineCharacter(options); // Output let outputText: string; + let sourceMapText: string; // Create a compilerHost object to allow the compiler to read and write files let compilerHost: CompilerHost = { getSourceFile: (fileName, target) => fileName === inputFileName ? sourceFile : undefined, writeFile: (name, text, writeByteOrderMark) => { - Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); - outputText = text; + if (fileExtensionIs(name, ".map")) { + Debug.assert(sourceMapText === undefined, `Unexpected multiple source map outputs for the file '${name}'`); + sourceMapText = text; + } + else { + Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name); + outputText = text; + } }, getDefaultLibFileName: () => "lib.d.ts", useCaseSensitiveFileNames: () => false, @@ -1807,16 +1832,29 @@ namespace ts { }; let program = createProgram([inputFileName], options, compilerHost); - - addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); - addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); - + + let diagnostics: Diagnostic[]; + if (transpileOptions.reportDiagnostics) { + diagnostics = []; + addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile)); + addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics()); + } // Emit program.emit(); Debug.assert(outputText !== undefined, "Output generation failed"); - return outputText; + return { outputText, diagnostics, sourceMapText }; + } + + /* + * This is a shortcut function for transpileModule - it accepts transpileOptions as parameters and returns only outputText part of the result. + */ + export function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string { + let output = transpileModule(input, { compilerOptions, fileName, reportDiagnostics: !!diagnostics, moduleName }); + // addRange correctly handles cases when wither 'from' or 'to' argument is missing + addRange(diagnostics, output.diagnostics); + return output.outputText; } export function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile { diff --git a/src/services/signatureHelp.ts b/src/services/signatureHelp.ts index f44ebade2a7..df321647e5c 100644 --- a/src/services/signatureHelp.ts +++ b/src/services/signatureHelp.ts @@ -611,13 +611,11 @@ namespace ts.SignatureHelp { let displayParts = mapToDisplayParts(writer => typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation)); - let isOptional = hasQuestionToken(parameter.valueDeclaration); - return { name: parameter.name, documentation: parameter.getDocumentationComment(), displayParts, - isOptional + isOptional: typeChecker.isOptionalParameter(parameter.valueDeclaration) }; } diff --git a/tests/baselines/reference/classExtendsNull.errors.txt b/tests/baselines/reference/classExtendsNull.errors.txt new file mode 100644 index 00000000000..7bb44774826 --- /dev/null +++ b/tests/baselines/reference/classExtendsNull.errors.txt @@ -0,0 +1,21 @@ +tests/cases/compiler/classExtendsNull.ts(2,5): error TS17005: A constructor cannot contain a 'super' call when its class extends 'null' + + +==== tests/cases/compiler/classExtendsNull.ts (1 errors) ==== + class C extends null { + constructor() { + ~~~~~~~~~~~~~~~ + super(); + ~~~~~~~~~~~~~~~~ + return Object.create(null); + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + } + ~~~~~ +!!! error TS17005: A constructor cannot contain a 'super' call when its class extends 'null' + } + + class D extends null { + constructor() { + return Object.create(null); + } + } \ No newline at end of file diff --git a/tests/baselines/reference/classExtendsNull.js b/tests/baselines/reference/classExtendsNull.js new file mode 100644 index 00000000000..5627f10dca6 --- /dev/null +++ b/tests/baselines/reference/classExtendsNull.js @@ -0,0 +1,35 @@ +//// [classExtendsNull.ts] +class C extends null { + constructor() { + super(); + return Object.create(null); + } +} + +class D extends null { + constructor() { + return Object.create(null); + } +} + +//// [classExtendsNull.js] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +var C = (function (_super) { + __extends(C, _super); + function C() { + _super.call(this); + return Object.create(null); + } + return C; +})(null); +var D = (function (_super) { + __extends(D, _super); + function D() { + return Object.create(null); + } + return D; +})(null); diff --git a/tests/baselines/reference/constEnumErrors.errors.txt b/tests/baselines/reference/constEnumErrors.errors.txt index be7dad54eeb..4236544defa 100644 --- a/tests/baselines/reference/constEnumErrors.errors.txt +++ b/tests/baselines/reference/constEnumErrors.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/constEnumErrors.ts(1,12): error TS2300: Duplicate identifier 'E'. tests/cases/compiler/constEnumErrors.ts(5,8): error TS2300: Duplicate identifier 'E'. -tests/cases/compiler/constEnumErrors.ts(12,9): error TS2474: In 'const' enum declarations member initializer must be constant expression. +tests/cases/compiler/constEnumErrors.ts(12,9): error TS2651: A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums. tests/cases/compiler/constEnumErrors.ts(14,9): error TS2474: In 'const' enum declarations member initializer must be constant expression. tests/cases/compiler/constEnumErrors.ts(15,10): error TS2474: In 'const' enum declarations member initializer must be constant expression. tests/cases/compiler/constEnumErrors.ts(22,13): error TS2476: A const enum member can only be accessed using a string literal. @@ -31,7 +31,7 @@ tests/cases/compiler/constEnumErrors.ts(42,9): error TS2478: 'const' enum member // forward reference to the element of the same enum X = Y, ~ -!!! error TS2474: In 'const' enum declarations member initializer must be constant expression. +!!! error TS2651: A member initializer in a 'const' enum declaration cannot reference members declared after it, including members defined in other 'const' enums. // forward reference to the element of the same enum Y = E1.Z, ~~~~ diff --git a/tests/baselines/reference/defaultExportsCannotMerge01.errors.txt b/tests/baselines/reference/defaultExportsCannotMerge01.errors.txt new file mode 100644 index 00000000000..be08d976eeb --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge01.errors.txt @@ -0,0 +1,49 @@ +tests/cases/conformance/es6/modules/m1.ts(2,25): error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. +tests/cases/conformance/es6/modules/m1.ts(11,18): error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. +tests/cases/conformance/es6/modules/m2.ts(5,8): error TS2304: Cannot find name 'Entity'. +tests/cases/conformance/es6/modules/m2.ts(6,8): error TS2503: Cannot find namespace 'Entity'. +tests/cases/conformance/es6/modules/m2.ts(8,8): error TS2339: Property 'x' does not exist on type '() => number'. +tests/cases/conformance/es6/modules/m2.ts(9,8): error TS2339: Property 'y' does not exist on type '() => number'. + + +==== tests/cases/conformance/es6/modules/m1.ts (2 errors) ==== + + export default function Decl() { + ~~~~ +!!! error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. + return 0; + } + + export interface Decl { + p1: number; + p2: number; + } + + export namespace Decl { + ~~~~ +!!! error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. + export var x = 10; + export var y = 20; + + interface I { + } + } + +==== tests/cases/conformance/es6/modules/m2.ts (4 errors) ==== + import Entity from "m1" + + Entity(); + + var x: Entity; + ~~~~~~ +!!! error TS2304: Cannot find name 'Entity'. + var y: Entity.I; + ~~~~~~ +!!! error TS2503: Cannot find namespace 'Entity'. + + Entity.x; + ~ +!!! error TS2339: Property 'x' does not exist on type '() => number'. + Entity.y; + ~ +!!! error TS2339: Property 'y' does not exist on type '() => number'. \ No newline at end of file diff --git a/tests/baselines/reference/defaultExportsCannotMerge01.js b/tests/baselines/reference/defaultExportsCannotMerge01.js new file mode 100644 index 00000000000..99b8ecab1d3 --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge01.js @@ -0,0 +1,50 @@ +//// [tests/cases/conformance/es6/modules/defaultExportsCannotMerge01.ts] //// + +//// [m1.ts] + +export default function Decl() { + return 0; +} + +export interface Decl { + p1: number; + p2: number; +} + +export namespace Decl { + export var x = 10; + export var y = 20; + + interface I { + } +} + +//// [m2.ts] +import Entity from "m1" + +Entity(); + +var x: Entity; +var y: Entity.I; + +Entity.x; +Entity.y; + +//// [m1.js] +function Decl() { + return 0; +} +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Decl; +var Decl; +(function (Decl) { + Decl.x = 10; + Decl.y = 20; +})(Decl = exports.Decl || (exports.Decl = {})); +//// [m2.js] +var m1_1 = require("m1"); +m1_1.default(); +var x; +var y; +m1_1.default.x; +m1_1.default.y; diff --git a/tests/baselines/reference/defaultExportsCannotMerge02.errors.txt b/tests/baselines/reference/defaultExportsCannotMerge02.errors.txt new file mode 100644 index 00000000000..ad9b85c7e94 --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge02.errors.txt @@ -0,0 +1,44 @@ +tests/cases/conformance/es6/modules/m1.ts(2,22): error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. +tests/cases/conformance/es6/modules/m1.ts(5,18): error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. +tests/cases/conformance/es6/modules/m2.ts(3,1): error TS2348: Value of type 'typeof Decl' is not callable. Did you mean to include 'new'? +tests/cases/conformance/es6/modules/m2.ts(6,8): error TS2503: Cannot find namespace 'Entity'. +tests/cases/conformance/es6/modules/m2.ts(8,13): error TS2339: Property 'p1' does not exist on type 'Decl'. +tests/cases/conformance/es6/modules/m2.ts(8,20): error TS2339: Property 'p2' does not exist on type 'Decl'. + + +==== tests/cases/conformance/es6/modules/m1.ts (2 errors) ==== + + export default class Decl { + ~~~~ +!!! error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. + } + + export interface Decl { + ~~~~ +!!! error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. + p1: number; + p2: number; + } + + export namespace Decl { + interface I { + } + } + +==== tests/cases/conformance/es6/modules/m2.ts (4 errors) ==== + import Entity from "m1" + + Entity(); + ~~~~~~~~ +!!! error TS2348: Value of type 'typeof Decl' is not callable. Did you mean to include 'new'? + + var x: Entity; + var y: Entity.I; + ~~~~~~ +!!! error TS2503: Cannot find namespace 'Entity'. + var z = new Entity(); + var sum = z.p1 + z.p2 + ~~ +!!! error TS2339: Property 'p1' does not exist on type 'Decl'. + ~~ +!!! error TS2339: Property 'p2' does not exist on type 'Decl'. \ No newline at end of file diff --git a/tests/baselines/reference/defaultExportsCannotMerge02.js b/tests/baselines/reference/defaultExportsCannotMerge02.js new file mode 100644 index 00000000000..e3897395c74 --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge02.js @@ -0,0 +1,42 @@ +//// [tests/cases/conformance/es6/modules/defaultExportsCannotMerge02.ts] //// + +//// [m1.ts] + +export default class Decl { +} + +export interface Decl { + p1: number; + p2: number; +} + +export namespace Decl { + interface I { + } +} + +//// [m2.ts] +import Entity from "m1" + +Entity(); + +var x: Entity; +var y: Entity.I; +var z = new Entity(); +var sum = z.p1 + z.p2 + +//// [m1.js] +var Decl = (function () { + function Decl() { + } + return Decl; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Decl; +//// [m2.js] +var m1_1 = require("m1"); +m1_1.default(); +var x; +var y; +var z = new m1_1.default(); +var sum = z.p1 + z.p2; diff --git a/tests/baselines/reference/defaultExportsCannotMerge03.errors.txt b/tests/baselines/reference/defaultExportsCannotMerge03.errors.txt new file mode 100644 index 00000000000..b1d405671e3 --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge03.errors.txt @@ -0,0 +1,47 @@ +tests/cases/conformance/es6/modules/m1.ts(2,22): error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. +tests/cases/conformance/es6/modules/m1.ts(5,11): error TS2518: Only an ambient class can be merged with an interface. +tests/cases/conformance/es6/modules/m1.ts(5,11): error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. +tests/cases/conformance/es6/modules/m2.ts(3,1): error TS2348: Value of type 'typeof Decl' is not callable. Did you mean to include 'new'? +tests/cases/conformance/es6/modules/m2.ts(6,8): error TS2503: Cannot find namespace 'Entity'. +tests/cases/conformance/es6/modules/m2.ts(8,13): error TS2339: Property 'p1' does not exist on type 'Decl'. +tests/cases/conformance/es6/modules/m2.ts(8,20): error TS2339: Property 'p2' does not exist on type 'Decl'. + + +==== tests/cases/conformance/es6/modules/m1.ts (3 errors) ==== + + export default class Decl { + ~~~~ +!!! error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. + } + + interface Decl { + ~~~~ +!!! error TS2518: Only an ambient class can be merged with an interface. + ~~~~ +!!! error TS2652: Merged declaration 'Decl' cannot include a default export declaration. Consider adding a separate 'export default Decl' declaration instead. + p1: number; + p2: number; + } + + namespace Decl { + interface I { + } + } + +==== tests/cases/conformance/es6/modules/m2.ts (4 errors) ==== + import Entity from "m1" + + Entity(); + ~~~~~~~~ +!!! error TS2348: Value of type 'typeof Decl' is not callable. Did you mean to include 'new'? + + var x: Entity; + var y: Entity.I; + ~~~~~~ +!!! error TS2503: Cannot find namespace 'Entity'. + var z = new Entity(); + var sum = z.p1 + z.p2 + ~~ +!!! error TS2339: Property 'p1' does not exist on type 'Decl'. + ~~ +!!! error TS2339: Property 'p2' does not exist on type 'Decl'. \ No newline at end of file diff --git a/tests/baselines/reference/defaultExportsCannotMerge03.js b/tests/baselines/reference/defaultExportsCannotMerge03.js new file mode 100644 index 00000000000..05e7de94120 --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge03.js @@ -0,0 +1,42 @@ +//// [tests/cases/conformance/es6/modules/defaultExportsCannotMerge03.ts] //// + +//// [m1.ts] + +export default class Decl { +} + +interface Decl { + p1: number; + p2: number; +} + +namespace Decl { + interface I { + } +} + +//// [m2.ts] +import Entity from "m1" + +Entity(); + +var x: Entity; +var y: Entity.I; +var z = new Entity(); +var sum = z.p1 + z.p2 + +//// [m1.js] +var Decl = (function () { + function Decl() { + } + return Decl; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Decl; +//// [m2.js] +var m1_1 = require("m1"); +m1_1.default(); +var x; +var y; +var z = new m1_1.default(); +var sum = z.p1 + z.p2; diff --git a/tests/baselines/reference/defaultExportsCannotMerge04.errors.txt b/tests/baselines/reference/defaultExportsCannotMerge04.errors.txt new file mode 100644 index 00000000000..000a9b8f30e --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge04.errors.txt @@ -0,0 +1,28 @@ +tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts(2,25): error TS2652: Merged declaration 'Foo' cannot include a default export declaration. Consider adding a separate 'export default Foo' declaration instead. +tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts(5,11): error TS2652: Merged declaration 'Foo' cannot include a default export declaration. Consider adding a separate 'export default Foo' declaration instead. +tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts(9,11): error TS2395: Individual declarations in merged declaration 'Foo' must be all exported or all local. +tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts(12,18): error TS2395: Individual declarations in merged declaration 'Foo' must be all exported or all local. + + +==== tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts (4 errors) ==== + + export default function Foo() { + ~~~ +!!! error TS2652: Merged declaration 'Foo' cannot include a default export declaration. Consider adding a separate 'export default Foo' declaration instead. + } + + namespace Foo { + ~~~ +!!! error TS2652: Merged declaration 'Foo' cannot include a default export declaration. Consider adding a separate 'export default Foo' declaration instead. + export var x; + } + + interface Foo { + ~~~ +!!! error TS2395: Individual declarations in merged declaration 'Foo' must be all exported or all local. + } + + export interface Foo { + ~~~ +!!! error TS2395: Individual declarations in merged declaration 'Foo' must be all exported or all local. + } \ No newline at end of file diff --git a/tests/baselines/reference/defaultExportsCannotMerge04.js b/tests/baselines/reference/defaultExportsCannotMerge04.js new file mode 100644 index 00000000000..eb1122a8197 --- /dev/null +++ b/tests/baselines/reference/defaultExportsCannotMerge04.js @@ -0,0 +1,23 @@ +//// [defaultExportsCannotMerge04.ts] + +export default function Foo() { +} + +namespace Foo { + export var x; +} + +interface Foo { +} + +export interface Foo { +} + +//// [defaultExportsCannotMerge04.js] +function Foo() { +} +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = Foo; +var Foo; +(function (Foo) { +})(Foo || (Foo = {})); diff --git a/tests/baselines/reference/duplicateSymbolsExportMatching.errors.txt b/tests/baselines/reference/duplicateSymbolsExportMatching.errors.txt index df4f8f13c31..85dd29b78a3 100644 --- a/tests/baselines/reference/duplicateSymbolsExportMatching.errors.txt +++ b/tests/baselines/reference/duplicateSymbolsExportMatching.errors.txt @@ -1,21 +1,21 @@ -tests/cases/compiler/duplicateSymbolsExportMatching.ts(24,15): error TS2395: Individual declarations in merged declaration I must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(25,22): error TS2395: Individual declarations in merged declaration I must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(26,22): error TS2395: Individual declarations in merged declaration E must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(27,15): error TS2395: Individual declarations in merged declaration E must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(32,12): error TS2395: Individual declarations in merged declaration inst must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(35,19): error TS2395: Individual declarations in merged declaration inst must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(42,9): error TS2395: Individual declarations in merged declaration v must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(43,16): error TS2395: Individual declarations in merged declaration v must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(44,9): error TS2395: Individual declarations in merged declaration w must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(45,16): error TS2395: Individual declarations in merged declaration w must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(49,12): error TS2395: Individual declarations in merged declaration F must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(24,15): error TS2395: Individual declarations in merged declaration 'I' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(25,22): error TS2395: Individual declarations in merged declaration 'I' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(26,22): error TS2395: Individual declarations in merged declaration 'E' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(27,15): error TS2395: Individual declarations in merged declaration 'E' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(32,12): error TS2395: Individual declarations in merged declaration 'inst' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(35,19): error TS2395: Individual declarations in merged declaration 'inst' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(42,9): error TS2395: Individual declarations in merged declaration 'v' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(43,16): error TS2395: Individual declarations in merged declaration 'v' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(44,9): error TS2395: Individual declarations in merged declaration 'w' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(45,16): error TS2395: Individual declarations in merged declaration 'w' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(49,12): error TS2395: Individual declarations in merged declaration 'F' must be all exported or all local. tests/cases/compiler/duplicateSymbolsExportMatching.ts(49,12): error TS2434: A namespace declaration cannot be located prior to a class or function with which it is merged -tests/cases/compiler/duplicateSymbolsExportMatching.ts(52,21): error TS2395: Individual declarations in merged declaration F must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(56,11): error TS2395: Individual declarations in merged declaration C must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(57,12): error TS2395: Individual declarations in merged declaration C must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(58,19): error TS2395: Individual declarations in merged declaration C must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(64,11): error TS2395: Individual declarations in merged declaration D must be all exported or all local. -tests/cases/compiler/duplicateSymbolsExportMatching.ts(65,18): error TS2395: Individual declarations in merged declaration D must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(52,21): error TS2395: Individual declarations in merged declaration 'F' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(56,11): error TS2395: Individual declarations in merged declaration 'C' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(57,12): error TS2395: Individual declarations in merged declaration 'C' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(58,19): error TS2395: Individual declarations in merged declaration 'C' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(64,11): error TS2395: Individual declarations in merged declaration 'D' must be all exported or all local. +tests/cases/compiler/duplicateSymbolsExportMatching.ts(65,18): error TS2395: Individual declarations in merged declaration 'D' must be all exported or all local. ==== tests/cases/compiler/duplicateSymbolsExportMatching.ts (18 errors) ==== @@ -44,28 +44,28 @@ tests/cases/compiler/duplicateSymbolsExportMatching.ts(65,18): error TS2395: Ind module N2 { interface I { } ~ -!!! error TS2395: Individual declarations in merged declaration I must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'I' must be all exported or all local. export interface I { } // error ~ -!!! error TS2395: Individual declarations in merged declaration I must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'I' must be all exported or all local. export interface E { } ~ -!!! error TS2395: Individual declarations in merged declaration E must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'E' must be all exported or all local. interface E { } // error ~ -!!! error TS2395: Individual declarations in merged declaration E must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'E' must be all exported or all local. } // Should report error only once for instantiated module module M { module inst { ~~~~ -!!! error TS2395: Individual declarations in merged declaration inst must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'inst' must be all exported or all local. var t; } export module inst { // one error ~~~~ -!!! error TS2395: Individual declarations in merged declaration inst must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'inst' must be all exported or all local. var t; } } @@ -74,41 +74,41 @@ tests/cases/compiler/duplicateSymbolsExportMatching.ts(65,18): error TS2395: Ind module M2 { var v: string; ~ -!!! error TS2395: Individual declarations in merged declaration v must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'v' must be all exported or all local. export var v: string; // one error (visibility) ~ -!!! error TS2395: Individual declarations in merged declaration v must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'v' must be all exported or all local. var w: number; ~ -!!! error TS2395: Individual declarations in merged declaration w must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'w' must be all exported or all local. export var w: string; // two errors (visibility and type mismatch) ~ -!!! error TS2395: Individual declarations in merged declaration w must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'w' must be all exported or all local. } module M { module F { ~ -!!! error TS2395: Individual declarations in merged declaration F must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'F' must be all exported or all local. ~ !!! error TS2434: A namespace declaration cannot be located prior to a class or function with which it is merged var t; } export function F() { } // Only one error for duplicate identifier (don't consider visibility) ~ -!!! error TS2395: Individual declarations in merged declaration F must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'F' must be all exported or all local. } module M { class C { } ~ -!!! error TS2395: Individual declarations in merged declaration C must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'C' must be all exported or all local. module C { } ~ -!!! error TS2395: Individual declarations in merged declaration C must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'C' must be all exported or all local. export module C { // Two visibility errors (one for the clodule symbol, and one for the merged container symbol) ~ -!!! error TS2395: Individual declarations in merged declaration C must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'C' must be all exported or all local. var t; } } @@ -116,7 +116,7 @@ tests/cases/compiler/duplicateSymbolsExportMatching.ts(65,18): error TS2395: Ind // Top level interface D { } ~ -!!! error TS2395: Individual declarations in merged declaration D must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'D' must be all exported or all local. export interface D { } ~ -!!! error TS2395: Individual declarations in merged declaration D must be all exported or all local. \ No newline at end of file +!!! error TS2395: Individual declarations in merged declaration 'D' must be all exported or all local. \ No newline at end of file diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.errors.txt b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.errors.txt index 5934ab52ccf..b32a7b67b61 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.errors.txt +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.errors.txt @@ -1,10 +1,9 @@ tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts(1,9): error TS1016: A required parameter cannot follow an optional parameter. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts(2,8): error TS1047: A rest parameter cannot be optional. tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts(4,5): error TS1048: A rest parameter cannot have an initializer. -tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts(7,12): error TS1016: A required parameter cannot follow an optional parameter. -==== tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts (4 errors) ==== +==== tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts (3 errors) ==== (arg1?, arg2) => 101; ~~~~ !!! error TS1016: A required parameter cannot follow an optional parameter. @@ -16,7 +15,5 @@ tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts(7,12): error TS1016 ~~~ !!! error TS1048: A rest parameter cannot have an initializer. - // Non optional parameter following an optional one - (arg1 = 1, arg2) => 1; - ~~~~ -!!! error TS1016: A required parameter cannot follow an optional parameter. \ No newline at end of file + // Uninitialized parameter makes the initialized one required + (arg1 = 1, arg2) => 1; \ No newline at end of file diff --git a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js index e746b24a066..4d27f8230eb 100644 --- a/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js +++ b/tests/baselines/reference/fatarrowfunctionsOptionalArgsErrors1.js @@ -4,7 +4,7 @@ (...arg) => 103; (...arg:number [] = []) => 104; -// Non optional parameter following an optional one +// Uninitialized parameter makes the initialized one required (arg1 = 1, arg2) => 1; //// [fatarrowfunctionsOptionalArgsErrors1.js] @@ -30,7 +30,7 @@ } return 104; }); -// Non optional parameter following an optional one +// Uninitialized parameter makes the initialized one required (function (arg1, arg2) { if (arg1 === void 0) { arg1 = 1; } return 1; diff --git a/tests/baselines/reference/inferentialTypingUsingApparentType2.types b/tests/baselines/reference/inferentialTypingUsingApparentType2.types index 597f5885f5a..5841e021c3a 100644 --- a/tests/baselines/reference/inferentialTypingUsingApparentType2.types +++ b/tests/baselines/reference/inferentialTypingUsingApparentType2.types @@ -13,7 +13,7 @@ function foo(x: T): T { } foo({ m(x) { return x.length } }); ->foo({ m(x) { return x.length } }) : { } +>foo({ m(x) { return x.length } }) : { m(x: string): number; } >foo : (x: T) => T >{ m(x) { return x.length } } : { m(x: string): number; } >m : (x: string) => number diff --git a/tests/baselines/reference/inferringAnyFunctionType1.js b/tests/baselines/reference/inferringAnyFunctionType1.js new file mode 100644 index 00000000000..6b48cf2db58 --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType1.js @@ -0,0 +1,12 @@ +//// [inferringAnyFunctionType1.ts] +function f number }>(p: T): T { + return p; +} + +var v = f([x => x]); + +//// [inferringAnyFunctionType1.js] +function f(p) { + return p; +} +var v = f([function (x) { return x; }]); diff --git a/tests/baselines/reference/inferringAnyFunctionType1.symbols b/tests/baselines/reference/inferringAnyFunctionType1.symbols new file mode 100644 index 00000000000..6a43952d770 --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType1.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/inferringAnyFunctionType1.ts === +function f number }>(p: T): T { +>f : Symbol(f, Decl(inferringAnyFunctionType1.ts, 0, 0)) +>T : Symbol(T, Decl(inferringAnyFunctionType1.ts, 0, 11)) +>p1 : Symbol(p1, Decl(inferringAnyFunctionType1.ts, 0, 29)) +>p : Symbol(p, Decl(inferringAnyFunctionType1.ts, 0, 54)) +>T : Symbol(T, Decl(inferringAnyFunctionType1.ts, 0, 11)) +>T : Symbol(T, Decl(inferringAnyFunctionType1.ts, 0, 11)) + + return p; +>p : Symbol(p, Decl(inferringAnyFunctionType1.ts, 0, 54)) +} + +var v = f([x => x]); +>v : Symbol(v, Decl(inferringAnyFunctionType1.ts, 4, 3)) +>f : Symbol(f, Decl(inferringAnyFunctionType1.ts, 0, 0)) +>x : Symbol(x, Decl(inferringAnyFunctionType1.ts, 4, 11)) +>x : Symbol(x, Decl(inferringAnyFunctionType1.ts, 4, 11)) + diff --git a/tests/baselines/reference/inferringAnyFunctionType1.types b/tests/baselines/reference/inferringAnyFunctionType1.types new file mode 100644 index 00000000000..16402cc3ced --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType1.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/inferringAnyFunctionType1.ts === +function f number }>(p: T): T { +>f : number; }>(p: T) => T +>T : T +>p1 : number +>p : T +>T : T +>T : T + + return p; +>p : T +} + +var v = f([x => x]); +>v : [(x: number) => number] +>f([x => x]) : [(x: number) => number] +>f : number; }>(p: T) => T +>[x => x] : [(x: number) => number] +>x => x : (x: number) => number +>x : number +>x : number + diff --git a/tests/baselines/reference/inferringAnyFunctionType2.js b/tests/baselines/reference/inferringAnyFunctionType2.js new file mode 100644 index 00000000000..3841793233e --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType2.js @@ -0,0 +1,12 @@ +//// [inferringAnyFunctionType2.ts] +function f number]>(p: T): T { + return p; +} + +var v = f([x => x]); + +//// [inferringAnyFunctionType2.js] +function f(p) { + return p; +} +var v = f([function (x) { return x; }]); diff --git a/tests/baselines/reference/inferringAnyFunctionType2.symbols b/tests/baselines/reference/inferringAnyFunctionType2.symbols new file mode 100644 index 00000000000..9bdb627d46d --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType2.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/inferringAnyFunctionType2.ts === +function f number]>(p: T): T { +>f : Symbol(f, Decl(inferringAnyFunctionType2.ts, 0, 0)) +>T : Symbol(T, Decl(inferringAnyFunctionType2.ts, 0, 11)) +>p1 : Symbol(p1, Decl(inferringAnyFunctionType2.ts, 0, 23)) +>p : Symbol(p, Decl(inferringAnyFunctionType2.ts, 0, 47)) +>T : Symbol(T, Decl(inferringAnyFunctionType2.ts, 0, 11)) +>T : Symbol(T, Decl(inferringAnyFunctionType2.ts, 0, 11)) + + return p; +>p : Symbol(p, Decl(inferringAnyFunctionType2.ts, 0, 47)) +} + +var v = f([x => x]); +>v : Symbol(v, Decl(inferringAnyFunctionType2.ts, 4, 3)) +>f : Symbol(f, Decl(inferringAnyFunctionType2.ts, 0, 0)) +>x : Symbol(x, Decl(inferringAnyFunctionType2.ts, 4, 11)) +>x : Symbol(x, Decl(inferringAnyFunctionType2.ts, 4, 11)) + diff --git a/tests/baselines/reference/inferringAnyFunctionType2.types b/tests/baselines/reference/inferringAnyFunctionType2.types new file mode 100644 index 00000000000..7884bdfc6ba --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType2.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/inferringAnyFunctionType2.ts === +function f number]>(p: T): T { +>f : number]>(p: T) => T +>T : T +>p1 : number +>p : T +>T : T +>T : T + + return p; +>p : T +} + +var v = f([x => x]); +>v : [(x: number) => number] +>f([x => x]) : [(x: number) => number] +>f : number]>(p: T) => T +>[x => x] : [(x: number) => number] +>x => x : (x: number) => number +>x : number +>x : number + diff --git a/tests/baselines/reference/inferringAnyFunctionType3.js b/tests/baselines/reference/inferringAnyFunctionType3.js new file mode 100644 index 00000000000..ed1c4348dfc --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType3.js @@ -0,0 +1,12 @@ +//// [inferringAnyFunctionType3.ts] +function f number)[]>(p: T): T { + return p; +} + +var v = f([x => x]); + +//// [inferringAnyFunctionType3.js] +function f(p) { + return p; +} +var v = f([function (x) { return x; }]); diff --git a/tests/baselines/reference/inferringAnyFunctionType3.symbols b/tests/baselines/reference/inferringAnyFunctionType3.symbols new file mode 100644 index 00000000000..472d170b81d --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType3.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/inferringAnyFunctionType3.ts === +function f number)[]>(p: T): T { +>f : Symbol(f, Decl(inferringAnyFunctionType3.ts, 0, 0)) +>T : Symbol(T, Decl(inferringAnyFunctionType3.ts, 0, 11)) +>p1 : Symbol(p1, Decl(inferringAnyFunctionType3.ts, 0, 23)) +>p : Symbol(p, Decl(inferringAnyFunctionType3.ts, 0, 49)) +>T : Symbol(T, Decl(inferringAnyFunctionType3.ts, 0, 11)) +>T : Symbol(T, Decl(inferringAnyFunctionType3.ts, 0, 11)) + + return p; +>p : Symbol(p, Decl(inferringAnyFunctionType3.ts, 0, 49)) +} + +var v = f([x => x]); +>v : Symbol(v, Decl(inferringAnyFunctionType3.ts, 4, 3)) +>f : Symbol(f, Decl(inferringAnyFunctionType3.ts, 0, 0)) +>x : Symbol(x, Decl(inferringAnyFunctionType3.ts, 4, 11)) +>x : Symbol(x, Decl(inferringAnyFunctionType3.ts, 4, 11)) + diff --git a/tests/baselines/reference/inferringAnyFunctionType3.types b/tests/baselines/reference/inferringAnyFunctionType3.types new file mode 100644 index 00000000000..1edcfc34643 --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType3.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/inferringAnyFunctionType3.ts === +function f number)[]>(p: T): T { +>f : number)[]>(p: T) => T +>T : T +>p1 : number +>p : T +>T : T +>T : T + + return p; +>p : T +} + +var v = f([x => x]); +>v : ((x: number) => number)[] +>f([x => x]) : ((x: number) => number)[] +>f : number)[]>(p: T) => T +>[x => x] : ((x: number) => number)[] +>x => x : (x: number) => number +>x : number +>x : number + diff --git a/tests/baselines/reference/inferringAnyFunctionType4.js b/tests/baselines/reference/inferringAnyFunctionType4.js new file mode 100644 index 00000000000..dccc51920b0 --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType4.js @@ -0,0 +1,12 @@ +//// [inferringAnyFunctionType4.ts] +function f number>(p: T): T { + return p; +} + +var v = f(x => x); + +//// [inferringAnyFunctionType4.js] +function f(p) { + return p; +} +var v = f(function (x) { return x; }); diff --git a/tests/baselines/reference/inferringAnyFunctionType4.symbols b/tests/baselines/reference/inferringAnyFunctionType4.symbols new file mode 100644 index 00000000000..bfbacfc277c --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType4.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/inferringAnyFunctionType4.ts === +function f number>(p: T): T { +>f : Symbol(f, Decl(inferringAnyFunctionType4.ts, 0, 0)) +>T : Symbol(T, Decl(inferringAnyFunctionType4.ts, 0, 11)) +>p1 : Symbol(p1, Decl(inferringAnyFunctionType4.ts, 0, 22)) +>p : Symbol(p, Decl(inferringAnyFunctionType4.ts, 0, 45)) +>T : Symbol(T, Decl(inferringAnyFunctionType4.ts, 0, 11)) +>T : Symbol(T, Decl(inferringAnyFunctionType4.ts, 0, 11)) + + return p; +>p : Symbol(p, Decl(inferringAnyFunctionType4.ts, 0, 45)) +} + +var v = f(x => x); +>v : Symbol(v, Decl(inferringAnyFunctionType4.ts, 4, 3)) +>f : Symbol(f, Decl(inferringAnyFunctionType4.ts, 0, 0)) +>x : Symbol(x, Decl(inferringAnyFunctionType4.ts, 4, 10)) +>x : Symbol(x, Decl(inferringAnyFunctionType4.ts, 4, 10)) + diff --git a/tests/baselines/reference/inferringAnyFunctionType4.types b/tests/baselines/reference/inferringAnyFunctionType4.types new file mode 100644 index 00000000000..49d46d0433e --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType4.types @@ -0,0 +1,21 @@ +=== tests/cases/compiler/inferringAnyFunctionType4.ts === +function f number>(p: T): T { +>f : number>(p: T) => T +>T : T +>p1 : number +>p : T +>T : T +>T : T + + return p; +>p : T +} + +var v = f(x => x); +>v : (x: number) => number +>f(x => x) : (x: number) => number +>f : number>(p: T) => T +>x => x : (x: number) => number +>x : number +>x : number + diff --git a/tests/baselines/reference/inferringAnyFunctionType5.js b/tests/baselines/reference/inferringAnyFunctionType5.js new file mode 100644 index 00000000000..babbab1be9e --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType5.js @@ -0,0 +1,12 @@ +//// [inferringAnyFunctionType5.ts] +function f number }>(p: T): T { + return p; +} + +var v = f({ q: x => x }); + +//// [inferringAnyFunctionType5.js] +function f(p) { + return p; +} +var v = f({ q: function (x) { return x; } }); diff --git a/tests/baselines/reference/inferringAnyFunctionType5.symbols b/tests/baselines/reference/inferringAnyFunctionType5.symbols new file mode 100644 index 00000000000..abf0fe68f46 --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType5.symbols @@ -0,0 +1,21 @@ +=== tests/cases/compiler/inferringAnyFunctionType5.ts === +function f number }>(p: T): T { +>f : Symbol(f, Decl(inferringAnyFunctionType5.ts, 0, 0)) +>T : Symbol(T, Decl(inferringAnyFunctionType5.ts, 0, 11)) +>q : Symbol(q, Decl(inferringAnyFunctionType5.ts, 0, 22)) +>p1 : Symbol(p1, Decl(inferringAnyFunctionType5.ts, 0, 27)) +>p : Symbol(p, Decl(inferringAnyFunctionType5.ts, 0, 52)) +>T : Symbol(T, Decl(inferringAnyFunctionType5.ts, 0, 11)) +>T : Symbol(T, Decl(inferringAnyFunctionType5.ts, 0, 11)) + + return p; +>p : Symbol(p, Decl(inferringAnyFunctionType5.ts, 0, 52)) +} + +var v = f({ q: x => x }); +>v : Symbol(v, Decl(inferringAnyFunctionType5.ts, 4, 3)) +>f : Symbol(f, Decl(inferringAnyFunctionType5.ts, 0, 0)) +>q : Symbol(q, Decl(inferringAnyFunctionType5.ts, 4, 11)) +>x : Symbol(x, Decl(inferringAnyFunctionType5.ts, 4, 14)) +>x : Symbol(x, Decl(inferringAnyFunctionType5.ts, 4, 14)) + diff --git a/tests/baselines/reference/inferringAnyFunctionType5.types b/tests/baselines/reference/inferringAnyFunctionType5.types new file mode 100644 index 00000000000..8f7ae123eac --- /dev/null +++ b/tests/baselines/reference/inferringAnyFunctionType5.types @@ -0,0 +1,24 @@ +=== tests/cases/compiler/inferringAnyFunctionType5.ts === +function f number }>(p: T): T { +>f : number; }>(p: T) => T +>T : T +>q : (p1: number) => number +>p1 : number +>p : T +>T : T +>T : T + + return p; +>p : T +} + +var v = f({ q: x => x }); +>v : { q: (x: number) => number; } +>f({ q: x => x }) : { q: (x: number) => number; } +>f : number; }>(p: T) => T +>{ q: x => x } : { q: (x: number) => number; } +>q : (x: number) => number +>x => x : (x: number) => number +>x : number +>x : number + diff --git a/tests/baselines/reference/innerModExport2.errors.txt b/tests/baselines/reference/innerModExport2.errors.txt index 52a9d01c997..f9568bb45a4 100644 --- a/tests/baselines/reference/innerModExport2.errors.txt +++ b/tests/baselines/reference/innerModExport2.errors.txt @@ -1,7 +1,7 @@ tests/cases/compiler/innerModExport2.ts(5,5): error TS2304: Cannot find name 'module'. tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected. -tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. -tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. +tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. +tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExportFunc' does not exist on type 'typeof Outer'. @@ -18,7 +18,7 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport var non_export_var = 0; export var export_var = 1; ~~~~~~~~~~ -!!! error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. function NonExportFunc() { return 0; } @@ -26,7 +26,7 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport } var export_var: number; ~~~~~~~~~~ -!!! error TS2395: Individual declarations in merged declaration export_var must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'export_var' must be all exported or all local. export var outer_var_export = 0; export function outerFuncExport() { return 0; } diff --git a/tests/baselines/reference/isolatedModulesSourceMap.errors.txt b/tests/baselines/reference/isolatedModulesSourceMap.errors.txt deleted file mode 100644 index 6383e85ecd5..00000000000 --- a/tests/baselines/reference/isolatedModulesSourceMap.errors.txt +++ /dev/null @@ -1,7 +0,0 @@ -error TS5043: Option 'sourceMap' cannot be specified with option 'isolatedModules'. - - -!!! error TS5043: Option 'sourceMap' cannot be specified with option 'isolatedModules'. -==== tests/cases/compiler/isolatedModulesSourceMap.ts (0 errors) ==== - - export var x; \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesSourceMap.js b/tests/baselines/reference/isolatedModulesSourceMap.js index ca6f4b4190e..2722a3ce7ab 100644 --- a/tests/baselines/reference/isolatedModulesSourceMap.js +++ b/tests/baselines/reference/isolatedModulesSourceMap.js @@ -1,7 +1,7 @@ //// [isolatedModulesSourceMap.ts] -export var x; +export var x = 1; //// [isolatedModulesSourceMap.js] -export var x; +export var x = 1; //# sourceMappingURL=isolatedModulesSourceMap.js.map \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesSourceMap.js.map b/tests/baselines/reference/isolatedModulesSourceMap.js.map index 8e505dcda7a..9fa3e0da0d6 100644 --- a/tests/baselines/reference/isolatedModulesSourceMap.js.map +++ b/tests/baselines/reference/isolatedModulesSourceMap.js.map @@ -1,2 +1,2 @@ //// [isolatedModulesSourceMap.js.map] -{"version":3,"file":"isolatedModulesSourceMap.js","sourceRoot":"","sources":["isolatedModulesSourceMap.ts"],"names":[],"mappings":"AACA,WAAW,CAAC,CAAC"} \ No newline at end of file +{"version":3,"file":"isolatedModulesSourceMap.js","sourceRoot":"","sources":["isolatedModulesSourceMap.ts"],"names":[],"mappings":"AACA,WAAW,CAAC,GAAG,CAAC,CAAC"} \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesSourceMap.sourcemap.txt b/tests/baselines/reference/isolatedModulesSourceMap.sourcemap.txt index 5c6b7659bc6..d31445505f7 100644 --- a/tests/baselines/reference/isolatedModulesSourceMap.sourcemap.txt +++ b/tests/baselines/reference/isolatedModulesSourceMap.sourcemap.txt @@ -8,20 +8,26 @@ sources: isolatedModulesSourceMap.ts emittedFile:tests/cases/compiler/isolatedModulesSourceMap.js sourceFile:isolatedModulesSourceMap.ts ------------------------------------------------------------------- ->>>export var x; +>>>export var x = 1; 1 > 2 >^^^^^^^^^^^ 3 > ^ -4 > ^ -5 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +4 > ^^^ +5 > ^ +6 > ^ +7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> 1 > > 2 >export var 3 > x -4 > ; +4 > = +5 > 1 +6 > ; 1 >Emitted(1, 1) Source(2, 1) + SourceIndex(0) 2 >Emitted(1, 12) Source(2, 12) + SourceIndex(0) 3 >Emitted(1, 13) Source(2, 13) + SourceIndex(0) -4 >Emitted(1, 14) Source(2, 14) + SourceIndex(0) +4 >Emitted(1, 16) Source(2, 16) + SourceIndex(0) +5 >Emitted(1, 17) Source(2, 17) + SourceIndex(0) +6 >Emitted(1, 18) Source(2, 18) + SourceIndex(0) --- >>>//# sourceMappingURL=isolatedModulesSourceMap.js.map \ No newline at end of file diff --git a/tests/baselines/reference/isolatedModulesSourceMap.symbols b/tests/baselines/reference/isolatedModulesSourceMap.symbols new file mode 100644 index 00000000000..d4ae3c34cf1 --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSourceMap.symbols @@ -0,0 +1,5 @@ +=== tests/cases/compiler/isolatedModulesSourceMap.ts === + +export var x = 1; +>x : Symbol(x, Decl(isolatedModulesSourceMap.ts, 1, 10)) + diff --git a/tests/baselines/reference/isolatedModulesSourceMap.types b/tests/baselines/reference/isolatedModulesSourceMap.types new file mode 100644 index 00000000000..1955fe5da6e --- /dev/null +++ b/tests/baselines/reference/isolatedModulesSourceMap.types @@ -0,0 +1,6 @@ +=== tests/cases/compiler/isolatedModulesSourceMap.ts === + +export var x = 1; +>x : number +>1 : number + diff --git a/tests/baselines/reference/jsxImportInAttribute.js b/tests/baselines/reference/jsxImportInAttribute.js new file mode 100644 index 00000000000..40b21e87c3f --- /dev/null +++ b/tests/baselines/reference/jsxImportInAttribute.js @@ -0,0 +1,21 @@ +//// [tests/cases/compiler/jsxImportInAttribute.tsx] //// + +//// [component.d.ts] + +declare module "Test" { + export default class Text { } +} + +//// [consumer.tsx] +/// +import Test from 'Test'; + +let x = Test; // emit test_1.default +; // ? + + +//// [consumer.jsx] +/// +var Test_1 = require('Test'); +var x = Test_1["default"]; // emit test_1.default +; // ? diff --git a/tests/baselines/reference/jsxImportInAttribute.symbols b/tests/baselines/reference/jsxImportInAttribute.symbols new file mode 100644 index 00000000000..8481771f085 --- /dev/null +++ b/tests/baselines/reference/jsxImportInAttribute.symbols @@ -0,0 +1,19 @@ +=== tests/cases/compiler/consumer.tsx === +/// +import Test from 'Test'; +>Test : Symbol(Test, Decl(consumer.tsx, 1, 6)) + +let x = Test; // emit test_1.default +>x : Symbol(x, Decl(consumer.tsx, 3, 3)) +>Test : Symbol(Test, Decl(consumer.tsx, 1, 6)) + +; // ? +>attr : Symbol(unknown) + +=== tests/cases/compiler/component.d.ts === + +declare module "Test" { + export default class Text { } +>Text : Symbol(Text, Decl(component.d.ts, 1, 23)) +} + diff --git a/tests/baselines/reference/jsxImportInAttribute.types b/tests/baselines/reference/jsxImportInAttribute.types new file mode 100644 index 00000000000..8dfbe292fe0 --- /dev/null +++ b/tests/baselines/reference/jsxImportInAttribute.types @@ -0,0 +1,22 @@ +=== tests/cases/compiler/consumer.tsx === +/// +import Test from 'Test'; +>Test : typeof Test + +let x = Test; // emit test_1.default +>x : typeof Test +>Test : typeof Test + +; // ? +> : any +>anything : any +>attr : any +>Test : any + +=== tests/cases/compiler/component.d.ts === + +declare module "Test" { + export default class Text { } +>Text : Text +} + diff --git a/tests/baselines/reference/jsxViaImport.errors.txt b/tests/baselines/reference/jsxViaImport.errors.txt new file mode 100644 index 00000000000..8fa22809a44 --- /dev/null +++ b/tests/baselines/reference/jsxViaImport.errors.txt @@ -0,0 +1,27 @@ +tests/cases/compiler/consumer.tsx(5,17): error TS2604: JSX element type 'BaseComponent' does not have any construct or call signatures. + + +==== tests/cases/compiler/consumer.tsx (1 errors) ==== + /// + import BaseComponent = require('BaseComponent'); + class TestComponent extends React.Component { + render() { + return ; + ~~~~~~~~~~~~~ +!!! error TS2604: JSX element type 'BaseComponent' does not have any construct or call signatures. + } + } + +==== tests/cases/compiler/component.d.ts (0 errors) ==== + + declare module JSX { + interface ElementAttributesProperty { props; } + } + declare module React { + class Component { } + } + declare module "BaseComponent" { + var base: React.Component; + export = base; + } + \ No newline at end of file diff --git a/tests/baselines/reference/jsxViaImport.js b/tests/baselines/reference/jsxViaImport.js new file mode 100644 index 00000000000..6bf61af67f5 --- /dev/null +++ b/tests/baselines/reference/jsxViaImport.js @@ -0,0 +1,43 @@ +//// [tests/cases/compiler/jsxViaImport.tsx] //// + +//// [component.d.ts] + +declare module JSX { + interface ElementAttributesProperty { props; } +} +declare module React { + class Component { } +} +declare module "BaseComponent" { + var base: React.Component; + export = base; +} + +//// [consumer.tsx] +/// +import BaseComponent = require('BaseComponent'); +class TestComponent extends React.Component { + render() { + return ; + } +} + + +//// [consumer.jsx] +var __extends = (this && this.__extends) || function (d, b) { + for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +}; +/// +var BaseComponent = require('BaseComponent'); +var TestComponent = (function (_super) { + __extends(TestComponent, _super); + function TestComponent() { + _super.apply(this, arguments); + } + TestComponent.prototype.render = function () { + return ; + }; + return TestComponent; +})(React.Component); diff --git a/tests/baselines/reference/multipleDefaultExports01.errors.txt b/tests/baselines/reference/multipleDefaultExports01.errors.txt new file mode 100644 index 00000000000..7b49afe1a4e --- /dev/null +++ b/tests/baselines/reference/multipleDefaultExports01.errors.txt @@ -0,0 +1,31 @@ +tests/cases/conformance/es6/modules/m1.ts(2,22): error TS2300: Duplicate identifier 'foo'. +tests/cases/conformance/es6/modules/m1.ts(6,25): error TS2300: Duplicate identifier 'bar'. +tests/cases/conformance/es6/modules/m1.ts(11,1): error TS2300: Duplicate identifier 'default'. +tests/cases/conformance/es6/modules/m2.ts(3,1): error TS2348: Value of type 'typeof foo' is not callable. Did you mean to include 'new'? + + +==== tests/cases/conformance/es6/modules/m1.ts (3 errors) ==== + + export default class foo { + ~~~ +!!! error TS2300: Duplicate identifier 'foo'. + + } + + export default function bar() { + ~~~ +!!! error TS2300: Duplicate identifier 'bar'. + + } + + var x = 10; + export default x; + ~~~~~~~~~~~~~~~~~ +!!! error TS2300: Duplicate identifier 'default'. + +==== tests/cases/conformance/es6/modules/m2.ts (1 errors) ==== + import Entity from "m1" + + Entity(); + ~~~~~~~~ +!!! error TS2348: Value of type 'typeof foo' is not callable. Did you mean to include 'new'? \ No newline at end of file diff --git a/tests/baselines/reference/multipleDefaultExports01.js b/tests/baselines/reference/multipleDefaultExports01.js new file mode 100644 index 00000000000..e633cf69f55 --- /dev/null +++ b/tests/baselines/reference/multipleDefaultExports01.js @@ -0,0 +1,38 @@ +//// [tests/cases/conformance/es6/modules/multipleDefaultExports01.ts] //// + +//// [m1.ts] + +export default class foo { + +} + +export default function bar() { + +} + +var x = 10; +export default x; + +//// [m2.ts] +import Entity from "m1" + +Entity(); + +//// [m1.js] +var foo = (function () { + function foo() { + } + return foo; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = foo; +function bar() { +} +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = bar; +var x = 10; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = x; +//// [m2.js] +var m1_1 = require("m1"); +m1_1.default(); diff --git a/tests/baselines/reference/multipleDefaultExports02.errors.txt b/tests/baselines/reference/multipleDefaultExports02.errors.txt new file mode 100644 index 00000000000..51220ecfae2 --- /dev/null +++ b/tests/baselines/reference/multipleDefaultExports02.errors.txt @@ -0,0 +1,22 @@ +tests/cases/conformance/es6/modules/m1.ts(2,25): error TS2393: Duplicate function implementation. +tests/cases/conformance/es6/modules/m1.ts(6,25): error TS2393: Duplicate function implementation. + + +==== tests/cases/conformance/es6/modules/m1.ts (2 errors) ==== + + export default function foo() { + ~~~ +!!! error TS2393: Duplicate function implementation. + + } + + export default function bar() { + ~~~ +!!! error TS2393: Duplicate function implementation. + + } + +==== tests/cases/conformance/es6/modules/m2.ts (0 errors) ==== + import Entity from "m1" + + Entity(); \ No newline at end of file diff --git a/tests/baselines/reference/multipleDefaultExports02.js b/tests/baselines/reference/multipleDefaultExports02.js new file mode 100644 index 00000000000..3d1b84ff6a6 --- /dev/null +++ b/tests/baselines/reference/multipleDefaultExports02.js @@ -0,0 +1,29 @@ +//// [tests/cases/conformance/es6/modules/multipleDefaultExports02.ts] //// + +//// [m1.ts] + +export default function foo() { + +} + +export default function bar() { + +} + +//// [m2.ts] +import Entity from "m1" + +Entity(); + +//// [m1.js] +function foo() { +} +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = foo; +function bar() { +} +Object.defineProperty(exports, "__esModule", { value: true }); +exports.default = bar; +//// [m2.js] +var m1_1 = require("m1"); +m1_1.default(); diff --git a/tests/baselines/reference/multivar.errors.txt b/tests/baselines/reference/multivar.errors.txt index 931e61de5ae..44061b9d74c 100644 --- a/tests/baselines/reference/multivar.errors.txt +++ b/tests/baselines/reference/multivar.errors.txt @@ -1,5 +1,5 @@ -tests/cases/compiler/multivar.ts(6,19): error TS2395: Individual declarations in merged declaration b2 must be all exported or all local. -tests/cases/compiler/multivar.ts(22,9): error TS2395: Individual declarations in merged declaration b2 must be all exported or all local. +tests/cases/compiler/multivar.ts(6,19): error TS2395: Individual declarations in merged declaration 'b2' must be all exported or all local. +tests/cases/compiler/multivar.ts(22,9): error TS2395: Individual declarations in merged declaration 'b2' must be all exported or all local. ==== tests/cases/compiler/multivar.ts (2 errors) ==== @@ -10,7 +10,7 @@ tests/cases/compiler/multivar.ts(22,9): error TS2395: Individual declarations in export var a, b2: number = 10, b; ~~ -!!! error TS2395: Individual declarations in merged declaration b2 must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'b2' must be all exported or all local. var m1; var a2, b22: number = 10, b222; var m3; @@ -28,7 +28,7 @@ tests/cases/compiler/multivar.ts(22,9): error TS2395: Individual declarations in declare var d1, d2; var b2; ~~ -!!! error TS2395: Individual declarations in merged declaration b2 must be all exported or all local. +!!! error TS2395: Individual declarations in merged declaration 'b2' must be all exported or all local. declare var v1; } diff --git a/tests/baselines/reference/optionalParamArgsTest.errors.txt b/tests/baselines/reference/optionalParamArgsTest.errors.txt index 3c4d2e37be9..05fefa85065 100644 --- a/tests/baselines/reference/optionalParamArgsTest.errors.txt +++ b/tests/baselines/reference/optionalParamArgsTest.errors.txt @@ -1,6 +1,6 @@ tests/cases/compiler/optionalParamArgsTest.ts(31,12): error TS2393: Duplicate function implementation. -tests/cases/compiler/optionalParamArgsTest.ts(35,12): error TS2393: Duplicate function implementation. -tests/cases/compiler/optionalParamArgsTest.ts(35,47): error TS1016: A required parameter cannot follow an optional parameter. +tests/cases/compiler/optionalParamArgsTest.ts(34,12): error TS2393: Duplicate function implementation. +tests/cases/compiler/optionalParamArgsTest.ts(98,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/optionalParamArgsTest.ts(99,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/optionalParamArgsTest.ts(100,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/optionalParamArgsTest.ts(101,1): error TS2346: Supplied parameters do not match any signature of call target. @@ -20,10 +20,9 @@ tests/cases/compiler/optionalParamArgsTest.ts(114,1): error TS2346: Supplied par tests/cases/compiler/optionalParamArgsTest.ts(115,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/optionalParamArgsTest.ts(116,1): error TS2346: Supplied parameters do not match any signature of call target. tests/cases/compiler/optionalParamArgsTest.ts(117,1): error TS2346: Supplied parameters do not match any signature of call target. -tests/cases/compiler/optionalParamArgsTest.ts(118,1): error TS2346: Supplied parameters do not match any signature of call target. -==== tests/cases/compiler/optionalParamArgsTest.ts (23 errors) ==== +==== tests/cases/compiler/optionalParamArgsTest.ts (22 errors) ==== // Optional parameter and default argument tests // Key: @@ -58,13 +57,10 @@ tests/cases/compiler/optionalParamArgsTest.ts(118,1): error TS2346: Supplied par ~~~~ !!! error TS2393: Duplicate function implementation. - // Negative test - // "Optional parameters may only be followed by other optional parameters" + // Uninitialized parameter makes the initialized one required public C1M5(C1M5A1:number,C1M5A2:number=0,C1M5A3:number) { return C1M5A1 + C1M5A2; } ~~~~ !!! error TS2393: Duplicate function implementation. - ~~~~~~ -!!! error TS1016: A required parameter cannot follow an optional parameter. } class C2 extends C1 { diff --git a/tests/baselines/reference/optionalParamArgsTest.js b/tests/baselines/reference/optionalParamArgsTest.js index 414f474598d..0c5a5d82814 100644 --- a/tests/baselines/reference/optionalParamArgsTest.js +++ b/tests/baselines/reference/optionalParamArgsTest.js @@ -31,8 +31,7 @@ class C1 { public C1M5(C1M5A1:number,C1M5A2:number=0,C1M5A3?:number) { return C1M5A1 + C1M5A2; } - // Negative test - // "Optional parameters may only be followed by other optional parameters" + // Uninitialized parameter makes the initialized one required public C1M5(C1M5A1:number,C1M5A2:number=0,C1M5A3:number) { return C1M5A1 + C1M5A2; } } @@ -152,8 +151,7 @@ var C1 = (function () { if (C1M5A2 === void 0) { C1M5A2 = 0; } return C1M5A1 + C1M5A2; }; - // Negative test - // "Optional parameters may only be followed by other optional parameters" + // Uninitialized parameter makes the initialized one required C1.prototype.C1M5 = function (C1M5A1, C1M5A2, C1M5A3) { if (C1M5A2 === void 0) { C1M5A2 = 0; } return C1M5A1 + C1M5A2; diff --git a/tests/baselines/reference/requiredInitializedParameter1.errors.txt b/tests/baselines/reference/requiredInitializedParameter1.errors.txt new file mode 100644 index 00000000000..ef958dbdec9 --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter1.errors.txt @@ -0,0 +1,28 @@ +tests/cases/compiler/requiredInitializedParameter1.ts(11,1): error TS2346: Supplied parameters do not match any signature of call target. +tests/cases/compiler/requiredInitializedParameter1.ts(16,1): error TS2346: Supplied parameters do not match any signature of call target. + + +==== tests/cases/compiler/requiredInitializedParameter1.ts (2 errors) ==== + function f1(a, b = 0, c) { } + function f2(a, b = 0, c = 0) { } + function f3(a, b = 0, c?) { } + function f4(a, b = 0, ...c) { } + + f1(0, 1, 2); + f2(0, 1, 2); + f3(0, 1, 2); + f4(0, 1, 2); + + f1(0, 1); + ~~~~~~~~ +!!! error TS2346: Supplied parameters do not match any signature of call target. + f2(0, 1); + f3(0, 1); + f4(0, 1); + + f1(0); + ~~~~~ +!!! error TS2346: Supplied parameters do not match any signature of call target. + f2(0); + f3(0); + f4(0); \ No newline at end of file diff --git a/tests/baselines/reference/requiredInitializedParameter1.js b/tests/baselines/reference/requiredInitializedParameter1.js new file mode 100644 index 00000000000..0fe07503056 --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter1.js @@ -0,0 +1,51 @@ +//// [requiredInitializedParameter1.ts] +function f1(a, b = 0, c) { } +function f2(a, b = 0, c = 0) { } +function f3(a, b = 0, c?) { } +function f4(a, b = 0, ...c) { } + +f1(0, 1, 2); +f2(0, 1, 2); +f3(0, 1, 2); +f4(0, 1, 2); + +f1(0, 1); +f2(0, 1); +f3(0, 1); +f4(0, 1); + +f1(0); +f2(0); +f3(0); +f4(0); + +//// [requiredInitializedParameter1.js] +function f1(a, b, c) { + if (b === void 0) { b = 0; } +} +function f2(a, b, c) { + if (b === void 0) { b = 0; } + if (c === void 0) { c = 0; } +} +function f3(a, b, c) { + if (b === void 0) { b = 0; } +} +function f4(a, b) { + if (b === void 0) { b = 0; } + var c = []; + for (var _i = 2; _i < arguments.length; _i++) { + c[_i - 2] = arguments[_i]; + } +} +f1(0, 1, 2); +f2(0, 1, 2); +f3(0, 1, 2); +f4(0, 1, 2); +f1(0, 1); +f2(0, 1); +f3(0, 1); +f4(0, 1); +f1(0); +f2(0); +f3(0); +f4(0); diff --git a/tests/baselines/reference/requiredInitializedParameter2.errors.txt b/tests/baselines/reference/requiredInitializedParameter2.errors.txt new file mode 100644 index 00000000000..5dcec536e1b --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter2.errors.txt @@ -0,0 +1,17 @@ +tests/cases/compiler/requiredInitializedParameter2.ts(5,7): error TS2420: Class 'C1' incorrectly implements interface 'I1'. + Types of property 'method' are incompatible. + Type '(a: number, b: any) => void' is not assignable to type '() => any'. + + +==== tests/cases/compiler/requiredInitializedParameter2.ts (1 errors) ==== + interface I1 { + method(); + } + + class C1 implements I1 { + ~~ +!!! error TS2420: Class 'C1' incorrectly implements interface 'I1'. +!!! error TS2420: Types of property 'method' are incompatible. +!!! error TS2420: Type '(a: number, b: any) => void' is not assignable to type '() => any'. + method(a = 0, b) { } + } \ No newline at end of file diff --git a/tests/baselines/reference/requiredInitializedParameter2.js b/tests/baselines/reference/requiredInitializedParameter2.js new file mode 100644 index 00000000000..3c69d54e1d9 --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter2.js @@ -0,0 +1,18 @@ +//// [requiredInitializedParameter2.ts] +interface I1 { + method(); +} + +class C1 implements I1 { + method(a = 0, b) { } +} + +//// [requiredInitializedParameter2.js] +var C1 = (function () { + function C1() { + } + C1.prototype.method = function (a, b) { + if (a === void 0) { a = 0; } + }; + return C1; +})(); diff --git a/tests/baselines/reference/requiredInitializedParameter3.js b/tests/baselines/reference/requiredInitializedParameter3.js new file mode 100644 index 00000000000..68e1aa696ea --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter3.js @@ -0,0 +1,27 @@ +//// [requiredInitializedParameter3.ts] +interface I1 { + method(); +} + +class C1 implements I1 { + method(a = 0, b?) { } +} + +//// [requiredInitializedParameter3.js] +var C1 = (function () { + function C1() { + } + C1.prototype.method = function (a, b) { + if (a === void 0) { a = 0; } + }; + return C1; +})(); + + +//// [requiredInitializedParameter3.d.ts] +interface I1 { + method(): any; +} +declare class C1 implements I1 { + method(a?: number, b?: any): void; +} diff --git a/tests/baselines/reference/requiredInitializedParameter3.symbols b/tests/baselines/reference/requiredInitializedParameter3.symbols new file mode 100644 index 00000000000..e9f35b21bcf --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter3.symbols @@ -0,0 +1,17 @@ +=== tests/cases/compiler/requiredInitializedParameter3.ts === +interface I1 { +>I1 : Symbol(I1, Decl(requiredInitializedParameter3.ts, 0, 0)) + + method(); +>method : Symbol(method, Decl(requiredInitializedParameter3.ts, 0, 14)) +} + +class C1 implements I1 { +>C1 : Symbol(C1, Decl(requiredInitializedParameter3.ts, 2, 1)) +>I1 : Symbol(I1, Decl(requiredInitializedParameter3.ts, 0, 0)) + + method(a = 0, b?) { } +>method : Symbol(method, Decl(requiredInitializedParameter3.ts, 4, 24)) +>a : Symbol(a, Decl(requiredInitializedParameter3.ts, 5, 11)) +>b : Symbol(b, Decl(requiredInitializedParameter3.ts, 5, 17)) +} diff --git a/tests/baselines/reference/requiredInitializedParameter3.types b/tests/baselines/reference/requiredInitializedParameter3.types new file mode 100644 index 00000000000..aa37f5e13dd --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter3.types @@ -0,0 +1,18 @@ +=== tests/cases/compiler/requiredInitializedParameter3.ts === +interface I1 { +>I1 : I1 + + method(); +>method : () => any +} + +class C1 implements I1 { +>C1 : C1 +>I1 : I1 + + method(a = 0, b?) { } +>method : (a?: number, b?: any) => void +>a : number +>0 : number +>b : any +} diff --git a/tests/baselines/reference/requiredInitializedParameter4.js b/tests/baselines/reference/requiredInitializedParameter4.js new file mode 100644 index 00000000000..3b23f119391 --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter4.js @@ -0,0 +1,20 @@ +//// [requiredInitializedParameter4.ts] +class C1 { + method(a = 0, b) { } +} + +//// [requiredInitializedParameter4.js] +var C1 = (function () { + function C1() { + } + C1.prototype.method = function (a, b) { + if (a === void 0) { a = 0; } + }; + return C1; +})(); + + +//// [requiredInitializedParameter4.d.ts] +declare class C1 { + method(a: number, b: any): void; +} diff --git a/tests/baselines/reference/requiredInitializedParameter4.symbols b/tests/baselines/reference/requiredInitializedParameter4.symbols new file mode 100644 index 00000000000..2790b33698c --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter4.symbols @@ -0,0 +1,9 @@ +=== tests/cases/compiler/requiredInitializedParameter4.ts === +class C1 { +>C1 : Symbol(C1, Decl(requiredInitializedParameter4.ts, 0, 0)) + + method(a = 0, b) { } +>method : Symbol(method, Decl(requiredInitializedParameter4.ts, 0, 10)) +>a : Symbol(a, Decl(requiredInitializedParameter4.ts, 1, 11)) +>b : Symbol(b, Decl(requiredInitializedParameter4.ts, 1, 17)) +} diff --git a/tests/baselines/reference/requiredInitializedParameter4.types b/tests/baselines/reference/requiredInitializedParameter4.types new file mode 100644 index 00000000000..c483146a1ba --- /dev/null +++ b/tests/baselines/reference/requiredInitializedParameter4.types @@ -0,0 +1,10 @@ +=== tests/cases/compiler/requiredInitializedParameter4.ts === +class C1 { +>C1 : C1 + + method(a = 0, b) { } +>method : (a: number, b: any) => void +>a : number +>0 : number +>b : any +} diff --git a/tests/baselines/reference/strictModeInConstructor.errors.txt b/tests/baselines/reference/strictModeInConstructor.errors.txt index 11ba2e26a68..9a80732842a 100644 --- a/tests/baselines/reference/strictModeInConstructor.errors.txt +++ b/tests/baselines/reference/strictModeInConstructor.errors.txt @@ -1,8 +1,7 @@ -tests/cases/compiler/strictModeInConstructor.ts(9,5): error TS2376: A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties. tests/cases/compiler/strictModeInConstructor.ts(27,5): error TS2376: A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties. -==== tests/cases/compiler/strictModeInConstructor.ts (2 errors) ==== +==== tests/cases/compiler/strictModeInConstructor.ts (1 errors) ==== class A { } @@ -12,14 +11,9 @@ tests/cases/compiler/strictModeInConstructor.ts(27,5): error TS2376: A 'super' c public s: number = 9; constructor () { - ~~~~~~~~~~~~~~~~ "use strict"; // No error - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ super(); - ~~~~~~~~~~~~~~~~ } - ~~~~~ -!!! error TS2376: A 'super' call must be the first statement in the constructor when a class contains initialized properties or has parameter properties. } class C extends A { diff --git a/tests/baselines/reference/tsxElementResolution8.errors.txt b/tests/baselines/reference/tsxElementResolution8.errors.txt index 5710c4e177d..92ff05d1aed 100644 --- a/tests/baselines/reference/tsxElementResolution8.errors.txt +++ b/tests/baselines/reference/tsxElementResolution8.errors.txt @@ -1,10 +1,8 @@ tests/cases/conformance/jsx/tsxElementResolution8.tsx(8,2): error TS2604: JSX element type 'Div' does not have any construct or call signatures. -tests/cases/conformance/jsx/tsxElementResolution8.tsx(16,2): error TS2601: The return type of a JSX element constructor must return an object type. -tests/cases/conformance/jsx/tsxElementResolution8.tsx(29,2): error TS2601: The return type of a JSX element constructor must return an object type. tests/cases/conformance/jsx/tsxElementResolution8.tsx(34,2): error TS2604: JSX element type 'Obj3' does not have any construct or call signatures. -==== tests/cases/conformance/jsx/tsxElementResolution8.tsx (4 errors) ==== +==== tests/cases/conformance/jsx/tsxElementResolution8.tsx (2 errors) ==== declare module JSX { interface Element { } interface IntrinsicElements { } @@ -23,8 +21,6 @@ tests/cases/conformance/jsx/tsxElementResolution8.tsx(34,2): error TS2604: JSX e // Error function Fnum(): number{ return 42; } - ~~~~ -!!! error TS2601: The return type of a JSX element constructor must return an object type. interface Obj1 { new(): {}; @@ -38,8 +34,6 @@ tests/cases/conformance/jsx/tsxElementResolution8.tsx(34,2): error TS2604: JSX e } var Obj2: Obj2; ; // Error - ~~~~ -!!! error TS2601: The return type of a JSX element constructor must return an object type. interface Obj3 { } diff --git a/tests/baselines/reference/tsxElementResolution9.errors.txt b/tests/baselines/reference/tsxElementResolution9.errors.txt deleted file mode 100644 index 64514eebc00..00000000000 --- a/tests/baselines/reference/tsxElementResolution9.errors.txt +++ /dev/null @@ -1,38 +0,0 @@ -tests/cases/conformance/jsx/tsxElementResolution9.tsx(11,2): error TS2601: The return type of a JSX element constructor must return an object type. -tests/cases/conformance/jsx/tsxElementResolution9.tsx(18,2): error TS2601: The return type of a JSX element constructor must return an object type. -tests/cases/conformance/jsx/tsxElementResolution9.tsx(25,2): error TS2601: The return type of a JSX element constructor must return an object type. - - -==== tests/cases/conformance/jsx/tsxElementResolution9.tsx (3 errors) ==== - declare module JSX { - interface Element { } - interface IntrinsicElements { } - } - - interface Obj1 { - new(n: string): { x: number }; - new(n: number): { y: string }; - } - var Obj1: Obj1; - ; // Error, return type is not an object type - ~~~~ -!!! error TS2601: The return type of a JSX element constructor must return an object type. - - interface Obj2 { - (n: string): { x: number }; - (n: number): { y: string }; - } - var Obj2: Obj2; - ; // Error, return type is not an object type - ~~~~ -!!! error TS2601: The return type of a JSX element constructor must return an object type. - - interface Obj3 { - (n: string): { x: number }; - (n: number): { x: number; y: string }; - } - var Obj3: Obj3; - ; // OK - ~~~~ -!!! error TS2601: The return type of a JSX element constructor must return an object type. - \ No newline at end of file diff --git a/tests/baselines/reference/tsxElementResolution9.symbols b/tests/baselines/reference/tsxElementResolution9.symbols new file mode 100644 index 00000000000..bfa04219ef9 --- /dev/null +++ b/tests/baselines/reference/tsxElementResolution9.symbols @@ -0,0 +1,67 @@ +=== tests/cases/conformance/jsx/tsxElementResolution9.tsx === +declare module JSX { +>JSX : Symbol(JSX, Decl(tsxElementResolution9.tsx, 0, 0)) + + interface Element { } +>Element : Symbol(Element, Decl(tsxElementResolution9.tsx, 0, 20)) + + interface IntrinsicElements { } +>IntrinsicElements : Symbol(IntrinsicElements, Decl(tsxElementResolution9.tsx, 1, 22)) +} + +interface Obj1 { +>Obj1 : Symbol(Obj1, Decl(tsxElementResolution9.tsx, 3, 1), Decl(tsxElementResolution9.tsx, 9, 3)) + + new(n: string): { x: number }; +>n : Symbol(n, Decl(tsxElementResolution9.tsx, 6, 5)) +>x : Symbol(x, Decl(tsxElementResolution9.tsx, 6, 18)) + + new(n: number): { y: string }; +>n : Symbol(n, Decl(tsxElementResolution9.tsx, 7, 5)) +>y : Symbol(y, Decl(tsxElementResolution9.tsx, 7, 18)) +} +var Obj1: Obj1; +>Obj1 : Symbol(Obj1, Decl(tsxElementResolution9.tsx, 3, 1), Decl(tsxElementResolution9.tsx, 9, 3)) +>Obj1 : Symbol(Obj1, Decl(tsxElementResolution9.tsx, 3, 1), Decl(tsxElementResolution9.tsx, 9, 3)) + +; // Error, return type is not an object type +>Obj1 : Symbol(Obj1, Decl(tsxElementResolution9.tsx, 3, 1), Decl(tsxElementResolution9.tsx, 9, 3)) + +interface Obj2 { +>Obj2 : Symbol(Obj2, Decl(tsxElementResolution9.tsx, 10, 9), Decl(tsxElementResolution9.tsx, 16, 3)) + + (n: string): { x: number }; +>n : Symbol(n, Decl(tsxElementResolution9.tsx, 13, 2)) +>x : Symbol(x, Decl(tsxElementResolution9.tsx, 13, 15)) + + (n: number): { y: string }; +>n : Symbol(n, Decl(tsxElementResolution9.tsx, 14, 2)) +>y : Symbol(y, Decl(tsxElementResolution9.tsx, 14, 15)) +} +var Obj2: Obj2; +>Obj2 : Symbol(Obj2, Decl(tsxElementResolution9.tsx, 10, 9), Decl(tsxElementResolution9.tsx, 16, 3)) +>Obj2 : Symbol(Obj2, Decl(tsxElementResolution9.tsx, 10, 9), Decl(tsxElementResolution9.tsx, 16, 3)) + +; // Error, return type is not an object type +>Obj2 : Symbol(Obj2, Decl(tsxElementResolution9.tsx, 10, 9), Decl(tsxElementResolution9.tsx, 16, 3)) + +interface Obj3 { +>Obj3 : Symbol(Obj3, Decl(tsxElementResolution9.tsx, 17, 9), Decl(tsxElementResolution9.tsx, 23, 3)) + + (n: string): { x: number }; +>n : Symbol(n, Decl(tsxElementResolution9.tsx, 20, 2)) +>x : Symbol(x, Decl(tsxElementResolution9.tsx, 20, 15)) + + (n: number): { x: number; y: string }; +>n : Symbol(n, Decl(tsxElementResolution9.tsx, 21, 2)) +>x : Symbol(x, Decl(tsxElementResolution9.tsx, 21, 15)) +>y : Symbol(y, Decl(tsxElementResolution9.tsx, 21, 26)) +} +var Obj3: Obj3; +>Obj3 : Symbol(Obj3, Decl(tsxElementResolution9.tsx, 17, 9), Decl(tsxElementResolution9.tsx, 23, 3)) +>Obj3 : Symbol(Obj3, Decl(tsxElementResolution9.tsx, 17, 9), Decl(tsxElementResolution9.tsx, 23, 3)) + +; // OK +>Obj3 : Symbol(Obj3, Decl(tsxElementResolution9.tsx, 17, 9), Decl(tsxElementResolution9.tsx, 23, 3)) +>x : Symbol(unknown) + diff --git a/tests/baselines/reference/tsxElementResolution9.types b/tests/baselines/reference/tsxElementResolution9.types new file mode 100644 index 00000000000..525e4600b2e --- /dev/null +++ b/tests/baselines/reference/tsxElementResolution9.types @@ -0,0 +1,70 @@ +=== tests/cases/conformance/jsx/tsxElementResolution9.tsx === +declare module JSX { +>JSX : any + + interface Element { } +>Element : Element + + interface IntrinsicElements { } +>IntrinsicElements : IntrinsicElements +} + +interface Obj1 { +>Obj1 : Obj1 + + new(n: string): { x: number }; +>n : string +>x : number + + new(n: number): { y: string }; +>n : number +>y : string +} +var Obj1: Obj1; +>Obj1 : Obj1 +>Obj1 : Obj1 + +; // Error, return type is not an object type +> : JSX.Element +>Obj1 : Obj1 + +interface Obj2 { +>Obj2 : Obj2 + + (n: string): { x: number }; +>n : string +>x : number + + (n: number): { y: string }; +>n : number +>y : string +} +var Obj2: Obj2; +>Obj2 : Obj2 +>Obj2 : Obj2 + +; // Error, return type is not an object type +> : JSX.Element +>Obj2 : Obj2 + +interface Obj3 { +>Obj3 : Obj3 + + (n: string): { x: number }; +>n : string +>x : number + + (n: number): { x: number; y: string }; +>n : number +>x : number +>y : string +} +var Obj3: Obj3; +>Obj3 : Obj3 +>Obj3 : Obj3 + +; // OK +> : JSX.Element +>Obj3 : Obj3 +>x : any + diff --git a/tests/cases/compiler/classExtendsNull.ts b/tests/cases/compiler/classExtendsNull.ts new file mode 100644 index 00000000000..5532fa72702 --- /dev/null +++ b/tests/cases/compiler/classExtendsNull.ts @@ -0,0 +1,12 @@ +class C extends null { + constructor() { + super(); + return Object.create(null); + } +} + +class D extends null { + constructor() { + return Object.create(null); + } +} \ No newline at end of file diff --git a/tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts b/tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts index d8ddcf4bb8f..814f1b41619 100644 --- a/tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts +++ b/tests/cases/compiler/fatarrowfunctionsOptionalArgsErrors1.ts @@ -3,5 +3,5 @@ (...arg) => 103; (...arg:number [] = []) => 104; -// Non optional parameter following an optional one +// Uninitialized parameter makes the initialized one required (arg1 = 1, arg2) => 1; \ No newline at end of file diff --git a/tests/cases/compiler/inferringAnyFunctionType1.ts b/tests/cases/compiler/inferringAnyFunctionType1.ts new file mode 100644 index 00000000000..bc1e6f68973 --- /dev/null +++ b/tests/cases/compiler/inferringAnyFunctionType1.ts @@ -0,0 +1,5 @@ +function f number }>(p: T): T { + return p; +} + +var v = f([x => x]); \ No newline at end of file diff --git a/tests/cases/compiler/inferringAnyFunctionType2.ts b/tests/cases/compiler/inferringAnyFunctionType2.ts new file mode 100644 index 00000000000..0984e578f67 --- /dev/null +++ b/tests/cases/compiler/inferringAnyFunctionType2.ts @@ -0,0 +1,5 @@ +function f number]>(p: T): T { + return p; +} + +var v = f([x => x]); \ No newline at end of file diff --git a/tests/cases/compiler/inferringAnyFunctionType3.ts b/tests/cases/compiler/inferringAnyFunctionType3.ts new file mode 100644 index 00000000000..4576a30898a --- /dev/null +++ b/tests/cases/compiler/inferringAnyFunctionType3.ts @@ -0,0 +1,5 @@ +function f number)[]>(p: T): T { + return p; +} + +var v = f([x => x]); \ No newline at end of file diff --git a/tests/cases/compiler/inferringAnyFunctionType4.ts b/tests/cases/compiler/inferringAnyFunctionType4.ts new file mode 100644 index 00000000000..592908bdfec --- /dev/null +++ b/tests/cases/compiler/inferringAnyFunctionType4.ts @@ -0,0 +1,5 @@ +function f number>(p: T): T { + return p; +} + +var v = f(x => x); \ No newline at end of file diff --git a/tests/cases/compiler/inferringAnyFunctionType5.ts b/tests/cases/compiler/inferringAnyFunctionType5.ts new file mode 100644 index 00000000000..2ff4a325c5a --- /dev/null +++ b/tests/cases/compiler/inferringAnyFunctionType5.ts @@ -0,0 +1,5 @@ +function f number }>(p: T): T { + return p; +} + +var v = f({ q: x => x }); \ No newline at end of file diff --git a/tests/cases/compiler/isolatedModulesSourceMap.ts b/tests/cases/compiler/isolatedModulesSourceMap.ts index 31dd4d9f0cf..465941d9a8b 100644 --- a/tests/cases/compiler/isolatedModulesSourceMap.ts +++ b/tests/cases/compiler/isolatedModulesSourceMap.ts @@ -3,4 +3,4 @@ // @target: es6 // @filename: file1.ts -export var x; \ No newline at end of file +export var x = 1; \ No newline at end of file diff --git a/tests/cases/compiler/jsxImportInAttribute.tsx b/tests/cases/compiler/jsxImportInAttribute.tsx new file mode 100644 index 00000000000..c4f16f55ddb --- /dev/null +++ b/tests/cases/compiler/jsxImportInAttribute.tsx @@ -0,0 +1,14 @@ +//@jsx: preserve +//@module: commonjs + +//@filename: component.d.ts +declare module "Test" { + export default class Text { } +} + +//@filename: consumer.tsx +/// +import Test from 'Test'; + +let x = Test; // emit test_1.default +; // ? diff --git a/tests/cases/compiler/jsxViaImport.tsx b/tests/cases/compiler/jsxViaImport.tsx new file mode 100644 index 00000000000..5b3b7e11d83 --- /dev/null +++ b/tests/cases/compiler/jsxViaImport.tsx @@ -0,0 +1,23 @@ +//@jsx: preserve +//@module: commonjs + +//@filename: component.d.ts +declare module JSX { + interface ElementAttributesProperty { props; } +} +declare module React { + class Component { } +} +declare module "BaseComponent" { + var base: React.Component; + export = base; +} + +//@filename: consumer.tsx +/// +import BaseComponent = require('BaseComponent'); +class TestComponent extends React.Component { + render() { + return ; + } +} diff --git a/tests/cases/compiler/optionalParamArgsTest.ts b/tests/cases/compiler/optionalParamArgsTest.ts index ce34acae869..609cbfe4734 100644 --- a/tests/cases/compiler/optionalParamArgsTest.ts +++ b/tests/cases/compiler/optionalParamArgsTest.ts @@ -30,8 +30,7 @@ class C1 { public C1M5(C1M5A1:number,C1M5A2:number=0,C1M5A3?:number) { return C1M5A1 + C1M5A2; } - // Negative test - // "Optional parameters may only be followed by other optional parameters" + // Uninitialized parameter makes the initialized one required public C1M5(C1M5A1:number,C1M5A2:number=0,C1M5A3:number) { return C1M5A1 + C1M5A2; } } diff --git a/tests/cases/compiler/requiredInitializedParameter1.ts b/tests/cases/compiler/requiredInitializedParameter1.ts new file mode 100644 index 00000000000..35d606426f0 --- /dev/null +++ b/tests/cases/compiler/requiredInitializedParameter1.ts @@ -0,0 +1,19 @@ +function f1(a, b = 0, c) { } +function f2(a, b = 0, c = 0) { } +function f3(a, b = 0, c?) { } +function f4(a, b = 0, ...c) { } + +f1(0, 1, 2); +f2(0, 1, 2); +f3(0, 1, 2); +f4(0, 1, 2); + +f1(0, 1); +f2(0, 1); +f3(0, 1); +f4(0, 1); + +f1(0); +f2(0); +f3(0); +f4(0); \ No newline at end of file diff --git a/tests/cases/compiler/requiredInitializedParameter2.ts b/tests/cases/compiler/requiredInitializedParameter2.ts new file mode 100644 index 00000000000..48d42869ee7 --- /dev/null +++ b/tests/cases/compiler/requiredInitializedParameter2.ts @@ -0,0 +1,7 @@ +interface I1 { + method(); +} + +class C1 implements I1 { + method(a = 0, b) { } +} \ No newline at end of file diff --git a/tests/cases/compiler/requiredInitializedParameter3.ts b/tests/cases/compiler/requiredInitializedParameter3.ts new file mode 100644 index 00000000000..803eefb6342 --- /dev/null +++ b/tests/cases/compiler/requiredInitializedParameter3.ts @@ -0,0 +1,8 @@ +//@declaration: true +interface I1 { + method(); +} + +class C1 implements I1 { + method(a = 0, b?) { } +} \ No newline at end of file diff --git a/tests/cases/compiler/requiredInitializedParameter4.ts b/tests/cases/compiler/requiredInitializedParameter4.ts new file mode 100644 index 00000000000..4ba15878e43 --- /dev/null +++ b/tests/cases/compiler/requiredInitializedParameter4.ts @@ -0,0 +1,4 @@ +//@declaration: true +class C1 { + method(a = 0, b) { } +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/modules/defaultExportsCannotMerge01.ts b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge01.ts new file mode 100644 index 00000000000..7caa9caf574 --- /dev/null +++ b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge01.ts @@ -0,0 +1,31 @@ +// @module: commonjs +// @target: ES5 + +// @filename: m1.ts +export default function Decl() { + return 0; +} + +export interface Decl { + p1: number; + p2: number; +} + +export namespace Decl { + export var x = 10; + export var y = 20; + + interface I { + } +} + +// @filename: m2.ts +import Entity from "m1" + +Entity(); + +var x: Entity; +var y: Entity.I; + +Entity.x; +Entity.y; \ No newline at end of file diff --git a/tests/cases/conformance/es6/modules/defaultExportsCannotMerge02.ts b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge02.ts new file mode 100644 index 00000000000..f7312ec2e66 --- /dev/null +++ b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge02.ts @@ -0,0 +1,26 @@ +// @module: commonjs +// @target: ES5 + +// @filename: m1.ts +export default class Decl { +} + +export interface Decl { + p1: number; + p2: number; +} + +export namespace Decl { + interface I { + } +} + +// @filename: m2.ts +import Entity from "m1" + +Entity(); + +var x: Entity; +var y: Entity.I; +var z = new Entity(); +var sum = z.p1 + z.p2 \ No newline at end of file diff --git a/tests/cases/conformance/es6/modules/defaultExportsCannotMerge03.ts b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge03.ts new file mode 100644 index 00000000000..dad8431812b --- /dev/null +++ b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge03.ts @@ -0,0 +1,26 @@ +// @module: commonjs +// @target: ES5 + +// @filename: m1.ts +export default class Decl { +} + +interface Decl { + p1: number; + p2: number; +} + +namespace Decl { + interface I { + } +} + +// @filename: m2.ts +import Entity from "m1" + +Entity(); + +var x: Entity; +var y: Entity.I; +var z = new Entity(); +var sum = z.p1 + z.p2 \ No newline at end of file diff --git a/tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts new file mode 100644 index 00000000000..ab72d10504a --- /dev/null +++ b/tests/cases/conformance/es6/modules/defaultExportsCannotMerge04.ts @@ -0,0 +1,15 @@ +// @module: commonjs +// @target: ES5 + +export default function Foo() { +} + +namespace Foo { + export var x; +} + +interface Foo { +} + +export interface Foo { +} \ No newline at end of file diff --git a/tests/cases/conformance/es6/modules/multipleDefaultExports01.ts b/tests/cases/conformance/es6/modules/multipleDefaultExports01.ts new file mode 100644 index 00000000000..84172248e93 --- /dev/null +++ b/tests/cases/conformance/es6/modules/multipleDefaultExports01.ts @@ -0,0 +1,19 @@ +// @module: commonjs +// @target: ES5 + +// @filename: m1.ts +export default class foo { + +} + +export default function bar() { + +} + +var x = 10; +export default x; + +// @filename: m2.ts +import Entity from "m1" + +Entity(); \ No newline at end of file diff --git a/tests/cases/conformance/es6/modules/multipleDefaultExports02.ts b/tests/cases/conformance/es6/modules/multipleDefaultExports02.ts new file mode 100644 index 00000000000..1e9c8dabc13 --- /dev/null +++ b/tests/cases/conformance/es6/modules/multipleDefaultExports02.ts @@ -0,0 +1,16 @@ +// @module: commonjs +// @target: ES5 + +// @filename: m1.ts +export default function foo() { + +} + +export default function bar() { + +} + +// @filename: m2.ts +import Entity from "m1" + +Entity(); \ No newline at end of file diff --git a/tests/cases/fourslash/addDeclareToFunction.ts b/tests/cases/fourslash/addDeclareToFunction.ts index 46e5d123632..a31713fc56f 100644 --- a/tests/cases/fourslash/addDeclareToFunction.ts +++ b/tests/cases/fourslash/addDeclareToFunction.ts @@ -1,7 +1,8 @@ +/// + //// /*1*/function parseInt(s/*2*/:string):number; goTo.marker('2'); edit.deleteAtCaret(':string'.length); goTo.marker('1'); -edit.insert('declare '); - +edit.insert('declare '); \ No newline at end of file diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index a0463073d8c..cbba2e916ce 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -29,7 +29,34 @@ // type 'fs.' as an alternate way of accessing the top-level objects // (e.g. 'fs.goTo.eof();') +//--------------------------------------- +// For API editors: +// When editting this file, and only while editing this file, enable the reference comments +// and comment out the declarations in this section to get proper type information. +// Undo these changes before compiling/committing/editing any other fourslash tests. +// The test suite will likely crash if you try 'jake runtests' with reference comments enabled. +// +// Explanation: +// We want type-completion while we edit this file, but at compile time/while editting fourslash tests, +// we don't want to include the following reference because we are compiling this file in "--out" mode and don't want to rope +// in the entire codebase into the compilation each fourslash test. Additionally, we don't want to expose the +// src/harness/fourslash.ts API's (or the rest of the compiler) because they are unstable and complicate the +// fourslash testing DSL. Finally, in this case, runtime reflection is (much) faster. +// +// TODO: figure out a better solution to the API exposure problem. + +// /// +// /// + declare var FourSlash; +module ts { + export interface SymbolDisplayPart { + text: string; + kind: string; + } +} + +//--------------------------------------------- // Return code used by getEmitOutput function to indicate status of the function // It is a duplicate of the one in types.ts to expose it to testcases in fourslash @@ -42,7 +69,6 @@ enum EmitReturnStatus { } module FourSlashInterface { - declare var FourSlash; export interface Marker { fileName: string; @@ -201,15 +227,6 @@ module FourSlashInterface { FourSlash.currentTestState.verifyReferencesAtPositionListContains(range.fileName, range.start, range.end, isWriteAccess); } - public implementorsCountIs(count: number) { - FourSlash.currentTestState.verifyImplementorsCountIs(count); - } - - // Add tests for this. - public currentParameterIsVariable() { - FourSlash.currentTestState.verifyCurrentParameterIsVariable(!this.negative); - } - public signatureHelpPresent() { FourSlash.currentTestState.verifySignatureHelpPresent(!this.negative); } @@ -361,14 +378,11 @@ module FourSlashInterface { FourSlash.currentTestState.verifyNoMatchingBracePosition(bracePosition); } - public setVerifyDocComments(val: boolean) { - FourSlash.currentTestState.setVerifyDocComments(val); - } - public getScriptLexicalStructureListCount(count: number) { FourSlash.currentTestState.verifyGetScriptLexicalStructureListCount(count); } + // TODO: figure out what to do with the unused arguments. public getScriptLexicalStructureListContains( name: string, kind: string, @@ -376,13 +390,7 @@ module FourSlashInterface { parentName?: string, isAdditionalSpan?: boolean, markerPosition?: number) { - FourSlash.currentTestState.verifGetScriptLexicalStructureListContains( - name, - kind, - fileName, - parentName, - isAdditionalSpan, - markerPosition); + FourSlash.currentTestState.verifyGetScriptLexicalStructureListContains(name, kind); } public navigationItemsListCount(count: number, searchValue: string, matchKind?: string) { @@ -698,12 +706,7 @@ module fs { export var format = new FourSlashInterface.format(); export var cancellation = new FourSlashInterface.cancellation(); } -module ts { - export interface SymbolDisplayPart { - text: string; - kind: string; - } -} + function verifyOperationIsCancelled(f) { FourSlash.verifyOperationIsCancelled(f); } diff --git a/tests/cases/unittests/session.ts b/tests/cases/unittests/session.ts new file mode 100644 index 00000000000..c1dfd508942 --- /dev/null +++ b/tests/cases/unittests/session.ts @@ -0,0 +1,447 @@ +/// + +namespace ts.server { + let lastWrittenToHost: string; + const mockHost: ServerHost = { + args: [], + newLine: "\n", + useCaseSensitiveFileNames: true, + write(s): void { lastWrittenToHost = s; }, + readFile(): string { return void 0; }, + writeFile(): void {}, + resolvePath(): string { return void 0; }, + fileExists: () => false, + directoryExists: () => false, + createDirectory(): void {}, + getExecutingFilePath(): string { return void 0; }, + getCurrentDirectory(): string { return void 0; }, + readDirectory(): string[] { return []; }, + exit(): void {} + }; + const mockLogger: Logger = { + close(): void {}, + isVerbose(): boolean { return false; }, + loggingEnabled(): boolean { return false; }, + perftrc(s: string): void {}, + info(s: string): void {}, + startGroup(): void {}, + endGroup(): void {}, + msg(s: string, type?: string): void {}, + }; + + describe("the Session class", () => { + let session: Session; + let lastSent: protocol.Message; + + beforeEach(() => { + session = new Session(mockHost, Buffer.byteLength, process.hrtime, mockLogger); + session.send = (msg: protocol.Message) => { + lastSent = msg; + }; + }); + + describe("executeCommand", () => { + it("should throw when commands are executed with invalid arguments", () => { + const req: protocol.FileRequest = { + command: CommandNames.Open, + seq: 0, + type: "command", + arguments: { + file: undefined + } + }; + + expect(() => session.executeCommand(req)).to.throw(); + }); + it("should output an error response when a command does not exist", () => { + const req: protocol.Request = { + command: "foobar", + seq: 0, + type: "command" + }; + + session.executeCommand(req); + + expect(lastSent).to.deep.equal({ + command: CommandNames.Unknown, + type: "response", + seq: 0, + message: "Unrecognized JSON command: foobar", + request_seq: 0, + success: false + }); + }); + it("should return a tuple containing the response and if a response is required on success", () => { + const req: protocol.ConfigureRequest = { + command: CommandNames.Configure, + seq: 0, + type: "command", + arguments: { + hostInfo: "unit test", + formatOptions: { + newLineCharacter: "`n" + } + } + }; + + expect(session.executeCommand(req)).to.deep.equal({ + responseRequired: false + }); + expect(lastSent).to.deep.equal({ + command: CommandNames.Configure, + type: "response", + success: true, + request_seq: 0, + seq: 0, + body: undefined + }); + }); + }); + + describe("onMessage", () => { + it("should not throw when commands are executed with invalid arguments", () => { + let i = 0; + for (name in CommandNames) { + if (!Object.prototype.hasOwnProperty.call(CommandNames, name)) { + continue; + } + const req: protocol.Request = { + command: name, + seq: i++, + type: "command" + }; + session.onMessage(JSON.stringify(req)); + req.seq = i++; + req.arguments = {}; + session.onMessage(JSON.stringify(req)); + req.seq = i++; + req.arguments = null; + session.onMessage(JSON.stringify(req)); + req.seq = i++; + req.arguments = ""; + session.onMessage(JSON.stringify(req)); + req.seq = i++; + req.arguments = 0; + session.onMessage(JSON.stringify(req)); + req.seq = i++; + req.arguments = []; + session.onMessage(JSON.stringify(req)); + } + session.onMessage("GARBAGE NON_JSON DATA"); + }); + it("should output the response for a correctly handled message", () => { + const req: protocol.ConfigureRequest = { + command: CommandNames.Configure, + seq: 0, + type: "command", + arguments: { + hostInfo: "unit test", + formatOptions: { + newLineCharacter: "`n" + } + } + }; + + session.onMessage(JSON.stringify(req)); + + expect(lastSent).to.deep.equal({ + command: CommandNames.Configure, + type: "response", + success: true, + request_seq: 0, + seq: 0, + body: undefined + }); + }); + }); + + describe("send", () => { + it("is an overrideable handle which sends protocol messages over the wire", () => { + const msg = {seq: 0, type: "none"}; + const strmsg = JSON.stringify(msg); + const len = 1 + Buffer.byteLength(strmsg, "utf8"); + const resultMsg = `Content-Length: ${len}\r\n\r\n${strmsg}\n`; + + session.send = Session.prototype.send; + assert(session.send); + expect(session.send(msg)).to.not.exist; + expect(lastWrittenToHost).to.equal(resultMsg); + }); + }); + + describe("addProtocolHandler", () => { + it("can add protocol handlers", () => { + const respBody = { + item: false + }; + const command = "newhandle"; + const result = { + response: respBody, + responseRequired: true + }; + + session.addProtocolHandler(command, (req) => result); + + expect(session.executeCommand({ + command, + seq: 0, + type: "command" + })).to.deep.equal(result); + }); + it("throws when a duplicate handler is passed", () => { + const respBody = { + item: false + }; + const resp = { + response: respBody, + responseRequired: true + }; + const command = "newhandle"; + + session.addProtocolHandler(command, (req) => resp); + + expect(() => session.addProtocolHandler(command, (req) => resp)) + .to.throw(`Protocol handler already exists for command "${command}"`); + }); + }); + + describe("event", () => { + it("can format event responses and send them", () => { + const evt = "notify-test"; + const info = { + test: true + }; + + session.event(info, evt); + + expect(lastSent).to.deep.equal({ + type: "event", + seq: 0, + event: evt, + body: info + }); + }); + }); + + describe("output", () => { + it("can format command responses and send them", () => { + const body = { + block: { + key: "value" + } + }; + const command = "test"; + + session.output(body, command); + + expect(lastSent).to.deep.equal({ + seq: 0, + request_seq: 0, + type: "response", + command, + body: body, + success: true + }); + }); + }); + }); + + describe("how Session is extendable via subclassing", () => { + class TestSession extends Session { + lastSent: protocol.Message; + customHandler = "testhandler"; + constructor() { + super(mockHost, Buffer.byteLength, process.hrtime, mockLogger); + this.addProtocolHandler(this.customHandler, () => { + return {response: undefined, responseRequired: true}; + }); + } + send(msg: protocol.Message) { + this.lastSent = msg; + } + }; + + it("can override methods such as send", () => { + const session = new TestSession(); + const body = { + block: { + key: "value" + } + }; + const command = "test"; + + session.output(body, command); + + expect(session.lastSent).to.deep.equal({ + seq: 0, + request_seq: 0, + type: "response", + command, + body: body, + success: true + }); + }); + it("can add and respond to new protocol handlers", () => { + const session = new TestSession(); + + expect(session.executeCommand({ + seq: 0, + type: "command", + command: session.customHandler + })).to.deep.equal({ + response: undefined, + responseRequired: true + }); + }); + it("has access to the project service", () => { + class ServiceSession extends TestSession { + constructor() { + super(); + assert(this.projectService); + expect(this.projectService).to.be.instanceOf(ProjectService); + } + }; + new ServiceSession(); + }); + }); + + describe("an example of using the Session API to create an in-process server", () => { + class InProcSession extends Session { + private queue: protocol.Request[] = []; + constructor(private client: InProcClient) { + super(mockHost, Buffer.byteLength, process.hrtime, mockLogger); + this.addProtocolHandler("echo", (req: protocol.Request) => ({ + response: req.arguments, + responseRequired: true + })); + } + + send(msg: protocol.Message) { + this.client.handle(msg); + } + + enqueue(msg: protocol.Request) { + this.queue.unshift(msg); + } + + handleRequest(msg: protocol.Request) { + let response: protocol.Response; + try { + ({response} = this.executeCommand(msg)); + } + catch (e) { + this.output(undefined, msg.command, msg.seq, e.toString()); + return; + } + if (response) { + this.output(response, msg.command, msg.seq); + } + } + + consumeQueue() { + while (this.queue.length > 0) { + const elem = this.queue.pop(); + this.handleRequest(elem); + } + } + } + + class InProcClient { + private server: InProcSession; + private seq = 0; + private callbacks: ts.Map<(resp: protocol.Response) => void> = {}; + private eventHandlers: ts.Map<(args: any) => void> = {}; + + handle(msg: protocol.Message): void { + if (msg.type === "response") { + const response = msg; + if (this.callbacks[response.request_seq]) { + this.callbacks[response.request_seq](response); + delete this.callbacks[response.request_seq]; + } + } + else if (msg.type === "event") { + const event = msg; + this.emit(event.event, event.body); + } + } + + emit(name: string, args: any): void { + if (this.eventHandlers[name]) { + this.eventHandlers[name](args); + } + } + + on(name: string, handler: (args: any) => void): void { + this.eventHandlers[name] = handler; + } + + connect(session: InProcSession): void { + this.server = session; + } + + execute(command: string, args: any, callback: (resp: protocol.Response) => void): void { + if (!this.server) { + return; + } + this.seq++; + this.server.enqueue({ + seq: this.seq, + type: "command", + command, + arguments: args + }); + this.callbacks[this.seq] = callback; + } + }; + + it("can be constructed and respond to commands", (done) => { + const cli = new InProcClient(); + const session = new InProcSession(cli); + const toEcho = { + data: true + }; + const toEvent = { + data: false + }; + let responses = 0; + + // Connect the client + cli.connect(session); + + // Add an event handler + cli.on("testevent", (eventinfo) => { + expect(eventinfo).to.equal(toEvent); + responses++; + expect(responses).to.equal(1); + }); + + // Trigger said event from the server + session.event(toEvent, "testevent"); + + // Queue an echo command + cli.execute("echo", toEcho, (resp) => { + assert(resp.success, resp.message); + responses++; + expect(responses).to.equal(2); + expect(resp.body).to.deep.equal(toEcho); + }); + + // Queue a configure command + cli.execute("configure", { + hostInfo: "unit test", + formatOptions: { + newLineCharacter: "`n" + } + }, (resp) => { + assert(resp.success, resp.message); + responses++; + expect(responses).to.equal(3); + done(); + }); + + // Consume the queue and trigger the callbacks + session.consumeQueue(); + }); + }); +} \ No newline at end of file diff --git a/tests/cases/unittests/transpile.ts b/tests/cases/unittests/transpile.ts index fcce034b227..1fd8c860d01 100644 --- a/tests/cases/unittests/transpile.ts +++ b/tests/cases/unittests/transpile.ts @@ -2,58 +2,120 @@ module ts { describe("Transpile", () => { - - function runTest(input: string, compilerOptions: ts.CompilerOptions = {}, fileName?: string, moduleName?: string, expectedOutput?: string, expectedDiagnosticCodes: number[] = []): void { - let diagnostics: Diagnostic[] = []; - let result = transpile(input, compilerOptions, fileName || "file.ts", diagnostics, moduleName); - + + interface TranspileTestSettings { + options?: TranspileOptions; + expectedOutput?: string; + expectedDiagnosticCodes?: number[]; + } + + function checkDiagnostics(diagnostics: Diagnostic[], expectedDiagnosticCodes?: number[]) { + if(!expectedDiagnosticCodes) { + return; + } + for (let i = 0; i < expectedDiagnosticCodes.length; i++) { assert.equal(expectedDiagnosticCodes[i], diagnostics[i] && diagnostics[i].code, `Could not find expeced diagnostic.`); } - assert.equal(diagnostics.length, expectedDiagnosticCodes.length, "Resuting diagnostics count does not match expected"); - - if (expectedOutput !== undefined) { - assert.equal(result, expectedOutput); - } + assert.equal(diagnostics.length, expectedDiagnosticCodes.length, "Resuting diagnostics count does not match expected"); } + + function test(input: string, testSettings: TranspileTestSettings): void { + let diagnostics: Diagnostic[] = []; + + let transpileOptions: TranspileOptions = testSettings.options || {}; + let transpileResult = transpile(input, transpileOptions.compilerOptions, transpileOptions.fileName, diagnostics, transpileOptions.moduleName); + + transpileOptions.reportDiagnostics = true; + let transpileModuleResult = transpileModule(input, transpileOptions); + + checkDiagnostics(diagnostics, testSettings.expectedDiagnosticCodes); + checkDiagnostics(transpileModuleResult.diagnostics, testSettings.expectedDiagnosticCodes); + + if (testSettings.expectedOutput !== undefined) { + assert.equal(transpileResult, testSettings.expectedOutput); + assert.equal(transpileModuleResult.outputText, testSettings.expectedOutput); + } + + // check source maps + if (!transpileOptions.compilerOptions) { + transpileOptions.compilerOptions = {}; + } + + if (!transpileOptions.fileName) { + transpileOptions.fileName = "file.ts"; + } + + transpileOptions.compilerOptions.sourceMap = true; + let transpileModuleResultWithSourceMap = transpileModule(input, transpileOptions); + assert.isTrue(transpileModuleResultWithSourceMap.sourceMapText !== undefined); + + let expectedSourceMapFileName = removeFileExtension(transpileOptions.fileName) + ".js.map"; + let expectedSourceMappingUrlLine = `//# sourceMappingURL=${expectedSourceMapFileName}`; + + if (testSettings.expectedOutput !== undefined) { + assert.equal(transpileModuleResultWithSourceMap.outputText, testSettings.expectedOutput + expectedSourceMappingUrlLine); + } + else { + // expected output is not set, just verify that output text has sourceMappingURL as a last line + let output = transpileModuleResultWithSourceMap.outputText; + assert.isTrue(output.length >= expectedSourceMappingUrlLine.length); + if (output.length === expectedSourceMappingUrlLine.length) { + assert.equal(output, expectedSourceMappingUrlLine); + } + else { + let suffix = getNewLineCharacter(transpileOptions.compilerOptions) + expectedSourceMappingUrlLine + assert.isTrue(output.indexOf(suffix, output.length - suffix.length) !== -1); + } + } + } + it("Generates correct compilerOptions diagnostics", () => { // Expecting 5047: "Option 'isolatedModules' can only be used when either option'--module' is provided or option 'target' is 'ES6' or higher." - runTest(`var x = 0;`, {}, /*fileName*/ undefined, /*moduleName*/undefined, /*expectedOutput*/ undefined, /*expectedDiagnosticCodes*/ [5047]); + test(`var x = 0;`, { expectedDiagnosticCodes: [5047] }); }); it("Generates no diagnostics with valid inputs", () => { // No errors - runTest(`var x = 0;`, { module: ModuleKind.CommonJS }, /*fileName*/ undefined, /*moduleName*/undefined, /*expectedOutput*/ undefined, /*expectedDiagnosticCodes*/ []); + test(`var x = 0;`, { options: { compilerOptions: { module: ModuleKind.CommonJS } } }); }); it("Generates no diagnostics for missing file references", () => { - runTest(`/// -var x = 0;`, - { module: ModuleKind.CommonJS }, /*fileName*/ undefined, /*moduleName*/undefined, /*expectedOutput*/ undefined, /*expectedDiagnosticCodes*/ []); + test(`/// +var x = 0;`, + { options: { compilerOptions: { module: ModuleKind.CommonJS } } }); }); it("Generates no diagnostics for missing module imports", () => { - runTest(`import {a} from "module2";`, - { module: ModuleKind.CommonJS }, /*fileName*/ undefined,/*moduleName*/undefined, /*expectedOutput*/ undefined, /*expectedDiagnosticCodes*/ []); + test(`import {a} from "module2";`, + { options: { compilerOptions: { module: ModuleKind.CommonJS } } }); }); it("Generates expected syntactic diagnostics", () => { - runTest(`a b`, - { module: ModuleKind.CommonJS }, /*fileName*/ undefined, /*moduleName*/undefined, /*expectedOutput*/ undefined, /*expectedDiagnosticCodes*/ [1005]); /// 1005: ';' Expected + test(`a b`, + { options: { compilerOptions: { module: ModuleKind.CommonJS } }, expectedDiagnosticCodes: [1005] }); /// 1005: ';' Expected }); it("Does not generate semantic diagnostics", () => { - runTest(`var x: string = 0;`, - { module: ModuleKind.CommonJS }, /*fileName*/ undefined, /*moduleName*/undefined, /*expectedOutput*/ undefined, /*expectedDiagnosticCodes*/ []); + test(`var x: string = 0;`, + { options: { compilerOptions: { module: ModuleKind.CommonJS } } }); }); it("Generates module output", () => { - runTest(`var x = 0;`, { module: ModuleKind.AMD }, /*fileName*/ undefined, /*moduleName*/undefined, `define(["require", "exports"], function (require, exports) {\r\n var x = 0;\r\n});\r\n`); + test(`var x = 0;`, + { + options: { compilerOptions: { module: ModuleKind.AMD } }, + expectedOutput: `define(["require", "exports"], function (require, exports) {\r\n var x = 0;\r\n});\r\n` + }); }); it("Uses correct newLine character", () => { - runTest(`var x = 0;`, { module: ModuleKind.CommonJS, newLine: NewLineKind.LineFeed }, /*fileName*/ undefined, /*moduleName*/undefined, `var x = 0;\n`, /*expectedDiagnosticCodes*/ []); + test(`var x = 0;`, + { + options: { compilerOptions: { module: ModuleKind.CommonJS, newLine: NewLineKind.LineFeed } }, + expectedOutput: `var x = 0;\n` + }); }); it("Sets module name", () => { @@ -66,12 +128,15 @@ var x = 0;`, ` }\n` + ` }\n` + `});\n`; - runTest("var x = 1;", { module: ModuleKind.System, newLine: NewLineKind.LineFeed }, /*fileName*/ undefined, "NamedModule", output) + test("var x = 1;", + { + options: { compilerOptions: { module: ModuleKind.System, newLine: NewLineKind.LineFeed }, moduleName: "NamedModule" }, + expectedOutput: output + }) }); it("No extra errors for file without extension", () => { - runTest(`var x = 0;`, { module: ModuleKind.CommonJS }, "file", /*moduleName*/undefined, /*expectedOutput*/ undefined, /*expectedDiagnosticCodes*/[]); + test(`var x = 0;`, { options: { compilerOptions: { module: ModuleKind.CommonJS }, fileName: "file" } }); }); - }); }