diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 9fa5ab5cb6d9d..db0a40f9a3aa8 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -3684,10 +3684,6 @@ namespace ts { isExternalModuleAugmentation(node.parent.parent); } - function literalTypeToString(type: LiteralType) { - return type.flags & TypeFlags.StringLiteral ? '"' + escapeString((type).value) + '"' : "" + (type).value; - } - interface NodeBuilderContext { enclosingDeclaration: Node | undefined; flags: NodeBuilderFlags | undefined; @@ -3748,7 +3744,7 @@ namespace ts { return symbolName(symbol); } - function isDeclarationVisible(node: Declaration): boolean { + function isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean { if (node) { const links = getNodeLinks(node); if (links.isVisible === undefined) { @@ -25496,6 +25492,7 @@ namespace ts { function isImplementationOfOverload(node: SignatureDeclaration) { if (nodeIsPresent((node as FunctionLikeDeclaration).body)) { + if (isGetAccessor(node) || isSetAccessor(node)) return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures const symbol = getSymbolOfNode(node); const signaturesOfSymbol = getSignaturesOfSymbol(symbol); // If this function body corresponds to function with multiple signature, it is implementation of overload @@ -25635,7 +25632,11 @@ namespace ts { } } - function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: EmitTextWriter) { + function createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean) { + declaration = getParseTreeNode(declaration, isVariableLikeOrAccessor); + if (!declaration) { + return createToken(SyntaxKind.AnyKeyword) as KeywordTypeNode; + } // Get type of the symbol if this is the valid symbol otherwise get type at location const symbol = getSymbolOfNode(declaration); let type = symbol && !(symbol.flags & (SymbolFlags.TypeLiteral | SymbolFlags.Signature)) @@ -25643,22 +25644,30 @@ namespace ts { : unknownType; if (type.flags & TypeFlags.UniqueESSymbol && type.symbol === symbol) { - flags |= TypeFormatFlags.AllowUniqueESSymbolType; + flags |= NodeBuilderFlags.AllowUniqueESSymbolType; } - if (flags & TypeFormatFlags.AddUndefined) { + if (addUndefined) { type = getOptionalType(type); } - typeToString(type, enclosingDeclaration, flags | TypeFormatFlags.MultilineObjectLiterals, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | NodeBuilderFlags.MultilineObjectLiterals, tracker); } - function writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: EmitTextWriter) { + function createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker) { + signatureDeclaration = getParseTreeNode(signatureDeclaration, isFunctionLike); + if (!signatureDeclaration) { + return createToken(SyntaxKind.AnyKeyword) as KeywordTypeNode; + } const signature = getSignatureFromDeclaration(signatureDeclaration); - typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | TypeFormatFlags.MultilineObjectLiterals, writer); + return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | NodeBuilderFlags.MultilineObjectLiterals, tracker); } - function writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: EmitTextWriter) { + function createTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker) { + expr = getParseTreeNode(expr, isExpression); + if (!expr) { + return createToken(SyntaxKind.AnyKeyword) as KeywordTypeNode; + } const type = getWidenedType(getRegularTypeOfExpression(expr)); - typeToString(type, enclosingDeclaration, flags | TypeFormatFlags.MultilineObjectLiterals, writer); + return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | NodeBuilderFlags.MultilineObjectLiterals, tracker); } function hasGlobalName(name: string): boolean { @@ -25706,9 +25715,13 @@ namespace ts { return false; } - function writeLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, writer: EmitTextWriter) { + function literalTypeToNode(type: LiteralType): Expression { + return createLiteral(type.value); + } + + function createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration) { const type = getTypeOfSymbol(getSymbolOfNode(node)); - writer.writeStringLiteral(literalTypeToString(type)); + return literalTypeToNode(type); } function createResolver(): EmitResolver { @@ -25752,9 +25765,10 @@ namespace ts { isImplementationOfOverload, isRequiredInitializedParameter, isOptionalUninitializedParameterProperty, - writeTypeOfDeclaration, - writeReturnTypeOfSignatureDeclaration, - writeTypeOfExpression, + createTypeOfDeclaration, + createReturnTypeOfSignatureDeclaration, + createTypeOfExpression, + createLiteralConstValue, isSymbolAccessible, isEntityNameVisible, getConstantValue: node => { @@ -25776,7 +25790,6 @@ namespace ts { const symbol = node && getSymbolOfNode(node); return !!(symbol && getCheckFlags(symbol) & CheckFlags.Late); }, - writeLiteralConstValue, getJsxFactoryEntity: location => location ? (getJsxNamespace(location), (getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity }; diff --git a/src/compiler/comments.ts b/src/compiler/comments.ts index 1fec1e9562fc1..f26a66701e474 100644 --- a/src/compiler/comments.ts +++ b/src/compiler/comments.ts @@ -260,7 +260,15 @@ namespace ts { } } + function shouldWriteComment(text: string, pos: number) { + if (printerOptions.onlyPrintJsDocStyle) { + return (isJSDocLikeText(text, pos) || isPinnedComment(text, pos)); + } + return true; + } + function emitLeadingComment(commentPos: number, commentEnd: number, kind: SyntaxKind, hasTrailingNewLine: boolean, rangePos: number) { + if (!shouldWriteComment(currentText, commentPos)) return; if (!hasWrittenComment) { emitNewLineBeforeLeadingCommentOfPosition(currentLineMap, writer, rangePos, commentPos); hasWrittenComment = true; @@ -292,6 +300,7 @@ namespace ts { } function emitTrailingComment(commentPos: number, commentEnd: number, _kind: SyntaxKind, hasTrailingNewLine: boolean) { + if (!shouldWriteComment(currentText, commentPos)) return; // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/ if (!writer.isAtStartOfLine()) { writer.write(" "); @@ -404,6 +413,7 @@ namespace ts { } function writeComment(text: string, lineMap: number[], writer: EmitTextWriter, commentPos: number, commentEnd: number, newLine: string) { + if (!shouldWriteComment(currentText, commentPos)) return; if (emitPos) emitPos(commentPos); writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine); if (emitPos) emitPos(commentEnd); diff --git a/src/compiler/declarationEmitter.ts b/src/compiler/declarationEmitter.ts deleted file mode 100644 index 43c635db2f20c..0000000000000 --- a/src/compiler/declarationEmitter.ts +++ /dev/null @@ -1,2047 +0,0 @@ -/// - -/* @internal */ -namespace ts { - interface ModuleElementDeclarationEmitInfo { - node: Node; - outputPos: number; - indent: number; - asynchronousOutput?: string; // If the output for alias was written asynchronously, the corresponding output - subModuleElementDeclarationEmitInfo?: ModuleElementDeclarationEmitInfo[]; - isVisible?: boolean; - } - - interface DeclarationEmit { - reportedDeclarationError: boolean; - moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; - synchronousDeclarationOutput: string; - referencesOutput: string; - } - - type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => SymbolAccessibilityDiagnostic; - - interface EmitTextWriterWithSymbolWriter extends EmitTextWriter { - getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic; - } - - interface SymbolAccessibilityDiagnostic { - errorNode: Node; - diagnosticMessage: DiagnosticMessage; - typeName?: DeclarationName | QualifiedName; - } - - export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] { - const declarationDiagnostics = createDiagnosticCollection(); - forEachEmittedFile(host, getDeclarationDiagnosticsFromFile, targetSourceFile); - return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); - - function getDeclarationDiagnosticsFromFile({ declarationFilePath }: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) { - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sourceFileOrBundle, /*emitOnlyDtsFiles*/ false); - } - } - - function emitDeclarations(host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, declarationFilePath: string, - sourceFileOrBundle: SourceFile | Bundle, emitOnlyDtsFiles: boolean): DeclarationEmit { - const sourceFiles = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - const isBundledEmit = sourceFileOrBundle.kind === SyntaxKind.Bundle; - const newLine = host.getNewLine(); - const compilerOptions = host.getCompilerOptions(); - - let write: (s: string) => void; - let writeLine: () => void; - let increaseIndent: () => void; - let decreaseIndent: () => void; - let writeTextOfNode: (text: string, node: Node) => void; - - let writer: EmitTextWriterWithSymbolWriter; - - createAndSetNewTextWriterWithSymbolWriter(); - - let enclosingDeclaration: Node; - let resultHasExternalModuleIndicator: boolean; - let currentText: string; - let currentLineMap: ReadonlyArray; - let currentIdentifiers: Map; - let isCurrentFileExternalModule: boolean; - let reportedDeclarationError = false; - let errorNameNode: DeclarationName | QualifiedName; - const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments; - const emit = compilerOptions.stripInternal ? stripInternal : emitNode; - let needsDeclare = true; - - let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; - let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]; - - // Contains the reference paths that needs to go in the declaration file. - // Collecting this separately because reference paths need to be first thing in the declaration file - // and we could be collecting these paths from multiple files into single one with --out option - let referencesOutput = ""; - - let usedTypeDirectiveReferences: Map; - - // Emit references corresponding to each file - const emittedReferencedFiles: SourceFile[] = []; - let addedGlobalFileReference = false; - let allSourcesModuleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = []; - forEach(sourceFiles, sourceFile => { - // Dont emit for javascript file - if (isSourceFileJavaScript(sourceFile)) { - return; - } - - // Check what references need to be added - if (!compilerOptions.noResolve) { - forEach(sourceFile.referencedFiles, fileReference => { - const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference); - - // Emit reference in dts, if the file reference was not already emitted - if (referencedFile && !contains(emittedReferencedFiles, referencedFile)) { - // Add a reference to generated dts file, - // global file reference is added only - // - if it is not bundled emit (because otherwise it would be self reference) - // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { - addedGlobalFileReference = true; - } - emittedReferencedFiles.push(referencedFile); - } - }); - } - - resultHasExternalModuleIndicator = false; - if (!isBundledEmit || !isExternalModule(sourceFile)) { - needsDeclare = true; - emitSourceFile(sourceFile); - } - else if (isExternalModule(sourceFile)) { - needsDeclare = false; - write(`declare module "${getResolvedExternalModuleName(host, sourceFile)}" {`); - writeLine(); - increaseIndent(); - emitSourceFile(sourceFile); - decreaseIndent(); - write("}"); - writeLine(); - } - - // create asynchronous output for the importDeclarations - if (moduleElementDeclarationEmitInfo.length) { - const oldWriter = writer; - forEach(moduleElementDeclarationEmitInfo, aliasEmitInfo => { - if (aliasEmitInfo.isVisible && !aliasEmitInfo.asynchronousOutput) { - Debug.assert(aliasEmitInfo.node.kind === SyntaxKind.ImportDeclaration); - createAndSetNewTextWriterWithSymbolWriter(); - Debug.assert(aliasEmitInfo.indent === 0 || (aliasEmitInfo.indent === 1 && isBundledEmit)); - for (let i = 0; i < aliasEmitInfo.indent; i++) { - increaseIndent(); - } - writeImportDeclaration(aliasEmitInfo.node); - aliasEmitInfo.asynchronousOutput = writer.getText(); - for (let i = 0; i < aliasEmitInfo.indent; i++) { - decreaseIndent(); - } - } - }); - setWriter(oldWriter); - - allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); - moduleElementDeclarationEmitInfo = []; - } - - if (!isBundledEmit && isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { - // if file was external module this fact should be preserved in .d.ts as well. - // in case if we didn't write any external module specifiers in .d.ts we need to emit something - // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. - write("export {};"); - writeLine(); - } - }); - - if (usedTypeDirectiveReferences) { - forEachKey(usedTypeDirectiveReferences, directive => { - referencesOutput += `/// ${newLine}`; - }); - } - - return { - reportedDeclarationError, - moduleElementDeclarationEmitInfo: allSourcesModuleElementDeclarationEmitInfo, - synchronousDeclarationOutput: writer.getText(), - referencesOutput, - }; - - function hasInternalAnnotation(range: CommentRange) { - const comment = currentText.substring(range.pos, range.end); - return stringContains(comment, "@internal"); - } - - function stripInternal(node: Node) { - if (node) { - const leadingCommentRanges = getLeadingCommentRanges(currentText, node.pos); - if (forEach(leadingCommentRanges, hasInternalAnnotation)) { - return; - } - - emitNode(node); - } - } - - function createAndSetNewTextWriterWithSymbolWriter(): void { - const writer = createTextWriter(newLine); - writer.trackSymbol = trackSymbol; - writer.reportInaccessibleThisError = reportInaccessibleThisError; - writer.reportInaccessibleUniqueSymbolError = reportInaccessibleUniqueSymbolError; - writer.reportPrivateInBaseOfClassExpression = reportPrivateInBaseOfClassExpression; - writer.writeKeyword = writer.write; - writer.writeOperator = writer.write; - writer.writePunctuation = writer.write; - writer.writeSpace = writer.write; - writer.writeStringLiteral = writer.writeLiteral; - writer.writeParameter = writer.write; - writer.writeProperty = writer.write; - writer.writeSymbol = writer.write; - setWriter(writer); - } - - function setWriter(newWriter: EmitTextWriterWithSymbolWriter) { - writer = newWriter; - write = newWriter.write; - writeTextOfNode = newWriter.writeTextOfNode; - writeLine = newWriter.writeLine; - increaseIndent = newWriter.increaseIndent; - decreaseIndent = newWriter.decreaseIndent; - } - - function writeAsynchronousModuleElements(nodes: ReadonlyArray) { - const oldWriter = writer; - forEach(nodes, declaration => { - let nodeToCheck: Node; - if (declaration.kind === SyntaxKind.VariableDeclaration) { - nodeToCheck = declaration.parent.parent; - } - else if (declaration.kind === SyntaxKind.NamedImports || declaration.kind === SyntaxKind.ImportSpecifier || declaration.kind === SyntaxKind.ImportClause) { - Debug.fail("We should be getting ImportDeclaration instead to write"); - } - else { - nodeToCheck = declaration; - } - - let moduleElementEmitInfo = forEach(moduleElementDeclarationEmitInfo, declEmitInfo => declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined); - if (!moduleElementEmitInfo && asynchronousSubModuleDeclarationEmitInfo) { - moduleElementEmitInfo = forEach(asynchronousSubModuleDeclarationEmitInfo, declEmitInfo => declEmitInfo.node === nodeToCheck ? declEmitInfo : undefined); - } - - // If the alias was marked as not visible when we saw its declaration, we would have saved the aliasEmitInfo, but if we haven't yet visited the alias declaration - // then we don't need to write it at this point. We will write it when we actually see its declaration - // Eg. - // export function bar(a: foo.Foo) { } - // import foo = require("foo"); - // Writing of function bar would mark alias declaration foo as visible but we haven't yet visited that declaration so do nothing, - // we would write alias foo declaration when we visit it since it would now be marked as visible - if (moduleElementEmitInfo) { - if (moduleElementEmitInfo.node.kind === SyntaxKind.ImportDeclaration) { - // we have to create asynchronous output only after we have collected complete information - // because it is possible to enable multiple bindings as asynchronously visible - moduleElementEmitInfo.isVisible = true; - } - else { - createAndSetNewTextWriterWithSymbolWriter(); - for (let declarationIndent = moduleElementEmitInfo.indent; declarationIndent; declarationIndent--) { - increaseIndent(); - } - - if (nodeToCheck.kind === SyntaxKind.ModuleDeclaration) { - Debug.assert(asynchronousSubModuleDeclarationEmitInfo === undefined); - asynchronousSubModuleDeclarationEmitInfo = []; - } - writeModuleElement(nodeToCheck); - if (nodeToCheck.kind === SyntaxKind.ModuleDeclaration) { - moduleElementEmitInfo.subModuleElementDeclarationEmitInfo = asynchronousSubModuleDeclarationEmitInfo; - asynchronousSubModuleDeclarationEmitInfo = undefined; - } - moduleElementEmitInfo.asynchronousOutput = writer.getText(); - } - } - }); - setWriter(oldWriter); - } - - function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[]): void { - if (!typeReferenceDirectives) { - return; - } - - if (!usedTypeDirectiveReferences) { - usedTypeDirectiveReferences = createMap(); - } - for (const directive of typeReferenceDirectives) { - if (!usedTypeDirectiveReferences.has(directive)) { - usedTypeDirectiveReferences.set(directive, directive); - } - } - } - - function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) { - if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) { - // write the aliases - if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { - writeAsynchronousModuleElements(symbolAccessibilityResult.aliasesToMakeVisible); - } - } - else { - // Report error - reportedDeclarationError = true; - const errorInfo = writer.getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); - if (errorInfo) { - if (errorInfo.typeName) { - emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, - errorInfo.diagnosticMessage, - getTextOfNodeFromSourceText(currentText, errorInfo.typeName), - symbolAccessibilityResult.errorSymbolName, - symbolAccessibilityResult.errorModuleName)); - } - else { - emitterDiagnostics.add(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, - errorInfo.diagnosticMessage, - symbolAccessibilityResult.errorSymbolName, - symbolAccessibilityResult.errorModuleName)); - } - } - } - } - - function trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); - } - - function reportPrivateInBaseOfClassExpression(propertyName: string) { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add( - createDiagnosticForNode(errorNameNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); - } - } - - function reportInaccessibleUniqueSymbolError() { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, - declarationNameToString(errorNameNode), - "unique symbol")); - } - } - - function reportInaccessibleThisError() { - if (errorNameNode) { - reportedDeclarationError = true; - emitterDiagnostics.add(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, - declarationNameToString(errorNameNode), - "this")); - } - } - - function writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, type: TypeNode, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - - // use the checker's type, not the declared type, - // for optional parameter properties - // and also for non-optional initialized parameters that aren't a parameter property - // these types may need to add `undefined`. - const shouldUseResolverType = declaration.kind === SyntaxKind.Parameter && - (resolver.isRequiredInitializedParameter(declaration) || - resolver.isOptionalUninitializedParameterProperty(declaration)); - if (type && !shouldUseResolverType) { - // Write the type - emitType(type); - } - else { - errorNameNode = declaration.name; - const format = TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | - TypeFormatFlags.WriteClassExpressionAsTypeLiteral | - (shouldUseResolverType ? TypeFormatFlags.AddUndefined : 0); - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); - errorNameNode = undefined; - } - } - - function writeReturnTypeAtSignature(signature: SignatureDeclaration, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - write(": "); - if (signature.type) { - // Write the type - emitType(signature.type); - } - else { - errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration( - signature, - enclosingDeclaration, - TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | TypeFormatFlags.WriteClassExpressionAsTypeLiteral, - writer); - errorNameNode = undefined; - } - } - - function emitLines(nodes: ReadonlyArray) { - for (const node of nodes) { - emit(node); - } - } - - function emitSeparatedList(nodes: ReadonlyArray, separator: string, eachNodeEmitFn: (node: Node) => void, canEmitFn?: (node: Node) => boolean) { - let currentWriterPos = writer.getTextPos(); - for (const node of nodes) { - if (!canEmitFn || canEmitFn(node)) { - if (currentWriterPos !== writer.getTextPos()) { - write(separator); - } - currentWriterPos = writer.getTextPos(); - eachNodeEmitFn(node); - } - } - } - - function emitCommaList(nodes: ReadonlyArray, eachNodeEmitFn: (node: Node) => void, canEmitFn?: (node: Node) => boolean) { - emitSeparatedList(nodes, ", ", eachNodeEmitFn, canEmitFn); - } - - function writeJsDocComments(declaration: Node) { - if (declaration) { - const jsDocComments = getJSDocCommentRanges(declaration, currentText); - emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments); - // jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space - emitComments(currentText, currentLineMap, writer, jsDocComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeCommentRange); - } - } - - function emitTypeWithNewGetSymbolAccessibilityDiagnostic(type: TypeNode | EntityName, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - emitType(type); - } - - function emitType(type: TypeNode | Identifier | QualifiedName) { - switch (type.kind) { - case SyntaxKind.AnyKeyword: - case SyntaxKind.StringKeyword: - case SyntaxKind.NumberKeyword: - case SyntaxKind.BooleanKeyword: - case SyntaxKind.ObjectKeyword: - case SyntaxKind.SymbolKeyword: - case SyntaxKind.VoidKeyword: - case SyntaxKind.UndefinedKeyword: - case SyntaxKind.NullKeyword: - case SyntaxKind.NeverKeyword: - case SyntaxKind.ThisType: - case SyntaxKind.LiteralType: - return writeTextOfNode(currentText, type); - case SyntaxKind.ExpressionWithTypeArguments: - return emitExpressionWithTypeArguments(type); - case SyntaxKind.TypeReference: - return emitTypeReference(type); - case SyntaxKind.TypeQuery: - return emitTypeQuery(type); - case SyntaxKind.ArrayType: - return emitArrayType(type); - case SyntaxKind.TupleType: - return emitTupleType(type); - case SyntaxKind.UnionType: - return emitUnionType(type); - case SyntaxKind.IntersectionType: - return emitIntersectionType(type); - case SyntaxKind.ConditionalType: - return emitConditionalType(type); - case SyntaxKind.InferType: - return emitInferType(type); - case SyntaxKind.ParenthesizedType: - return emitParenType(type); - case SyntaxKind.TypeOperator: - return emitTypeOperator(type); - case SyntaxKind.IndexedAccessType: - return emitIndexedAccessType(type); - case SyntaxKind.MappedType: - return emitMappedType(type); - case SyntaxKind.FunctionType: - case SyntaxKind.ConstructorType: - return emitSignatureDeclarationWithJsDocComments(type); - case SyntaxKind.TypeLiteral: - return emitTypeLiteral(type); - case SyntaxKind.Identifier: - return emitEntityName(type); - case SyntaxKind.QualifiedName: - return emitEntityName(type); - case SyntaxKind.TypePredicate: - return emitTypePredicate(type); - } - - function writeEntityName(entityName: EntityName | Expression) { - if (entityName.kind === SyntaxKind.Identifier) { - writeTextOfNode(currentText, entityName); - } - else { - const left = entityName.kind === SyntaxKind.QualifiedName ? (entityName).left : (entityName).expression; - const right = entityName.kind === SyntaxKind.QualifiedName ? (entityName).right : (entityName).name; - writeEntityName(left); - write("."); - writeTextOfNode(currentText, right); - } - } - - function emitEntityName(entityName: EntityNameOrEntityNameExpression) { - const visibilityResult = resolver.isEntityNameVisible(entityName, - // Aliases can be written asynchronously so use correct enclosing declaration - entityName.parent.kind === SyntaxKind.ImportEqualsDeclaration ? entityName.parent : enclosingDeclaration); - - handleSymbolAccessibilityError(visibilityResult); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); - writeEntityName(entityName); - } - - function emitExpressionWithTypeArguments(node: ExpressionWithTypeArguments) { - if (isEntityNameExpression(node.expression)) { - Debug.assert(node.expression.kind === SyntaxKind.Identifier || node.expression.kind === SyntaxKind.PropertyAccessExpression); - emitEntityName(node.expression); - if (node.typeArguments) { - write("<"); - emitCommaList(node.typeArguments, emitType); - write(">"); - } - } - } - - function emitTypeReference(type: TypeReferenceNode) { - emitEntityName(type.typeName); - if (type.typeArguments) { - write("<"); - emitCommaList(type.typeArguments, emitType); - write(">"); - } - } - - function emitTypePredicate(type: TypePredicateNode) { - writeTextOfNode(currentText, type.parameterName); - write(" is "); - emitType(type.type); - } - - function emitTypeQuery(type: TypeQueryNode) { - write("typeof "); - emitEntityName(type.exprName); - } - - function emitArrayType(type: ArrayTypeNode) { - emitType(type.elementType); - write("[]"); - } - - function emitTupleType(type: TupleTypeNode) { - write("["); - emitCommaList(type.elementTypes, emitType); - write("]"); - } - - function emitUnionType(type: UnionTypeNode) { - emitSeparatedList(type.types, " | ", emitType); - } - - function emitIntersectionType(type: IntersectionTypeNode) { - emitSeparatedList(type.types, " & ", emitType); - } - - function emitConditionalType(node: ConditionalTypeNode) { - emitType(node.checkType); - write(" extends "); - emitType(node.extendsType); - write(" ? "); - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node.trueType; - emitType(node.trueType); - enclosingDeclaration = prevEnclosingDeclaration; - write(" : "); - emitType(node.falseType); - } - - function emitInferType(node: InferTypeNode) { - write("infer "); - writeTextOfNode(currentText, node.typeParameter.name); - } - - function emitParenType(type: ParenthesizedTypeNode) { - write("("); - emitType(type.type); - write(")"); - } - - function emitTypeOperator(type: TypeOperatorNode) { - write(tokenToString(type.operator)); - write(" "); - emitType(type.type); - } - - function emitIndexedAccessType(node: IndexedAccessTypeNode) { - emitType(node.objectType); - write("["); - emitType(node.indexType); - write("]"); - } - - function emitMappedType(node: MappedTypeNode) { - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - write("{"); - writeLine(); - increaseIndent(); - if (node.readonlyToken) { - write(node.readonlyToken.kind === SyntaxKind.PlusToken ? "+readonly " : - node.readonlyToken.kind === SyntaxKind.MinusToken ? "-readonly " : - "readonly "); - } - write("["); - writeEntityName(node.typeParameter.name); - write(" in "); - emitType(node.typeParameter.constraint); - write("]"); - if (node.questionToken) { - write(node.questionToken.kind === SyntaxKind.PlusToken ? "+?" : - node.questionToken.kind === SyntaxKind.MinusToken ? "-?" : - "?"); - } - write(": "); - if (node.type) { - emitType(node.type); - } - else { - write("any"); - } - write(";"); - writeLine(); - decreaseIndent(); - write("}"); - enclosingDeclaration = prevEnclosingDeclaration; - } - - function emitTypeLiteral(type: TypeLiteralNode) { - write("{"); - if (type.members.length) { - writeLine(); - increaseIndent(); - // write members - emitLines(type.members); - decreaseIndent(); - } - write("}"); - } - } - - function emitSourceFile(node: SourceFile) { - currentText = node.text; - currentLineMap = getLineStarts(node); - currentIdentifiers = node.identifiers; - isCurrentFileExternalModule = isExternalModule(node); - enclosingDeclaration = node; - emitDetachedComments(currentText, currentLineMap, writer, writeCommentRange, node, newLine, /*removeComments*/ true); - emitLines(node.statements); - } - - // Return a temp variable name to be used in `export default`/`export class ... extends` statements. - // The temp name will be of the form _default_counter. - // Note that export default is only allowed at most once in a module, so we - // do not need to keep track of created temp names. - function getExportTempVariableName(baseName: string): string { - if (!currentIdentifiers.has(baseName)) { - return baseName; - } - let count = 0; - while (true) { - count++; - const name = baseName + "_" + count; - if (!currentIdentifiers.has(name)) { - return name; - } - } - } - - function emitTempVariableDeclaration(expr: Expression, baseName: string, diagnostic: SymbolAccessibilityDiagnostic, needsDeclare: boolean): string { - const tempVarName = getExportTempVariableName(baseName); - if (needsDeclare) { - write("declare "); - } - write("const "); - write(tempVarName); - write(": "); - writer.getSymbolAccessibilityDiagnostic = () => diagnostic; - resolver.writeTypeOfExpression( - expr, - enclosingDeclaration, - TypeFormatFlags.UseTypeOfFunction | TypeFormatFlags.UseStructuralFallback | TypeFormatFlags.WriteClassExpressionAsTypeLiteral, - writer); - write(";"); - writeLine(); - return tempVarName; - } - - function emitExportAssignment(node: ExportAssignment) { - if (isSourceFile(node.parent)) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - } - if (node.expression.kind === SyntaxKind.Identifier) { - write(node.isExportEquals ? "export = " : "export default "); - writeTextOfNode(currentText, node.expression); - } - else { - const tempVarName = emitTempVariableDeclaration(node.expression, "_default", { - diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, - errorNode: node - }, needsDeclare); - write(node.isExportEquals ? "export = " : "export default "); - write(tempVarName); - } - write(";"); - writeLine(); - - // Make all the declarations visible for the export name - if (node.expression.kind === SyntaxKind.Identifier) { - const nodes = resolver.collectLinkedAliases(node.expression); - - // write each of these declarations asynchronously - writeAsynchronousModuleElements(nodes); - } - } - - function isModuleElementVisible(node: Declaration) { - return resolver.isDeclarationVisible(node); - } - - function emitModuleElement(node: Node, isModuleElementVisible: boolean) { - if (isModuleElementVisible) { - writeModuleElement(node); - } - // Import equals declaration in internal module can become visible as part of any emit so lets make sure we add these irrespective - else if (node.kind === SyntaxKind.ImportEqualsDeclaration || - (node.parent.kind === SyntaxKind.SourceFile && isCurrentFileExternalModule)) { - let isVisible: boolean; - if (asynchronousSubModuleDeclarationEmitInfo && node.parent.kind !== SyntaxKind.SourceFile) { - // Import declaration of another module that is visited async so lets put it in right spot - asynchronousSubModuleDeclarationEmitInfo.push({ - node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible - }); - } - else { - if (node.kind === SyntaxKind.ImportDeclaration) { - const importDeclaration = node; - if (importDeclaration.importClause) { - isVisible = (importDeclaration.importClause.name && resolver.isDeclarationVisible(importDeclaration.importClause)) || - isVisibleNamedBinding(importDeclaration.importClause.namedBindings); - } - } - moduleElementDeclarationEmitInfo.push({ - node, - outputPos: writer.getTextPos(), - indent: writer.getIndent(), - isVisible - }); - } - } - } - - function writeModuleElement(node: Node) { - switch (node.kind) { - case SyntaxKind.FunctionDeclaration: - return writeFunctionDeclaration(node); - case SyntaxKind.VariableStatement: - return writeVariableStatement(node); - case SyntaxKind.InterfaceDeclaration: - return writeInterfaceDeclaration(node); - case SyntaxKind.ClassDeclaration: - return writeClassDeclaration(node); - case SyntaxKind.TypeAliasDeclaration: - return writeTypeAliasDeclaration(node); - case SyntaxKind.EnumDeclaration: - return writeEnumDeclaration(node); - case SyntaxKind.ModuleDeclaration: - return writeModuleDeclaration(node); - case SyntaxKind.ImportEqualsDeclaration: - return writeImportEqualsDeclaration(node); - case SyntaxKind.ImportDeclaration: - return writeImportDeclaration(node); - default: - Debug.fail("Unknown symbol kind"); - } - } - - function emitModuleElementDeclarationFlags(node: Node) { - // If the node is parented in the current source file we need to emit export declare or just export - if (node.parent.kind === SyntaxKind.SourceFile) { - const modifiers = getModifierFlags(node); - // If the node is exported - if (modifiers & ModifierFlags.Export) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - write("export "); - } - - if (modifiers & ModifierFlags.Default) { - write("default "); - } - else if (node.kind !== SyntaxKind.InterfaceDeclaration && needsDeclare) { - write("declare "); - } - } - } - - function emitClassMemberDeclarationFlags(flags: ModifierFlags) { - if (flags & ModifierFlags.Private) { - write("private "); - } - else if (flags & ModifierFlags.Protected) { - write("protected "); - } - - if (flags & ModifierFlags.Static) { - write("static "); - } - if (flags & ModifierFlags.Readonly) { - write("readonly "); - } - if (flags & ModifierFlags.Abstract) { - write("abstract "); - } - } - - function writeImportEqualsDeclaration(node: ImportEqualsDeclaration) { - // note usage of writer. methods instead of aliases created, just to make sure we are using - // correct writer especially to handle asynchronous alias writing - emitJsDocComments(node); - if (hasModifier(node, ModifierFlags.Export)) { - write("export "); - } - write("import "); - writeTextOfNode(currentText, node.name); - write(" = "); - if (isInternalModuleImportEqualsDeclaration(node)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.moduleReference, getImportEntityNameVisibilityError); - write(";"); - } - else { - write("require("); - emitExternalModuleSpecifier(node); - write(");"); - } - writer.writeLine(); - - function getImportEntityNameVisibilityError(): SymbolAccessibilityDiagnostic { - return { - diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, - errorNode: node, - typeName: node.name - }; - } - } - - function isVisibleNamedBinding(namedBindings: NamespaceImport | NamedImports): boolean { - if (namedBindings) { - if (namedBindings.kind === SyntaxKind.NamespaceImport) { - return resolver.isDeclarationVisible(namedBindings); - } - else { - return namedBindings.elements.some(namedImport => resolver.isDeclarationVisible(namedImport)); - } - } - } - - function writeImportDeclaration(node: ImportDeclaration) { - emitJsDocComments(node); - if (hasModifier(node, ModifierFlags.Export)) { - write("export "); - } - write("import "); - if (node.importClause) { - const currentWriterPos = writer.getTextPos(); - if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) { - writeTextOfNode(currentText, node.importClause.name); - } - if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) { - if (currentWriterPos !== writer.getTextPos()) { - // If the default binding was emitted, write the separated - write(", "); - } - if (node.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { - write("* as "); - writeTextOfNode(currentText, node.importClause.namedBindings.name); - } - else { - write("{ "); - emitCommaList(node.importClause.namedBindings.elements, emitImportOrExportSpecifier, resolver.isDeclarationVisible); - write(" }"); - } - } - write(" from "); - } - emitExternalModuleSpecifier(node); - write(";"); - writer.writeLine(); - } - - function emitExternalModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration) { - // emitExternalModuleSpecifier is usually called when we emit something in the.d.ts file that will make it an external module (i.e. import/export declarations). - // the only case when it is not true is when we call it to emit correct name for module augmentation - d.ts files with just module augmentations are not considered - // external modules since they are indistinguishable from script files with ambient modules. To fix this in such d.ts files we'll emit top level 'export {}' - // so compiler will treat them as external modules. - resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== SyntaxKind.ModuleDeclaration; - const moduleSpecifier = parent.kind === SyntaxKind.ImportEqualsDeclaration ? getExternalModuleImportEqualsDeclarationExpression(parent) : - parent.kind === SyntaxKind.ModuleDeclaration ? parent.name : parent.moduleSpecifier; - - if (moduleSpecifier.kind === SyntaxKind.StringLiteral && isBundledEmit && (compilerOptions.out || compilerOptions.outFile)) { - const moduleName = getExternalModuleNameFromDeclaration(host, resolver, parent); - if (moduleName) { - write('"'); - write(moduleName); - write('"'); - return; - } - } - - writeTextOfNode(currentText, moduleSpecifier); - } - - function emitImportOrExportSpecifier(node: ImportOrExportSpecifier) { - if (node.propertyName) { - writeTextOfNode(currentText, node.propertyName); - write(" as "); - } - writeTextOfNode(currentText, node.name); - } - - function emitExportSpecifier(node: ExportSpecifier) { - emitImportOrExportSpecifier(node); - - // Make all the declarations visible for the export name - const nodes = resolver.collectLinkedAliases(node.propertyName || node.name); - - // write each of these declarations asynchronously - writeAsynchronousModuleElements(nodes); - } - - function emitExportDeclaration(node: ExportDeclaration) { - resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators - emitJsDocComments(node); - write("export "); - if (node.exportClause) { - write("{ "); - emitCommaList(node.exportClause.elements, emitExportSpecifier); - write(" }"); - } - else { - write("*"); - } - if (node.moduleSpecifier) { - write(" from "); - emitExternalModuleSpecifier(node); - } - write(";"); - writer.writeLine(); - } - - function writeModuleDeclaration(node: ModuleDeclaration) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (isGlobalScopeAugmentation(node)) { - write("global "); - } - else { - if (node.flags & NodeFlags.Namespace) { - write("namespace "); - } - else { - write("module "); - } - if (isExternalModuleAugmentation(node)) { - emitExternalModuleSpecifier(node); - } - else { - writeTextOfNode(currentText, node.name); - } - } - while (node.body && node.body.kind !== SyntaxKind.ModuleBlock) { - node = node.body; - write("."); - writeTextOfNode(currentText, node.name); - } - const prevEnclosingDeclaration = enclosingDeclaration; - if (node.body) { - enclosingDeclaration = node; - write(" {"); - writeLine(); - increaseIndent(); - emitLines((node.body).statements); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - else { - write(";"); - } - } - - function writeTypeAliasDeclaration(node: TypeAliasDeclaration) { - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("type "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - write(" = "); - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError); - write(";"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - - function getTypeAliasDeclarationVisibilityError(): SymbolAccessibilityDiagnostic { - return { - diagnosticMessage: Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, - errorNode: node.type, - typeName: node.name - }; - } - } - - function writeEnumDeclaration(node: EnumDeclaration) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (isConst(node)) { - write("const "); - } - write("enum "); - writeTextOfNode(currentText, node.name); - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - } - - function emitEnumMemberDeclaration(node: EnumMember) { - emitJsDocComments(node); - writeTextOfNode(currentText, node.name); - const enumMemberValue = resolver.getConstantValue(node); - if (enumMemberValue !== undefined) { - write(" = "); - write(getTextOfConstantValue(enumMemberValue)); - } - write(","); - writeLine(); - } - - function isPrivateMethodTypeParameter(node: TypeParameterDeclaration) { - return node.parent.kind === SyntaxKind.MethodDeclaration && hasModifier(node.parent, ModifierFlags.Private); - } - - function emitTypeParameters(typeParameters: ReadonlyArray) { - function emitTypeParameter(node: TypeParameterDeclaration) { - increaseIndent(); - emitJsDocComments(node); - decreaseIndent(); - writeTextOfNode(currentText, node.name); - // If there is constraint present and this is not a type parameter of the private method emit the constraint - if (node.constraint && !isPrivateMethodTypeParameter(node)) { - write(" extends "); - if (node.parent.kind === SyntaxKind.FunctionType || - node.parent.kind === SyntaxKind.ConstructorType || - (node.parent.parent && node.parent.parent.kind === SyntaxKind.TypeLiteral)) { - Debug.assert(node.parent.kind === SyntaxKind.MethodDeclaration || - node.parent.kind === SyntaxKind.MethodSignature || - node.parent.kind === SyntaxKind.FunctionType || - node.parent.kind === SyntaxKind.ConstructorType || - node.parent.kind === SyntaxKind.CallSignature || - node.parent.kind === SyntaxKind.ConstructSignature); - emitType(node.constraint); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.constraint, getTypeParameterConstraintVisibilityError); - } - } - if (node.default && !isPrivateMethodTypeParameter(node)) { - write(" = "); - if (node.parent.kind === SyntaxKind.FunctionType || - node.parent.kind === SyntaxKind.ConstructorType || - (node.parent.parent && node.parent.parent.kind === SyntaxKind.TypeLiteral)) { - Debug.assert(node.parent.kind === SyntaxKind.MethodDeclaration || - node.parent.kind === SyntaxKind.MethodSignature || - node.parent.kind === SyntaxKind.FunctionType || - node.parent.kind === SyntaxKind.ConstructorType || - node.parent.kind === SyntaxKind.CallSignature || - node.parent.kind === SyntaxKind.ConstructSignature); - emitType(node.default); - } - else { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.default, getTypeParameterConstraintVisibilityError); - } - } - - function getTypeParameterConstraintVisibilityError(): SymbolAccessibilityDiagnostic { - // Type parameter constraints are named by user so we should always be able to name it - let diagnosticMessage: DiagnosticMessage; - switch (node.parent.kind) { - case SyntaxKind.ClassDeclaration: - diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; - break; - - case SyntaxKind.InterfaceDeclaration: - diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; - break; - - case SyntaxKind.ConstructSignature: - diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - - case SyntaxKind.CallSignature: - diagnosticMessage = Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - break; - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - if (hasModifier(node.parent, ModifierFlags.Static)) { - diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { - diagnosticMessage = Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - break; - - case SyntaxKind.FunctionDeclaration: - diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; - break; - - case SyntaxKind.TypeAliasDeclaration: - diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; - break; - - default: - Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); - } - - return { - diagnosticMessage, - errorNode: node, - typeName: node.name - }; - } - } - - if (typeParameters) { - write("<"); - emitCommaList(typeParameters, emitTypeParameter); - write(">"); - } - } - - function emitHeritageClause(typeReferences: ReadonlyArray, isImplementsList: boolean) { - if (typeReferences) { - write(isImplementsList ? " implements " : " extends "); - emitCommaList(typeReferences, emitTypeOfTypeReference); - } - - function emitTypeOfTypeReference(node: ExpressionWithTypeArguments) { - if (isEntityNameExpression(node.expression)) { - emitTypeWithNewGetSymbolAccessibilityDiagnostic(node, getHeritageClauseVisibilityError); - } - else if (!isImplementsList && node.expression.kind === SyntaxKind.NullKeyword) { - write("null"); - } - - function getHeritageClauseVisibilityError(): SymbolAccessibilityDiagnostic { - let diagnosticMessage: DiagnosticMessage; - // Heritage clause is written by user so it can always be named - if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { - // Class or Interface implemented/extended is inaccessible - diagnosticMessage = isImplementsList ? - Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : - Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; - } - else { - // interface is inaccessible - diagnosticMessage = Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; - } - - return { - diagnosticMessage, - errorNode: node, - typeName: getNameOfDeclaration(node.parent.parent) - }; - } - } - } - - function writeClassDeclaration(node: ClassDeclaration) { - function emitParameterProperties(constructorDeclaration: ConstructorDeclaration) { - if (constructorDeclaration) { - forEach(constructorDeclaration.parameters, param => { - if (hasModifier(param, ModifierFlags.ParameterPropertyModifier)) { - emitPropertyDeclaration(param); - } - }); - } - } - - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - const baseTypeNode = getClassExtendsHeritageClauseElement(node); - let tempVarName: string; - if (baseTypeNode && !isEntityNameExpression(baseTypeNode.expression)) { - tempVarName = baseTypeNode.expression.kind === SyntaxKind.NullKeyword ? - "null" : - emitTempVariableDeclaration(baseTypeNode.expression, `${node.name.escapedText}_base`, { - diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, - errorNode: baseTypeNode, - typeName: node.name - }, !findAncestor(node, n => n.kind === SyntaxKind.ModuleDeclaration)); - } - - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (hasModifier(node, ModifierFlags.Abstract)) { - write("abstract "); - } - write("class "); - writeTextOfNode(currentText, node.name); - emitTypeParameters(node.typeParameters); - if (baseTypeNode) { - if (!isEntityNameExpression(baseTypeNode.expression)) { - write(" extends "); - write(tempVarName); - if (baseTypeNode.typeArguments) { - write("<"); - emitCommaList(baseTypeNode.typeArguments, emitType); - write(">"); - } - } - else { - emitHeritageClause([baseTypeNode], /*isImplementsList*/ false); - } - } - emitHeritageClause(getClassImplementsHeritageClauseElements(node), /*isImplementsList*/ true); - write(" {"); - writeLine(); - increaseIndent(); - emitParameterProperties(getFirstConstructorWithBody(node)); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - - function writeInterfaceDeclaration(node: InterfaceDeclaration) { - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - write("interface "); - writeTextOfNode(currentText, node.name); - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - emitTypeParameters(node.typeParameters); - const interfaceExtendsTypes = filter(getInterfaceBaseTypeNodes(node), base => isEntityNameExpression(base.expression)); - if (interfaceExtendsTypes && interfaceExtendsTypes.length) { - emitHeritageClause(interfaceExtendsTypes, /*isImplementsList*/ false); - } - write(" {"); - writeLine(); - increaseIndent(); - emitLines(node.members); - decreaseIndent(); - write("}"); - writeLine(); - enclosingDeclaration = prevEnclosingDeclaration; - } - - function emitPropertyDeclaration(node: Declaration) { - if (hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - - emitJsDocComments(node); - emitClassMemberDeclarationFlags(getModifierFlags(node)); - emitVariableDeclaration(node); - write(";"); - writeLine(); - } - - function bindingNameContainsVisibleBindingElement(node: BindingName): boolean { - return !!node && isBindingPattern(node) && some(node.elements, elem => !isOmittedExpression(elem) && isVariableDeclarationVisible(elem)); - } - - function isVariableDeclarationVisible(node: VariableDeclaration | BindingElement) { - return resolver.isDeclarationVisible(node) || bindingNameContainsVisibleBindingElement(node.name); - } - - function emitVariableDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration) { - // If we are emitting property it isn't moduleElement and hence we already know it needs to be emitted - // so there is no check needed to see if declaration is visible - if (node.kind !== SyntaxKind.VariableDeclaration || isVariableDeclarationVisible(node)) { - if (isBindingPattern(node.name)) { - emitBindingPattern(node.name); - } - else { - writeNameOfDeclaration(node, getVariableDeclarationTypeVisibilityError); - - // If optional property emit ? but in the case of parameterProperty declaration with "?" indicating optional parameter for the constructor - // we don't want to emit property declaration with "?" - if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || - (node.kind === SyntaxKind.Parameter && !isParameterPropertyDeclaration(node))) && hasQuestionToken(node)) { - write("?"); - } - if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && node.parent.kind === SyntaxKind.TypeLiteral) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (resolver.isLiteralConstDeclaration(node)) { - write(" = "); - resolver.writeLiteralConstValue(node, writer); - } - else if (!hasModifier(node, ModifierFlags.Private)) { - writeTypeOfDeclaration(node, node.type, getVariableDeclarationTypeVisibilityError); - } - } - } - - function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { - if (node.kind === SyntaxKind.VariableDeclaration) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; - } - // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit - // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. - else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || - (node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) { - // TODO(jfreeman): Deal with computed properties in error reporting. - if (hasModifier(node, ModifierFlags.Static)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.Parameter) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - // Interfaces cannot have types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - } - - function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - - function emitBindingPattern(bindingPattern: BindingPattern) { - // Only select visible, non-omitted expression from the bindingPattern's elements. - // We have to do this to avoid emitting trailing commas. - // For example: - // original: var [, c,,] = [ 2,3,4] - // emitted: declare var c: number; // instead of declare var c:number, ; - const elements: Node[] = []; - for (const element of bindingPattern.elements) { - if (element.kind !== SyntaxKind.OmittedExpression && isVariableDeclarationVisible(element)) { - elements.push(element); - } - } - emitCommaList(elements, emitBindingElement); - } - - function emitBindingElement(bindingElement: BindingElement) { - function getBindingElementTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage, - errorNode: bindingElement, - typeName: bindingElement.name - } : undefined; - } - - if (bindingElement.name) { - if (isBindingPattern(bindingElement.name)) { - emitBindingPattern(bindingElement.name); - } - else { - writeTextOfNode(currentText, bindingElement.name); - writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError); - } - } - } - } - - function emitTypeOfVariableDeclarationFromTypeLiteral(node: VariableLikeDeclaration) { - // if this is property of type literal, - // or is parameter of method/call/construct/index signature of type literal - // emit only if type is specified - if (hasType(node)) { - write(": "); - emitType(node.type); - } - } - - function isVariableStatementVisible(node: VariableStatement) { - return forEach(node.declarationList.declarations, varDeclaration => isVariableDeclarationVisible(varDeclaration)); - } - - function writeVariableStatement(node: VariableStatement) { - // If binding pattern doesn't have name, then there is nothing to be emitted for declaration file i.e. const [,] = [1,2]. - if (every(node.declarationList && node.declarationList.declarations, decl => decl.name && isEmptyBindingPattern(decl.name))) { - return; - } - emitJsDocComments(node); - emitModuleElementDeclarationFlags(node); - if (isLet(node.declarationList)) { - write("let "); - } - else if (isConst(node.declarationList)) { - write("const "); - } - else { - write("var "); - } - emitCommaList(node.declarationList.declarations, emitVariableDeclaration, isVariableDeclarationVisible); - write(";"); - writeLine(); - } - - function emitAccessorDeclaration(node: AccessorDeclaration) { - if (hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - - const accessors = getAllAccessorDeclarations((node.parent).members, node); - let accessorWithTypeAnnotation: AccessorDeclaration; - - if (node === accessors.firstAccessor) { - emitJsDocComments(accessors.getAccessor); - emitJsDocComments(accessors.setAccessor); - emitClassMemberDeclarationFlags(getModifierFlags(node) | (accessors.setAccessor ? 0 : ModifierFlags.Readonly)); - writeNameOfDeclaration(node, getAccessorNameVisibilityError); - if (!hasModifier(node, ModifierFlags.Private)) { - accessorWithTypeAnnotation = node; - let type = getTypeAnnotationFromAccessor(node); - if (!type) { - // couldn't get type for the first accessor, try the another one - const anotherAccessor = node.kind === SyntaxKind.GetAccessor ? accessors.setAccessor : accessors.getAccessor; - type = getTypeAnnotationFromAccessor(anotherAccessor); - if (type) { - accessorWithTypeAnnotation = anotherAccessor; - } - } - writeTypeOfDeclaration(node, type, getAccessorDeclarationTypeVisibilityError); - } - write(";"); - writeLine(); - } - - function getTypeAnnotationFromAccessor(accessor: AccessorDeclaration): TypeNode { - if (accessor) { - return accessor.kind === SyntaxKind.GetAccessor - ? accessor.type // Getter - return type - : accessor.parameters.length > 0 - ? accessor.parameters[0].type // Setter parameter type - : undefined; - } - } - - function getAccessorNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) { - const diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - - function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { - if (hasModifier(node, ModifierFlags.Static)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - return symbolAccessibilityResult.errorModuleName ? - Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - - function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage: DiagnosticMessage; - if (accessorWithTypeAnnotation.kind === SyntaxKind.SetAccessor) { - // Getters can infer the return type from the returned expression, but setters cannot, so the - // "_from_external_module_1_but_cannot_be_named" case cannot occur. - if (hasModifier(accessorWithTypeAnnotation, ModifierFlags.Static)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; - } - } - else { - if (hasModifier(accessorWithTypeAnnotation, ModifierFlags.Static)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; - } - else { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; - } - } - return { - diagnosticMessage, - errorNode: accessorWithTypeAnnotation.name, - typeName: accessorWithTypeAnnotation.name - }; - } - } - - function writeFunctionDeclaration(node: FunctionLikeDeclaration) { - if (hasDynamicName(node) && !resolver.isLateBound(node)) { - return; - } - - // If we are emitting Method/Constructor it isn't moduleElement and hence already determined to be emitting - // so no need to verify if the declaration is visible - if (!resolver.isImplementationOfOverload(node)) { - emitJsDocComments(node); - if (node.kind === SyntaxKind.FunctionDeclaration) { - emitModuleElementDeclarationFlags(node); - } - else if (node.kind === SyntaxKind.MethodDeclaration || node.kind === SyntaxKind.Constructor) { - emitClassMemberDeclarationFlags(getModifierFlags(node)); - } - if (node.kind === SyntaxKind.FunctionDeclaration) { - write("function "); - writeTextOfNode(currentText, node.name); - } - else if (node.kind === SyntaxKind.Constructor) { - write("constructor"); - } - else { - writeNameOfDeclaration(node, getMethodNameVisibilityError); - if (hasQuestionToken(node)) { - write("?"); - } - } - emitSignatureDeclaration(node); - } - - function getMethodNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - - function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { - if (hasModifier(node, ModifierFlags.Static)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; - } - else { - return symbolAccessibilityResult.errorModuleName ? - Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; - } - } - } - - function writeNameOfDeclaration(node: NamedDeclaration, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) { - if (hasDynamicName(node)) { - // If this node has a dynamic name, it can only be an identifier or property access because - // we've already skipped it otherwise. - Debug.assert(resolver.isLateBound(node)); - - writeLateBoundNameOfDeclaration(node as LateBoundDeclaration, getSymbolAccessibilityDiagnostic); - } - else { - // If this node is a computed name, it can only be a symbol, because we've already skipped - // it if it's not a well known symbol. In that case, the text of the name will be exactly - // what we want, namely the name expression enclosed in brackets. - writeTextOfNode(currentText, node.name); - } - } - - function writeLateBoundNameOfDeclaration(node: LateBoundDeclaration, getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic) { - writer.getSymbolAccessibilityDiagnostic = getSymbolAccessibilityDiagnostic; - const entityName = node.name.expression; - const visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); - handleSymbolAccessibilityError(visibilityResult); - recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); - writeTextOfNode(currentText, node.name); - } - - function emitSignatureDeclarationWithJsDocComments(node: SignatureDeclaration) { - emitJsDocComments(node); - emitSignatureDeclaration(node); - } - - function emitSignatureDeclaration(node: SignatureDeclaration) { - const prevEnclosingDeclaration = enclosingDeclaration; - enclosingDeclaration = node; - let closeParenthesizedFunctionType = false; - - if (node.kind === SyntaxKind.IndexSignature) { - // Index signature can have readonly modifier - emitClassMemberDeclarationFlags(getModifierFlags(node)); - write("["); - } - else { - if (node.kind === SyntaxKind.Constructor && hasModifier(node, ModifierFlags.Private)) { - write("();"); - writeLine(); - return; - } - // Construct signature or constructor type write new Signature - if (node.kind === SyntaxKind.ConstructSignature || node.kind === SyntaxKind.ConstructorType) { - write("new "); - } - else if (node.kind === SyntaxKind.FunctionType) { - const currentOutput = writer.getText(); - // Do not generate incorrect type when function type with type parameters is type argument - // This could happen if user used space between two '<' making it error free - // e.g var x: A< (a: Tany)=>Tany>; - if (node.typeParameters && currentOutput.charAt(currentOutput.length - 1) === "<") { - closeParenthesizedFunctionType = true; - write("("); - } - } - emitTypeParameters(node.typeParameters); - write("("); - } - - // Parameters - emitCommaList(node.parameters, emitParameterDeclaration); - - if (node.kind === SyntaxKind.IndexSignature) { - write("]"); - } - else { - write(")"); - } - - // If this is not a constructor and is not private, emit the return type - const isFunctionTypeOrConstructorType = node.kind === SyntaxKind.FunctionType || node.kind === SyntaxKind.ConstructorType; - if (isFunctionTypeOrConstructorType || node.parent.kind === SyntaxKind.TypeLiteral) { - // Emit type literal signature return type only if specified - if (node.type) { - write(isFunctionTypeOrConstructorType ? " => " : ": "); - emitType(node.type); - } - } - else if (node.kind !== SyntaxKind.Constructor && !hasModifier(node, ModifierFlags.Private)) { - writeReturnTypeAtSignature(node, getReturnTypeVisibilityError); - } - - enclosingDeclaration = prevEnclosingDeclaration; - - if (!isFunctionTypeOrConstructorType) { - write(";"); - writeLine(); - } - else if (closeParenthesizedFunctionType) { - write(")"); - } - - function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { - let diagnosticMessage: DiagnosticMessage; - switch (node.kind) { - case SyntaxKind.ConstructSignature: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - - case SyntaxKind.CallSignature: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - - case SyntaxKind.IndexSignature: - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; - break; - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - if (hasModifier(node, ModifierFlags.Static)) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; - } - else if (node.parent.kind === SyntaxKind.ClassDeclaration) { - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : - Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; - } - else { - // Interfaces cannot have return types that cannot be named - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : - Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; - } - break; - - case SyntaxKind.FunctionDeclaration: - diagnosticMessage = symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : - Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : - Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; - break; - - default: - Debug.fail("This is unknown kind for signature: " + node.kind); - } - - return { - diagnosticMessage, - errorNode: node.name || node - }; - } - } - - function emitParameterDeclaration(node: ParameterDeclaration) { - increaseIndent(); - emitJsDocComments(node); - if (node.dotDotDotToken) { - write("..."); - } - if (isBindingPattern(node.name)) { - // For bindingPattern, we can't simply writeTextOfNode from the source file - // because we want to omit the initializer and using writeTextOfNode will result in initializer get emitted. - // Therefore, we will have to recursively emit each element in the bindingPattern. - emitBindingPattern(node.name); - } - else { - writeTextOfNode(currentText, node.name); - } - if (resolver.isOptionalParameter(node)) { - write("?"); - } - decreaseIndent(); - - if (node.parent.kind === SyntaxKind.FunctionType || - node.parent.kind === SyntaxKind.ConstructorType || - node.parent.parent.kind === SyntaxKind.TypeLiteral) { - emitTypeOfVariableDeclarationFromTypeLiteral(node); - } - else if (!hasModifier(node.parent, ModifierFlags.Private)) { - writeTypeOfDeclaration(node, node.type, getParameterDeclarationTypeVisibilityError); - } - - function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { - const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); - return diagnosticMessage !== undefined ? { - diagnosticMessage, - errorNode: node, - typeName: node.name - } : undefined; - } - - function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult): DiagnosticMessage { - switch (node.parent.kind) { - case SyntaxKind.Constructor: - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; - - case SyntaxKind.ConstructSignature: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; - - case SyntaxKind.CallSignature: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; - - case SyntaxKind.IndexSignature: - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; - - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - if (hasModifier(node.parent, ModifierFlags.Static)) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; - } - else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; - } - else { - // Interfaces cannot have parameter types that cannot be named - return symbolAccessibilityResult.errorModuleName ? - Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; - } - - case SyntaxKind.FunctionDeclaration: - return symbolAccessibilityResult.errorModuleName ? - symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? - Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : - Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : - Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; - - default: - Debug.fail("This is unknown parent for parameter: " + node.parent.kind); - } - } - - function emitBindingPattern(bindingPattern: BindingPattern) { - // We have to explicitly emit square bracket and bracket because these tokens are not store inside the node. - if (bindingPattern.kind === SyntaxKind.ObjectBindingPattern) { - write("{"); - emitCommaList(bindingPattern.elements, emitBindingElement); - write("}"); - } - else if (bindingPattern.kind === SyntaxKind.ArrayBindingPattern) { - write("["); - const elements = bindingPattern.elements; - emitCommaList(elements, emitBindingElement); - if (elements && elements.hasTrailingComma) { - write(", "); - } - write("]"); - } - } - - function emitBindingElement(bindingElement: BindingElement | OmittedExpression) { - if (bindingElement.kind === SyntaxKind.OmittedExpression) { - // If bindingElement is an omittedExpression (i.e. containing elision), - // we will emit blank space (although this may differ from users' original code, - // it allows emitSeparatedList to write separator appropriately) - // Example: - // original: function foo([, x, ,]) {} - // tslint:disable-next-line no-double-space - // emit : function foo([ , x, , ]) {} - write(" "); - } - else if (bindingElement.kind === SyntaxKind.BindingElement) { - if (bindingElement.propertyName) { - // bindingElement has propertyName property in the following case: - // { y: [a,b,c] ...} -> bindingPattern will have a property called propertyName for "y" - // We have to explicitly emit the propertyName before descending into its binding elements. - // Example: - // original: function foo({y: [a,b,c]}) {} - // emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void; - writeTextOfNode(currentText, bindingElement.propertyName); - write(": "); - } - if (bindingElement.name) { - if (isBindingPattern(bindingElement.name)) { - // If it is a nested binding pattern, we will recursively descend into each element and emit each one separately. - // In the case of rest element, we will omit rest element. - // Example: - // original: function foo([a, [[b]], c] = [1,[["string"]], 3]) {} - // emit : declare function foo([a, [[b]], c]: [number, [[string]], number]): void; - // original with rest: function foo([a, ...c]) {} - // emit : declare function foo([a, ...c]): void; - emitBindingPattern(bindingElement.name); - } - else { - Debug.assert(bindingElement.name.kind === SyntaxKind.Identifier); - // If the node is just an identifier, we will simply emit the text associated with the node's name - // Example: - // original: function foo({y = 10, x}) {} - // emit : declare function foo({y, x}: {number, any}): void; - if (bindingElement.dotDotDotToken) { - write("..."); - } - writeTextOfNode(currentText, bindingElement.name); - } - } - } - } - } - - function emitNode(node: Node) { - switch (node.kind) { - case SyntaxKind.FunctionDeclaration: - case SyntaxKind.ModuleDeclaration: - case SyntaxKind.ImportEqualsDeclaration: - case SyntaxKind.InterfaceDeclaration: - case SyntaxKind.ClassDeclaration: - case SyntaxKind.TypeAliasDeclaration: - case SyntaxKind.EnumDeclaration: - return emitModuleElement(node, isModuleElementVisible(node)); - case SyntaxKind.VariableStatement: - return emitModuleElement(node, isVariableStatementVisible(node)); - case SyntaxKind.ImportDeclaration: - // Import declaration without import clause is visible, otherwise it is not visible - return emitModuleElement(node, /*isModuleElementVisible*/!(node).importClause); - case SyntaxKind.ExportDeclaration: - return emitExportDeclaration(node); - case SyntaxKind.Constructor: - case SyntaxKind.MethodDeclaration: - case SyntaxKind.MethodSignature: - return writeFunctionDeclaration(node); - case SyntaxKind.ConstructSignature: - case SyntaxKind.CallSignature: - case SyntaxKind.IndexSignature: - return emitSignatureDeclarationWithJsDocComments(node); - case SyntaxKind.GetAccessor: - case SyntaxKind.SetAccessor: - return emitAccessorDeclaration(node); - case SyntaxKind.PropertyDeclaration: - case SyntaxKind.PropertySignature: - return emitPropertyDeclaration(node); - case SyntaxKind.EnumMember: - return emitEnumMemberDeclaration(node); - case SyntaxKind.ExportAssignment: - return emitExportAssignment(node); - case SyntaxKind.SourceFile: - return emitSourceFile(node); - } - } - - /** - * Adds the reference to referenced file, returns true if global file reference was emitted - * @param referencedFile - * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not - */ - function writeReferencePath(referencedFile: SourceFile, addBundledFileReference: boolean, emitOnlyDtsFiles: boolean): boolean { - let declFileName: string; - let addedBundledEmitReference = false; - if (referencedFile.isDeclarationFile) { - // Declaration file, use declaration file name - declFileName = referencedFile.fileName; - } - else { - // Get the declaration file path - forEachEmittedFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); - } - - if (declFileName) { - declFileName = getRelativePathToDirectoryOrUrl( - getDirectoryPath(normalizeSlashes(declarationFilePath)), - declFileName, - host.getCurrentDirectory(), - host.getCanonicalFileName, - /*isAbsolutePathAnUrl*/ false); - - referencesOutput += `/// ${newLine}`; - } - return addedBundledEmitReference; - - function getDeclFileName(emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) { - // Dont add reference path to this file if it is a bundled emit and caller asked not emit bundled file path - const isBundledEmit = sourceFileOrBundle.kind === SyntaxKind.Bundle; - if (isBundledEmit && !addBundledFileReference) { - return; - } - - Debug.assert(!!emitFileNames.declarationFilePath || isSourceFileJavaScript(referencedFile), "Declaration file is not present only for javascript files"); - declFileName = emitFileNames.declarationFilePath || emitFileNames.jsFilePath; - addedBundledEmitReference = isBundledEmit; - } - } - } - - /* @internal */ - export function writeDeclarationFile(declarationFilePath: string, sourceFileOrBundle: SourceFile | Bundle, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, emitOnlyDtsFiles: boolean) { - const emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); - const emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped || emitOnlyDtsFiles) { - const sourceFiles = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; - const declarationOutput = emitDeclarationResult.referencesOutput - + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); - writeFile(host, emitterDiagnostics, declarationFilePath, declarationOutput, host.getCompilerOptions().emitBOM, sourceFiles); - } - return emitSkipped; - - function getDeclarationOutput(synchronousDeclarationOutput: string, moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[]) { - let appliedSyncOutputPos = 0; - let declarationOutput = ""; - // apply asynchronous additions to the synchronous output - forEach(moduleElementDeclarationEmitInfo, aliasEmitInfo => { - if (aliasEmitInfo.asynchronousOutput) { - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos, aliasEmitInfo.outputPos); - declarationOutput += getDeclarationOutput(aliasEmitInfo.asynchronousOutput, aliasEmitInfo.subModuleElementDeclarationEmitInfo); - appliedSyncOutputPos = aliasEmitInfo.outputPos; - } - }); - declarationOutput += synchronousDeclarationOutput.substring(appliedSyncOutputPos); - return declarationOutput; - } - } -} diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index 583138e24cfb4..a695b55f5ca8a 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -1,6 +1,5 @@ /// /// -/// /// /// @@ -18,18 +17,16 @@ namespace ts { * Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit. */ export function forEachEmittedFile( - host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle, emitOnlyDtsFiles: boolean) => T, - sourceFilesOrTargetSourceFile?: SourceFile[] | SourceFile, + host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) => T, + sourceFilesOrTargetSourceFile?: ReadonlyArray | SourceFile, emitOnlyDtsFiles?: boolean) { const sourceFiles = isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); const options = host.getCompilerOptions(); if (options.outFile || options.out) { if (sourceFiles.length) { - const jsFilePath = options.outFile || options.out; - const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - const declarationFilePath = options.declaration ? removeFileExtension(jsFilePath) + Extension.Dts : ""; - const result = action({ jsFilePath, sourceMapFilePath, declarationFilePath }, createBundle(sourceFiles), emitOnlyDtsFiles); + const bundle = createBundle(sourceFiles); + const result = action(getOutputPathsFor(bundle, host, emitOnlyDtsFiles), bundle); if (result) { return result; } @@ -37,10 +34,7 @@ namespace ts { } else { for (const sourceFile of sourceFiles) { - const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); - const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - const declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - const result = action({ jsFilePath, sourceMapFilePath, declarationFilePath }, sourceFile, emitOnlyDtsFiles); + const result = action(getOutputPathsFor(sourceFile, host, emitOnlyDtsFiles), sourceFile); if (result) { return result; } @@ -48,6 +42,25 @@ namespace ts { } } + /*@internal*/ + export function getOutputPathsFor(sourceFile: SourceFile | Bundle, host: EmitHost, forceDtsPaths: boolean) { + const options = host.getCompilerOptions(); + if (sourceFile.kind === SyntaxKind.Bundle) { + const jsFilePath = options.outFile || options.out; + const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + const declarationFilePath = (forceDtsPaths || options.declaration) ? removeFileExtension(jsFilePath) + Extension.Dts : undefined; + return { jsFilePath, sourceMapFilePath, declarationFilePath }; + } + else { + const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); + const sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); + // For legacy reasons (ie, we have baselines capturing the behavior), js files don't report a .d.ts output path - this would only matter if `declaration` and `allowJs` were both on, which is currently an error + const isJs = isSourceFileJavaScript(sourceFile); + const declarationFilePath = ((forceDtsPaths || options.declaration) && !isJs) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + return { jsFilePath, sourceMapFilePath, declarationFilePath }; + } + } + function getSourceMapFilePath(jsFilePath: string, options: CompilerOptions) { return options.sourceMap ? jsFilePath + ".map" : undefined; } @@ -70,13 +83,6 @@ namespace ts { return Extension.Js; } - function getOriginalSourceFileOrBundle(sourceFileOrBundle: SourceFile | Bundle) { - if (sourceFileOrBundle.kind === SyntaxKind.Bundle) { - return updateBundle(sourceFileOrBundle, sameMap(sourceFileOrBundle.sourceFiles, getOriginalSourceFile)); - } - return getOriginalSourceFile(sourceFileOrBundle); - } - /*@internal*/ // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean, transformers?: TransformerFactory[]): EmitResult { @@ -94,37 +100,11 @@ namespace ts { let isOwnFileEmit: boolean; let emitSkipped = false; - const sourceFiles = getSourceFilesToEmit(host, targetSourceFile); - - // Transform the source files - const transform = transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); - - // Create a printer to print the nodes - const printer = createPrinter(compilerOptions, { - // resolver hooks - hasGlobalName: resolver.hasGlobalName, - - // transform hooks - onEmitNode: transform.emitNodeWithNotification, - substituteNode: transform.substituteNode, - - // sourcemap hooks - onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, - onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, - onEmitSourceMapOfPosition: sourceMap.emitPos, - - // emitter hooks - onEmitHelpers: emitHelpers, - onSetSourceFile: setSourceFile, - }); - // Emit each output file performance.mark("beforePrint"); - forEachEmittedFile(host, emitSourceFileOrBundle, transform.transformed, emitOnlyDtsFiles); + forEachEmittedFile(host, emitSourceFileOrBundle, getSourceFilesToEmit(host, targetSourceFile), emitOnlyDtsFiles); performance.measure("printTime", "beforePrint"); - // Clean up emit nodes on parse tree - transform.dispose(); return { emitSkipped, @@ -134,19 +114,8 @@ namespace ts { }; function emitSourceFileOrBundle({ jsFilePath, sourceMapFilePath, declarationFilePath }: EmitFileNames, sourceFileOrBundle: SourceFile | Bundle) { - // Make sure not to write js file and source map file if any of them cannot be written - if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit && !compilerOptions.emitDeclarationOnly) { - if (!emitOnlyDtsFiles) { - printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle); - } - } - else { - emitSkipped = true; - } - - if (declarationFilePath) { - emitSkipped = writeDeclarationFile(declarationFilePath, getOriginalSourceFileOrBundle(sourceFileOrBundle), host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; - } + emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath); + emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath); if (!emitSkipped && emittedFilesList) { if (!emitOnlyDtsFiles) { @@ -161,7 +130,77 @@ namespace ts { } } - function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string, sourceFileOrBundle: SourceFile | Bundle) { + function emitJsFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, jsFilePath: string, sourceMapFilePath: string) { + const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Make sure not to write js file and source map file if any of them cannot be written + if (host.isEmitBlocked(jsFilePath) || compilerOptions.noEmit || compilerOptions.emitDeclarationOnly) { + emitSkipped = true; + return; + } + if (emitOnlyDtsFiles) { + return; + } + // Transform the source files + const transform = transformNodes(resolver, host, compilerOptions, sourceFiles, transformers, /*allowDtsFiles*/ false); + + // Create a printer to print the nodes + const printer = createPrinter(compilerOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + + // transform hooks + onEmitNode: transform.emitNodeWithNotification, + substituteNode: transform.substituteNode, + + // sourcemap hooks + onEmitSourceMapOfNode: sourceMap.emitNodeWithSourceMap, + onEmitSourceMapOfToken: sourceMap.emitTokenWithSourceMap, + onEmitSourceMapOfPosition: sourceMap.emitPos, + + // emitter hooks + onEmitHelpers: emitHelpers, + onSetSourceFile: setSourceFile, + }); + + printSourceFileOrBundle(jsFilePath, sourceMapFilePath, isSourceFile(sourceFileOrBundle) ? transform.transformed[0] : createBundle(transform.transformed), printer); + + // Clean up emit nodes on parse tree + transform.dispose(); + } + + function emitDeclarationFileOrBundle(sourceFileOrBundle: SourceFile | Bundle, declarationFilePath: string | undefined) { + if (!(declarationFilePath && !isInJavaScriptFile(sourceFileOrBundle))) { + return; + } + const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; + // Setup and perform the transformation to retrieve declarations from the input files + const nonJsFiles = filter(sourceFiles, isSourceFileNotJavaScript); + const inputListOrBundle = (compilerOptions.outFile || compilerOptions.out) ? [createBundle(nonJsFiles)] : nonJsFiles; + const declarationTransform = transformNodes(resolver, host, compilerOptions, inputListOrBundle, [transformDeclarations], /*allowDtsFiles*/ false); + if (length(declarationTransform.diagnostics)) { + for (const diagnostic of declarationTransform.diagnostics) { + emitterDiagnostics.add(diagnostic); + } + } + const declarationPrinter = createPrinter({ ...compilerOptions, onlyPrintJsDocStyle: true } as PrinterOptions, { + // resolver hooks + hasGlobalName: resolver.hasGlobalName, + + // transform hooks + onEmitNode: declarationTransform.emitNodeWithNotification, + substituteNode: declarationTransform.substituteNode, + }); + const declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit; + emitSkipped = emitSkipped || declBlocked; + if (!declBlocked || emitOnlyDtsFiles) { + const previousState = sourceMap.setState(/*disabled*/ true); + printSourceFileOrBundle(declarationFilePath, /*sourceMapFilePath*/ undefined, declarationTransform.transformed[0], declarationPrinter, /*shouldSkipSourcemap*/ true); + sourceMap.setState(previousState); + } + declarationTransform.dispose(); + } + + function printSourceFileOrBundle(jsFilePath: string, sourceMapFilePath: string, sourceFileOrBundle: SourceFile | Bundle, printer: Printer, shouldSkipSourcemap = false) { const bundle = sourceFileOrBundle.kind === SyntaxKind.Bundle ? sourceFileOrBundle : undefined; const sourceFile = sourceFileOrBundle.kind === SyntaxKind.SourceFile ? sourceFileOrBundle : undefined; const sourceFiles = bundle ? bundle.sourceFiles : [sourceFile]; @@ -180,17 +219,17 @@ namespace ts { writer.writeLine(); const sourceMappingURL = sourceMap.getSourceMappingURL(); - if (sourceMappingURL) { + if (!shouldSkipSourcemap && sourceMappingURL) { writer.write(`//# ${"sourceMappingURL"}=${sourceMappingURL}`); // Sometimes tools can sometimes see this line as a source mapping url comment } // Write the source map - if (compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { + if (!shouldSkipSourcemap && compilerOptions.sourceMap && !compilerOptions.inlineSourceMap) { writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap.getText(), /*writeByteOrderMark*/ false, sourceFiles); } // Record source map data for the test harness. - if (sourceMapDataList) { + if (!shouldSkipSourcemap && sourceMapDataList) { sourceMapDataList.push(sourceMap.getSourceMapData()); } @@ -384,6 +423,7 @@ namespace ts { emitShebangIfNeeded(bundle); emitPrologueDirectivesIfNeeded(bundle); emitHelpersIndirect(bundle); + emitSyntheticTripleSlashReferencesIfNeeded(bundle); for (const sourceFile of bundle.sourceFiles) { print(EmitHint.SourceFile, sourceFile, sourceFile); } @@ -2044,6 +2084,7 @@ namespace ts { emit(node.name); let body = node.body; + if (!body) return writeSemicolon(); while (body.kind === SyntaxKind.ModuleDeclaration) { writePunctuation("."); emit((body).name); @@ -2418,11 +2459,31 @@ namespace ts { emitSourceFileWorker(node); } + function emitSyntheticTripleSlashReferencesIfNeeded(node: Bundle) { + emitTripleSlashDirectives(node.syntheticFileReferences || [], node.syntheticTypeReferences || []); + } + + function emitTripleSlashDirectivesIfNeeded(node: SourceFile) { + if (node.isDeclarationFile) emitTripleSlashDirectives(node.referencedFiles, node.typeReferenceDirectives); + } + + function emitTripleSlashDirectives(files: ReadonlyArray, types: ReadonlyArray) { + for (const directive of files) { + write(`/// `); + writeLine(); + } + for (const directive of types) { + write(`/// `); + writeLine(); + } + } + function emitSourceFileWorker(node: SourceFile) { const statements = node.statements; pushNameGenerationScope(node); emitHelpersIndirect(node); const index = findIndex(statements, statement => !isPrologueDirective(statement)); + emitTripleSlashDirectivesIfNeeded(node); emitList(node, statements, ListFormat.MultiLine, index === -1 ? statements.length : index); popNameGenerationScope(node); } @@ -2668,7 +2729,7 @@ namespace ts { if (format & ListFormat.BracketsMask) { writePunctuation(getOpeningBracket(format)); - if (isEmpty) { + if (isEmpty && !isUndefined) { emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists } } @@ -2796,7 +2857,7 @@ namespace ts { } if (format & ListFormat.BracketsMask) { - if (isEmpty) { + if (isEmpty && !isUndefined) { emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists } writePunctuation(getClosingBracket(format)); @@ -2927,21 +2988,6 @@ namespace ts { } } - function guessIndentation(lines: string[]) { - let indentation: number; - for (const line of lines) { - for (let i = 0; i < line.length && (indentation === undefined || i < indentation); i++) { - if (!isWhiteSpaceLike(line.charCodeAt(i))) { - if (indentation === undefined || i < indentation) { - indentation = i; - break; - } - } - } - } - return indentation; - } - function increaseIndentIf(value: boolean, valueToWriteWhenNotIndenting?: string) { if (value) { increaseIndent(); @@ -3239,8 +3285,15 @@ namespace ts { * in global scope. The name is formed by adding an '_n' suffix to the specified base name, * where n is a positive integer. Note that names generated by makeTempVariableName and * makeUniqueName are guaranteed to never conflict. + * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1' */ - function makeUniqueName(baseName: string): string { + function makeUniqueName(baseName: string, optimistic?: boolean): string { + if (optimistic) { + if (isUniqueName(baseName)) { + generatedNames.set(baseName, true); + return baseName; + } + } // Find the first unique 'name_n', where n is a positive number if (baseName.charCodeAt(baseName.length - 1) !== CharacterCodes._) { baseName += "_"; @@ -3335,6 +3388,8 @@ namespace ts { return makeTempVariableName(TempFlags._i, !!(name.autoGenerateFlags & GeneratedIdentifierFlags.ReservedInNestedScopes)); case GeneratedIdentifierFlags.Unique: return makeUniqueName(idText(name)); + case GeneratedIdentifierFlags.OptimisticUnique: + return makeUniqueName(idText(name), /*optimistic*/ true); } Debug.fail("Unsupported GeneratedIdentifierKind."); diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 507997c346de3..59936f0eb1eca 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -171,6 +171,15 @@ namespace ts { return name; } + /** Create a unique name based on the supplied text. */ + export function createOptimisticUniqueName(text: string): Identifier { + const name = createIdentifier(text); + name.autoGenerateFlags = GeneratedIdentifierFlags.OptimisticUnique; + name.autoGenerateId = nextAutoGenerateId; + nextAutoGenerateId++; + return name; + } + /** Create a unique name generated for a node. */ export function getGeneratedNameForNode(node: Node): Identifier; /* @internal */ export function getGeneratedNameForNode(node: Node, shouldSkipNameGenerationScope?: boolean): Identifier; // tslint:disable-line unified-signatures @@ -214,6 +223,28 @@ namespace ts { return >createSynthesizedNode(SyntaxKind.FalseKeyword); } + // Modifiers + + export function createModifier(kind: T) { + return createToken(kind); + } + + export function createModifiersFromModifierFlags(flags: ModifierFlags) { + const result: Modifier[] = []; + if (flags & ModifierFlags.Export) { result.push(createModifier(SyntaxKind.ExportKeyword)); } + if (flags & ModifierFlags.Ambient) { result.push(createModifier(SyntaxKind.DeclareKeyword)); } + if (flags & ModifierFlags.Default) { result.push(createModifier(SyntaxKind.DefaultKeyword)); } + if (flags & ModifierFlags.Const) { result.push(createModifier(SyntaxKind.ConstKeyword)); } + if (flags & ModifierFlags.Public) { result.push(createModifier(SyntaxKind.PublicKeyword)); } + if (flags & ModifierFlags.Private) { result.push(createModifier(SyntaxKind.PrivateKeyword)); } + if (flags & ModifierFlags.Protected) { result.push(createModifier(SyntaxKind.ProtectedKeyword)); } + if (flags & ModifierFlags.Abstract) { result.push(createModifier(SyntaxKind.AbstractKeyword)); } + if (flags & ModifierFlags.Static) { result.push(createModifier(SyntaxKind.StaticKeyword)); } + if (flags & ModifierFlags.Readonly) { result.push(createModifier(SyntaxKind.ReadonlyKeyword)); } + if (flags & ModifierFlags.Async) { result.push(createModifier(SyntaxKind.AsyncKeyword)); } + return result; + } + // Names export function createQualifiedName(left: EntityName, right: string | Identifier) { @@ -2349,8 +2380,13 @@ namespace ts { // Top-level nodes - export function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray) { - if (node.statements !== statements) { + export function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]) { + if ( + node.statements !== statements || + (isDeclarationFile !== undefined && node.isDeclarationFile !== isDeclarationFile) || + (referencedFiles !== undefined && node.referencedFiles !== referencedFiles) || + (typeReferences !== undefined && node.typeReferenceDirectives !== typeReferences) + ) { const updated = createSynthesizedNode(SyntaxKind.SourceFile); updated.flags |= node.flags; updated.statements = createNodeArray(statements); @@ -2358,12 +2394,12 @@ namespace ts { updated.fileName = node.fileName; updated.path = node.path; updated.text = node.text; + updated.isDeclarationFile = isDeclarationFile === undefined ? node.isDeclarationFile : isDeclarationFile; + updated.referencedFiles = referencedFiles === undefined ? node.referencedFiles : referencedFiles; + updated.typeReferenceDirectives = typeReferences === undefined ? node.typeReferenceDirectives : typeReferences; if (node.amdDependencies !== undefined) updated.amdDependencies = node.amdDependencies; if (node.moduleName !== undefined) updated.moduleName = node.moduleName; - if (node.referencedFiles !== undefined) updated.referencedFiles = node.referencedFiles; - if (node.typeReferenceDirectives !== undefined) updated.typeReferenceDirectives = node.typeReferenceDirectives; if (node.languageVariant !== undefined) updated.languageVariant = node.languageVariant; - if (node.isDeclarationFile !== undefined) updated.isDeclarationFile = node.isDeclarationFile; if (node.renamedDependencies !== undefined) updated.renamedDependencies = node.renamedDependencies; if (node.hasNoDefaultLib !== undefined) updated.hasNoDefaultLib = node.hasNoDefaultLib; if (node.languageVersion !== undefined) updated.languageVersion = node.languageVersion; @@ -2958,7 +2994,8 @@ namespace ts { requestEmitHelper: noop, resumeLexicalEnvironment: noop, startLexicalEnvironment: noop, - suspendLexicalEnvironment: noop + suspendLexicalEnvironment: noop, + addDiagnostic: noop, }; // Compound nodes @@ -3157,8 +3194,7 @@ namespace ts { return { value: o && o[i++], done: !o }; } }; - }; - ` + };` }; export function createValuesHelper(context: TransformationContext, expression: Expression, location?: TextRange) { @@ -3192,8 +3228,7 @@ namespace ts { finally { if (e) throw e.error; } } return ar; - }; - ` + };` }; export function createReadHelper(context: TransformationContext, iteratorRecord: Expression, count: number | undefined, location?: TextRange) { diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index 36b3db49fe0fb..e00218efaea08 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -52,6 +52,13 @@ namespace ts { } } + /*@internal*/ + export function isJSDocLikeText(text: string, start: number) { + return text.charCodeAt(start + 1) === CharacterCodes.asterisk && + text.charCodeAt(start + 2) === CharacterCodes.asterisk && + text.charCodeAt(start + 3) !== CharacterCodes.slash; + } + /** * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise, @@ -6219,7 +6226,7 @@ namespace ts { let result: JSDoc; // Check for /** (JSDoc opening part) - if (!isJsDocStart(content, start)) { + if (!isJSDocLikeText(content, start)) { return result; } @@ -6331,13 +6338,6 @@ namespace ts { } } - function isJsDocStart(content: string, start: number) { - return content.charCodeAt(start) === CharacterCodes.slash && - content.charCodeAt(start + 1) === CharacterCodes.asterisk && - content.charCodeAt(start + 2) === CharacterCodes.asterisk && - content.charCodeAt(start + 3) !== CharacterCodes.asterisk; - } - function createJSDocComment(): JSDoc { const result = createNode(SyntaxKind.JSDocComment, start); result.tags = tags && createNodeArray(tags, tagsPos, tagsEnd); diff --git a/src/compiler/sourcemap.ts b/src/compiler/sourcemap.ts index f6ad5e5c52faf..ee5e713a9ef6b 100644 --- a/src/compiler/sourcemap.ts +++ b/src/compiler/sourcemap.ts @@ -67,6 +67,11 @@ namespace ts { * Gets test data for source maps. */ getSourceMapData(): SourceMapData; + + /** + * @returns the previous disabled state + */ + setState(disabled: boolean): boolean; } // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans @@ -107,8 +112,15 @@ namespace ts { emitTokenWithSourceMap, getText, getSourceMappingURL, + setState, }; + function setState(state: boolean) { + const last = disabled; + disabled = state; + return last; + } + /** * Skips trivia such as comments and white-space that can optionally overriden by the source map source */ diff --git a/src/compiler/transformer.ts b/src/compiler/transformer.ts index 341c0c9cd45ec..c187176d069ad 100644 --- a/src/compiler/transformer.ts +++ b/src/compiler/transformer.ts @@ -11,6 +11,7 @@ /// /// /// +/// /* @internal */ namespace ts { @@ -104,6 +105,7 @@ namespace ts { let onSubstituteNode: TransformationContext["onSubstituteNode"] = (_, node) => node; let onEmitNode: TransformationContext["onEmitNode"] = (hint, node, callback) => callback(hint, node); let state = TransformationState.Uninitialized; + const diagnostics: Diagnostic[] = []; // The transformation context is provided to each transformer as part of transformer // initialization. @@ -134,6 +136,9 @@ namespace ts { Debug.assert(state < TransformationState.Initialized, "Cannot modify transformation hooks after initialization has completed."); Debug.assert(value !== undefined, "Value must not be 'undefined'"); onEmitNode = value; + }, + addDiagnostic(diag) { + diagnostics.push(diag); } }; @@ -163,7 +168,8 @@ namespace ts { transformed, substituteNode, emitNodeWithNotification, - dispose + dispose, + diagnostics }; function transformRoot(node: T) { diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts new file mode 100644 index 0000000000000..83128b9acb4b1 --- /dev/null +++ b/src/compiler/transformers/declarations.ts @@ -0,0 +1,1276 @@ +/// +/// +/// + +/*@internal*/ +namespace ts { + export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, file: SourceFile | undefined): Diagnostic[] { + if (file && isSourceFileJavaScript(file)) { + return []; // No declaration diagnostics for js for now + } + const compilerOptions = host.getCompilerOptions(); + const result = transformNodes(resolver, host, compilerOptions, file ? [file] : filter(host.getSourceFiles(), isSourceFileNotJavaScript), [transformDeclarations], /*allowDtsFiles*/ false); + return result.diagnostics; + } + + const declarationEmitNodeBuilderFlags = NodeBuilderFlags.MultilineObjectLiterals | TypeFormatFlags.WriteClassExpressionAsTypeLiteral | NodeBuilderFlags.UseTypeOfFunction | NodeBuilderFlags.UseStructuralFallback | NodeBuilderFlags.AllowEmptyTuple; + + /** + * Transforms a ts file into a .d.ts file + * This process requires type information, which is retrieved through the emit resolver. Because of this, + * in many places this transformer assumes it will be operating on parse tree nodes directly. + * This means that _no transforms should be allowed to occur before this one_. + */ + export function transformDeclarations(context: TransformationContext) { + const throwDiagnostic = () => Debug.fail("Diagnostic emitted without context"); + let getSymbolAccessibilityDiagnostic: GetSymbolAccessibilityDiagnostic = throwDiagnostic; + let needsDeclare = true; + let isBundledEmit = false; + let resultHasExternalModuleIndicator = false; + let enclosingDeclaration: Node; + let necessaryTypeRefernces: Map; + let possibleImports: AnyImportSyntax[]; + let importDeclarationMap: Map; + let suppressNewDiagnosticContexts: boolean; + + const symbolTracker: SymbolTracker = { + trackSymbol, + reportInaccessibleThisError, + reportInaccessibleUniqueSymbolError, + reportPrivateInBaseOfClassExpression + }; + let errorNameNode: DeclarationName | undefined; + + let currentSourceFile: SourceFile; + const resolver = context.getEmitResolver(); + const options = context.getCompilerOptions(); + const newLine = getNewLineCharacter(options); + const { noResolve, stripInternal } = options; + const host = context.getEmitHost(); + return transformRoot; + + function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives: string[]): void { + if (!typeReferenceDirectives) { + return; + } + necessaryTypeRefernces = necessaryTypeRefernces || createMap(); + for (const ref of typeReferenceDirectives) { + necessaryTypeRefernces.set(ref, true); + } + } + + function handleSymbolAccessibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) { + if (symbolAccessibilityResult.accessibility === SymbolAccessibility.Accessible) { + // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info + if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) { + if (!possibleImports) { + possibleImports = symbolAccessibilityResult.aliasesToMakeVisible; + } + else { + for (const ref of symbolAccessibilityResult.aliasesToMakeVisible) { + pushIfUnique(possibleImports, ref); + } + } + } + + // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible + } + else { + // Report error + const errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult); + if (errorInfo) { + if (errorInfo.typeName) { + context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, + errorInfo.diagnosticMessage, + getTextOfNode(errorInfo.typeName), + symbolAccessibilityResult.errorSymbolName, + symbolAccessibilityResult.errorModuleName)); + } + else { + context.addDiagnostic(createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, + errorInfo.diagnosticMessage, + symbolAccessibilityResult.errorSymbolName, + symbolAccessibilityResult.errorModuleName)); + } + } + } + } + + function trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags) { + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); + } + + function reportPrivateInBaseOfClassExpression(propertyName: string) { + if (errorNameNode) { + context.addDiagnostic( + createDiagnosticForNode(errorNameNode, Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName)); + } + } + + function reportInaccessibleUniqueSymbolError() { + if (errorNameNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, + declarationNameToString(errorNameNode), + "unique symbol")); + } + } + + function reportInaccessibleThisError() { + if (errorNameNode) { + context.addDiagnostic(createDiagnosticForNode(errorNameNode, Diagnostics.The_inferred_type_of_0_references_an_inaccessible_1_type_A_type_annotation_is_necessary, + declarationNameToString(errorNameNode), + "this")); + } + } + + function transformRoot(node: Bundle): Bundle; + function transformRoot(node: SourceFile): SourceFile; + function transformRoot(node: SourceFile | Bundle): SourceFile | Bundle; + function transformRoot(node: SourceFile | Bundle) { + if (node.kind === SyntaxKind.SourceFile && (node.isDeclarationFile || isSourceFileJavaScript(node))) { + return node; + } + + if (node.kind === SyntaxKind.Bundle) { + isBundledEmit = true; + const refs = createMap(); + const bundle = createBundle(map(node.sourceFiles, + sourceFile => { + if (sourceFile.isDeclarationFile || isSourceFileJavaScript(sourceFile)) return; // Omit declaration files from bundle results, too + currentSourceFile = sourceFile; + enclosingDeclaration = sourceFile; + possibleImports = undefined; + suppressNewDiagnosticContexts = false; + importDeclarationMap = createMap(); + getSymbolAccessibilityDiagnostic = throwDiagnostic; + collectReferences(sourceFile, refs); + if (isExternalModule(sourceFile)) { + resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules) + needsDeclare = false; + const statements = visitNodes(sourceFile.statements, visitDeclarationStatements); + const newFile = updateSourceFileNode(sourceFile, [createModuleDeclaration( + [], + [createModifier(SyntaxKind.DeclareKeyword)], + createLiteral(getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), + createModuleBlock(setTextRange(createNodeArray(filterCandidateImports(statements)), sourceFile.statements)) + )], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + return newFile; + } + needsDeclare = true; + const updated = visitNodes(sourceFile.statements, visitDeclarationStatements); + return updateSourceFileNode(sourceFile, updated, /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ []); + } + )); + bundle.syntheticFileReferences = []; + bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences(); + const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + const referenceVisitor = mapReferencesIntoArray(bundle.syntheticFileReferences as FileReference[], outputFilePath); + refs.forEach(referenceVisitor); + return bundle; + } + + // Single source file + needsDeclare = true; + enclosingDeclaration = node; + currentSourceFile = node; + getSymbolAccessibilityDiagnostic = throwDiagnostic; + isBundledEmit = false; + resultHasExternalModuleIndicator = false; + suppressNewDiagnosticContexts = false; + possibleImports = undefined; + importDeclarationMap = createMap(); + necessaryTypeRefernces = undefined; + const refs = collectReferences(currentSourceFile, createMap()); + const references: FileReference[] = []; + const outputFilePath = getDirectoryPath(normalizeSlashes(getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath)); + const referenceVisitor = mapReferencesIntoArray(references, outputFilePath); + refs.forEach(referenceVisitor); + const statements = visitNodes(node.statements, visitDeclarationStatements); + let combinedStatements = setTextRange(createNodeArray(filterCandidateImports(statements)), node.statements); + if (isExternalModule(node) && !resultHasExternalModuleIndicator) { + combinedStatements = setTextRange(createNodeArray([...combinedStatements, createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, createNamedExports([]), /*moduleSpecifier*/ undefined)]), combinedStatements); + } + const updated = updateSourceFileNode(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences()); + return updated; + + function getFileReferencesForUsedTypeReferences() { + return necessaryTypeRefernces ? map(arrayFrom(necessaryTypeRefernces.keys()), getFileReferenceForTypeName) : []; + } + + function getFileReferenceForTypeName(typeName: string): FileReference { + return { fileName: typeName, pos: -1, end: -1 }; + } + + function mapReferencesIntoArray(references: FileReference[], outputFilePath: string): (file: SourceFile) => void { + return file => { + let declFileName: string; + if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed + declFileName = file.fileName; + } + else { + if (isBundledEmit && contains((node as Bundle).sourceFiles, file)) return; // Omit references to files which are being merged + const paths = getOutputPathsFor(file, host, /*forceDtsPaths*/ true); + declFileName = paths.declarationFilePath || paths.jsFilePath; + } + + if (declFileName) { + let fileName = getRelativePathToDirectoryOrUrl( + outputFilePath, + declFileName, + host.getCurrentDirectory(), + host.getCanonicalFileName, + /*isAbsolutePathAnUrl*/ false + ); + if (startsWith(fileName, "./") && hasExtension(fileName)) { + fileName = fileName.substring(2); + } + references.push({ pos: -1, end: -1, fileName }); + } + }; + } + } + + function collectReferences(sourceFile: SourceFile, ret: Map) { + if (noResolve || isSourceFileJavaScript(sourceFile)) return ret; + forEach(sourceFile.referencedFiles, f => { + const elem = tryResolveScriptReference(host, sourceFile, f); + if (elem) { + ret.set("" + getNodeId(elem), elem); + } + }); + return ret; + } + + function filterBindingPatternInitializers(name: BindingName) { + if (name.kind === SyntaxKind.Identifier) { + return name; + } + else { + if (name.kind === SyntaxKind.ArrayBindingPattern) { + return updateArrayBindingPattern(name, visitNodes(name.elements, visitBindingElement)); + } + else { + return updateObjectBindingPattern(name, visitNodes(name.elements, visitBindingElement)); + } + } + + function visitBindingElement(elem: T): T; + function visitBindingElement(elem: ArrayBindingElement): ArrayBindingElement { + if (elem.kind === SyntaxKind.OmittedExpression) { + return elem; + } + return updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined); + } + } + + function ensureParameter(p: ParameterDeclaration, modifierMask?: ModifierFlags): ParameterDeclaration { + let oldDiag: typeof getSymbolAccessibilityDiagnostic; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(p); + } + const newParam = updateParameter( + p, + /*decorators*/ undefined, + maskModifiers(p, modifierMask), + p.dotDotDotToken, + filterBindingPatternInitializers(p.name), + resolver.isOptionalParameter(p) ? (p.questionToken || createToken(SyntaxKind.QuestionToken)) : undefined, + ensureType(p, p.type, /*ignorePrivate*/ true), // Ignore private param props, since this type is going straight back into a param + ensureNoInitializer(p) + ); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return newParam; + } + + function shouldPrintWithInitializer(node: Node) { + return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(getParseTreeNode(node) as CanHaveLiteralInitializer); // TODO: Make safe + } + + function ensureNoInitializer(node: CanHaveLiteralInitializer) { + if (shouldPrintWithInitializer(node)) { + return resolver.createLiteralConstValue(getParseTreeNode(node) as CanHaveLiteralInitializer); // TODO: Make safe + } + return undefined; + } + + type HasInferredType = + | FunctionDeclaration + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration + | BindingElement + | ConstructSignatureDeclaration + | VariableDeclaration + | MethodSignature + | CallSignatureDeclaration + | ParameterDeclaration + | PropertyDeclaration + | PropertySignature; + + function ensureType(node: HasInferredType, type: TypeNode, ignorePrivate?: boolean): TypeNode { + if (!ignorePrivate && hasModifier(node, ModifierFlags.Private)) { + // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible) + return; + } + if (shouldPrintWithInitializer(node)) { + // Literal const declarations will have an initializer ensured rather than a type + return; + } + const shouldUseResolverType = node.kind === SyntaxKind.Parameter && + (resolver.isRequiredInitializedParameter(node) || + resolver.isOptionalUninitializedParameterProperty(node)); + if (type && !shouldUseResolverType) { + return visitNode(type, visitDeclarationSubtree); + } + if (!getParseTreeNode(node)) { + return type ? visitNode(type, visitDeclarationSubtree) : createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + if (node.kind === SyntaxKind.SetAccessor) { + // Set accessors with no associated type node (from it's param or get accessor return) are `any` since they are never contextually typed right now + // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that) + return createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + errorNameNode = node.name; + let oldDiag: typeof getSymbolAccessibilityDiagnostic; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(node); + } + if (node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement) { + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + if (node.kind === SyntaxKind.Parameter + || node.kind === SyntaxKind.PropertyDeclaration + || node.kind === SyntaxKind.PropertySignature) { + if (!node.initializer) return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType)); + return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + } + return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker)); + + function cleanup(returnValue: TypeNode | undefined) { + errorNameNode = undefined; + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + return returnValue || createKeywordTypeNode(SyntaxKind.AnyKeyword); + } + } + + function isDeclarationAndNotVisible(node: NamedDeclaration) { + node = getParseTreeNode(node) as NamedDeclaration; + switch (node.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.EnumDeclaration: + return !resolver.isDeclarationVisible(node); + // The following should be doing their own visibility checks based on filtering their members + case SyntaxKind.VariableDeclaration: + return !getBindingNameVisible(node as VariableDeclaration); + case SyntaxKind.ImportEqualsDeclaration: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + case SyntaxKind.ExportAssignment: + return false; + } + return false; + } + + function getBindingNameVisible(elem: BindingElement | VariableDeclaration | OmittedExpression): boolean { + if (isOmittedExpression(elem)) { + return false; + } + if (isBindingPattern(elem.name)) { + // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible + return forEach(elem.name.elements, getBindingNameVisible); + } + else { + return resolver.isDeclarationVisible(elem); + } + } + + function updateParamsList(node: Node, params: NodeArray, modifierMask?: ModifierFlags) { + if (hasModifier(node, ModifierFlags.Private)) { + return undefined; + } + const newParams = map(params, p => ensureParameter(p, modifierMask)); + if (!newParams) { + return undefined; + } + return createNodeArray(newParams, params.hasTrailingComma); + } + + function ensureTypeParams(node: Node, params: NodeArray) { + return hasModifier(node, ModifierFlags.Private) ? undefined : visitNodes(params, visitDeclarationSubtree); + } + + function isEnclosingDeclaration(node: Node) { + return isSourceFile(node) + || isTypeAliasDeclaration(node) + || isModuleDeclaration(node) + || isClassDeclaration(node) + || isInterfaceDeclaration(node) + || isFunctionLike(node) + || isIndexSignatureDeclaration(node) + || isMappedTypeNode(node); + } + + function checkEntityNameVisibility(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node) { + const visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration); + handleSymbolAccessibilityError(visibilityResult); + recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName)); + } + + function preserveJsDoc(updated: T, original: Node): T { + if (hasJSDocNodes(updated) && hasJSDocNodes(original)) { + updated.jsDoc = original.jsDoc; + } + return setCommentRange(updated, getCommentRange(original)); + } + + function rewriteModuleSpecifier(parent: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration, input: T): T | StringLiteral { + if (!input) return; + resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || parent.kind !== SyntaxKind.ModuleDeclaration; + if (input.kind === SyntaxKind.StringLiteral && isBundledEmit) { + const newName = getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent); + if (newName) { + return createLiteral(newName); + } + } + return input; + } + + function transformImportEqualsDeclaration(decl: ImportEqualsDeclaration) { + if (!resolver.isDeclarationVisible(decl)) return; + if (decl.moduleReference.kind === SyntaxKind.ExternalModuleReference) { + // Rewrite external module names if necessary + const specifier = getExternalModuleImportEqualsDeclarationExpression(decl); + return updateImportEqualsDeclaration( + decl, + /*decorators*/ undefined, + decl.modifiers, + decl.name, + updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)) + ); + } + else { + const oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(decl); + checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration); + getSymbolAccessibilityDiagnostic = oldDiag; + return decl; + } + } + + function transformImportDeclaration(decl: ImportDeclaration) { + if (!decl.importClause) { + // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc) + return updateImportDeclaration( + decl, + /*decorators*/ undefined, + decl.modifiers, + decl.importClause, + rewriteModuleSpecifier(decl, decl.moduleSpecifier) + ); + } + // The `importClause` visibility corresponds to the default's visibility. + const visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined; + if (!decl.importClause.namedBindings) { + // No named bindings (either namespace or list), meaning the import is just default or should be elided + return visibleDefaultBinding && updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, updateImportClause( + decl.importClause, + visibleDefaultBinding, + /*namedBindings*/ undefined + ), rewriteModuleSpecifier(decl, decl.moduleSpecifier)); + } + if (decl.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) { + // Namespace import (optionally with visible default) + const namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined; + return visibleDefaultBinding || namedBindings ? updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, updateImportClause( + decl.importClause, + visibleDefaultBinding, + namedBindings + ), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined; + } + // Named imports (optionally with visible default) + const bindingList = mapDefined(decl.importClause.namedBindings.elements, b => resolver.isDeclarationVisible(b) ? b : undefined); + if ((bindingList && bindingList.length) || visibleDefaultBinding) { + return updateImportDeclaration( + decl, + /*decorators*/ undefined, + decl.modifiers, + updateImportClause( + decl.importClause, + visibleDefaultBinding, + bindingList && bindingList.length ? updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined + ), + rewriteModuleSpecifier(decl, decl.moduleSpecifier) + ); + } + // Nothing visible + } + + function filterCandidateImports(statements: ReadonlyArray): ReadonlyArray { + // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during + // error handling which must now be included in the output and themselves checked for errors. + // For example: + // ``` + // module A { + // export module Q {} + // import B = Q; + // import C = B; + // export import D = C; + // } + // ``` + // In such a scenario, only Q and D are initially visible, but we don't consider imports as private names - instead we say they if they are referenced they must + // be recorded. So while checking D's visibility we mark C as visible, then we must check C which in turn marks B, completing the chain of + // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases. + const unconsideredImports: AnyImportSyntax[] = []; + while (length(possibleImports)) { + const i = possibleImports.shift(); + if ((isSourceFile(i.parent) ? i.parent : i.parent.parent) !== enclosingDeclaration) { // Filter to only declarations in the current scope + unconsideredImports.push(i); + continue; + } + // Eagerly transform import equals - if they're not visible, we'll get nothing, if they are, we'll immediately add them since it's complete + if (i.kind === SyntaxKind.ImportEqualsDeclaration) { + const result = transformImportEqualsDeclaration(i); + importDeclarationMap.set("" + getNodeId(i), result); + continue; + } + // Import declarations, on the other hand, can be partially painted by multiple aliases; so we can see many indeterminate states + // until we've marked all possible visibility + const result = transformImportDeclaration(i); + importDeclarationMap.set("" + getNodeId(i), result); + } + // Filtering available imports is the last thing done within a scope, so the possible set becomes those which could not + // be considered in the child scope + possibleImports = unconsideredImports; + // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list + // (and remove them from the set to examine for outter declarations) + return mapDefined(statements, statement => { + if (isImportDeclaration(statement) || isImportEqualsDeclaration(statement)) { + const key = "" + getNodeId(statement); + if (importDeclarationMap.has(key)) { + const result = importDeclarationMap.get(key); + importDeclarationMap.delete(key); + return result; + } + else { + return undefined; + } + } + else { + return statement; + } + }); + } + + function visitDeclarationSubtree(input: Node): VisitResult { + if (shouldStripInternal(input)) return; + if (isDeclaration(input)) { + if (isDeclarationAndNotVisible(input)) return; + if (hasDynamicName(input) && !resolver.isLateBound(getParseTreeNode(input) as Declaration)) { + return; + } + } + + // Elide implementation signatures from overload sets + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; + + // Elide semicolon class statements + if (isSemicolonClassElement(input)) return; + + let previousEnclosingDeclaration: typeof enclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input as Declaration; + } + const oldDiag = getSymbolAccessibilityDiagnostic; + + // Emit methods which are private as properties with no type information + if (isMethodDeclaration(input) || isMethodSignature(input)) { + if (hasModifier(input, ModifierFlags.Private)) { + if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input) return; // Elide all but the first overload + return cleanup(createProperty(/*decorators*/undefined, input.modifiers, input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined)); + } + } + + const canProdiceDiagnostic = canProduceDiagnostics(input); + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input as DeclarationDiagnosticProducing); + } + + if (isTypeQueryNode(input)) { + checkEntityNameVisibility(input.exprName, enclosingDeclaration); + } + + const oldWithinObjectLiteralType = suppressNewDiagnosticContexts; + let shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === SyntaxKind.TypeLiteral || input.kind === SyntaxKind.MappedType) && input.parent.kind !== SyntaxKind.TypeAliasDeclaration); + if (shouldEnterSuppressNewDiagnosticsContextContext) { + // We stop making new diagnostic contexts within object literal types. Unless it's an object type on the RHS of a type alias declaration. Then we do. + suppressNewDiagnosticContexts = true; + } + + if (isProcessedComponent(input)) { + switch (input.kind) { + case SyntaxKind.ExpressionWithTypeArguments: { + if ((isEntityName(input.expression) || isEntityNameExpression(input.expression))) { + checkEntityNameVisibility(input.expression, enclosingDeclaration); + } + const node = visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(updateExpressionWithTypeArguments(node, parenthesizeTypeParameters(node.typeArguments), node.expression)); + } + case SyntaxKind.TypeReference: { + checkEntityNameVisibility(input.typeName, enclosingDeclaration); + const node = visitEachChild(input, visitDeclarationSubtree, context); + return cleanup(updateTypeReferenceNode(node, node.typeName, parenthesizeTypeParameters(node.typeArguments))); + } + case SyntaxKind.ConstructSignature: + return cleanup(updateConstructSignature( + input, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input, input.type) + )); + case SyntaxKind.Constructor: { + const isPrivate = hasModifier(input, ModifierFlags.Private); + // A constructor declaration may not have a type annotation + const ctor = createSignatureDeclaration( + SyntaxKind.Constructor, + isPrivate ? undefined : ensureTypeParams(input, input.typeParameters), + isPrivate ? undefined : updateParamsList(input, input.parameters, ModifierFlags.None), + /*type*/ undefined + ); + ctor.modifiers = createNodeArray(ensureModifiers(input)); + return cleanup(ctor); + } + case SyntaxKind.MethodDeclaration: { + const sig = createSignatureDeclaration( + SyntaxKind.MethodSignature, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input, input.type) + ) as MethodSignature; + sig.name = input.name; + sig.modifiers = createNodeArray(ensureModifiers(input)); + sig.questionToken = input.questionToken; + return cleanup(sig); + } + case SyntaxKind.GetAccessor: { + const newNode = ensureAccessor(input); + return cleanup(newNode); + } + case SyntaxKind.SetAccessor: { + const newNode = ensureAccessor(input); + return cleanup(newNode); + } + case SyntaxKind.PropertyDeclaration: + return cleanup(updateProperty( + input, + /*decorators*/ undefined, + ensureModifiers(input), + input.name, + input.questionToken, + !hasModifier(input, ModifierFlags.Private) ? ensureType(input, input.type) : undefined, + ensureNoInitializer(input) + )); + case SyntaxKind.PropertySignature: + return cleanup(updatePropertySignature( + input, + ensureModifiers(input), + input.name, + input.questionToken, + !hasModifier(input, ModifierFlags.Private) ? ensureType(input, input.type) : undefined, + ensureNoInitializer(input) + )); + case SyntaxKind.MethodSignature: { + return cleanup(updateMethodSignature( + input, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input, input.type), + input.name, + input.questionToken + )); + } + case SyntaxKind.CallSignature: { + return cleanup(updateCallSignature( + input, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input, input.type) + )); + } + case SyntaxKind.IndexSignature: { + return cleanup(updateIndexSignature( + input, + /*decorators*/ undefined, + ensureModifiers(input), + updateParamsList(input, input.parameters), + visitNode(input.type, visitDeclarationSubtree) || createKeywordTypeNode(SyntaxKind.AnyKeyword) + )); + } + case SyntaxKind.VariableDeclaration: { + if (isBindingPattern(input.name)) { + return recreateBindingPattern(input.name); + } + shouldEnterSuppressNewDiagnosticsContextContext = true; + suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types + return cleanup(updateVariableDeclaration(input, input.name, ensureType(input, input.type), ensureNoInitializer(input))); + } + case SyntaxKind.TypeParameter: { + if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) { + return cleanup(updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined)); + } + return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); + } + case SyntaxKind.ConditionalType: { + // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration + // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type. + const checkType = visitNode(input.checkType, visitDeclarationSubtree); + const extendsType = visitNode(input.extendsType, visitDeclarationSubtree); + const oldEnclosingDecl = enclosingDeclaration; + enclosingDeclaration = input.trueType; + const trueType = visitNode(input.trueType, visitDeclarationSubtree); + enclosingDeclaration = oldEnclosingDecl; + const falseType = visitNode(input.falseType, visitDeclarationSubtree); + return cleanup(updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType)); + } + case SyntaxKind.FunctionType: { + return cleanup(updateFunctionTypeNode(input, visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), visitNode(input.type, visitDeclarationSubtree))); + } + case SyntaxKind.ConstructorType: { + return cleanup(updateConstructorTypeNode(input, visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), visitNode(input.type, visitDeclarationSubtree))); + } + default: Debug.assertNever(input, `Attempted to process unhandled node kind: ${(ts as any).SyntaxKind[(input as any).kind]}`); + } + } + + return cleanup(visitEachChild(input, visitDeclarationSubtree, context)); + + function cleanup(returnValue: T | undefined): T { + if (returnValue && canProdiceDiagnostic && hasDynamicName(input as Declaration)) { + checkName(input as DeclarationDiagnosticProducing); + } + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (canProdiceDiagnostic && !suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (shouldEnterSuppressNewDiagnosticsContextContext) { + suppressNewDiagnosticContexts = oldWithinObjectLiteralType; + } + if (returnValue === input) { + return returnValue; + } + return returnValue && setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + + function isPrivateMethodTypeParameter(node: TypeParameterDeclaration) { + return node.parent.kind === SyntaxKind.MethodDeclaration && hasModifier(node.parent, ModifierFlags.Private); + } + + function visitDeclarationStatements(input: Node): VisitResult { + if (!isPreservedDeclarationStatement(input)) { + // return undefined for unmatched kinds to omit them from the tree + return; + } + if (shouldStripInternal(input)) return; + + switch (input.kind) { + case SyntaxKind.ExportDeclaration: { + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + // Always visible if the parent node isn't dropped for being not visible + // Rewrite external module names if necessary + return updateExportDeclaration(input, /*decorators*/ undefined, input.modifiers, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier)); + } + case SyntaxKind.ExportAssignment: { + // Always visible if the parent node isn't dropped for being not visible + if (isSourceFile(input.parent)) { + resultHasExternalModuleIndicator = true; + } + if (input.expression.kind === SyntaxKind.Identifier) { + return input; + } + else { + const newId = createOptimisticUniqueName("_default"); + getSymbolAccessibilityDiagnostic = () => ({ + diagnosticMessage: Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0, + errorNode: input + }); + const varDecl = createVariableDeclaration(newId, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + const statement = createVariableStatement(needsDeclare ? [createModifier(SyntaxKind.DeclareKeyword)] : [], createVariableDeclarationList([varDecl], NodeFlags.Const)); + return [statement, updateExportAssignment(input, input.decorators, input.modifiers, newId)]; + } + } + case SyntaxKind.ImportEqualsDeclaration: + case SyntaxKind.ImportDeclaration: { + // Different parts of the import may be marked visible at different times (via visibility checking), so we defer our first look until later + // to reduce the likelihood we need to rewrite it + possibleImports = possibleImports || []; + pushIfUnique(possibleImports, input); + return input; + } + } + if (isDeclaration(input) && isDeclarationAndNotVisible(input)) return; + + // Elide implementation signatures from overload sets + if (isFunctionLike(input) && resolver.isImplementationOfOverload(input)) return; + + let previousEnclosingDeclaration: typeof enclosingDeclaration; + if (isEnclosingDeclaration(input)) { + previousEnclosingDeclaration = enclosingDeclaration; + enclosingDeclaration = input as Declaration; + } + let previousNeedsDeclare: typeof needsDeclare; + + const canProdiceDiagnostic = canProduceDiagnostics(input); + const oldDiag = getSymbolAccessibilityDiagnostic; + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(input as DeclarationDiagnosticProducing); + } + let oldPossibleImports: typeof possibleImports; + + switch (input.kind) { + case SyntaxKind.TypeAliasDeclaration: // Type aliases get `declare`d if need be (for legacy support), but that's all + return cleanup(updateTypeAliasDeclaration( + input, + /*decorators*/ undefined, + ensureModifiers(input), + input.name, + visitNodes(input.typeParameters, visitDeclarationSubtree, isTypeParameterDeclaration), + visitNode(input.type, visitDeclarationSubtree, isTypeNode) + )); + case SyntaxKind.InterfaceDeclaration: { + return cleanup(updateInterfaceDeclaration( + input, + /*decorators*/ undefined, + ensureModifiers(input), + input.name, + ensureTypeParams(input, input.typeParameters), + transformHeritageClauses(input.heritageClauses), + visitNodes(input.members, visitDeclarationSubtree) + )); + } + case SyntaxKind.FunctionDeclaration: { + // Generators lose their generator-ness, excepting their return type + return cleanup(updateFunctionDeclaration( + input, + /*decorators*/ undefined, + ensureModifiers(input), + /*asteriskToken*/ undefined, + input.name, + ensureTypeParams(input, input.typeParameters), + updateParamsList(input, input.parameters), + ensureType(input, input.type), + /*body*/ undefined + )); + } + case SyntaxKind.ModuleDeclaration: { + previousNeedsDeclare = needsDeclare; + needsDeclare = false; + oldPossibleImports = possibleImports; + possibleImports = undefined; + const inner = input.body; + if (inner && inner.kind === SyntaxKind.ModuleBlock) { + const statements = visitNodes(inner.statements, visitDeclarationStatements); + const body = updateModuleBlock(inner, filterCandidateImports(statements)); + needsDeclare = previousNeedsDeclare; + const mods = ensureModifiers(input); + return cleanup(updateModuleDeclaration( + input, + /*decorators*/ undefined, + mods, + isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, + body + )); + } + else { + needsDeclare = previousNeedsDeclare; + const mods = ensureModifiers(input); + needsDeclare = false; + return cleanup(updateModuleDeclaration( + input, + /*decorators*/ undefined, + mods, + input.name, + visitNode(inner, visitDeclarationStatements) + )); + } + } + case SyntaxKind.ClassDeclaration: { + const modifiers = createNodeArray(ensureModifiers(input)); + const typeParameters = ensureTypeParams(input, input.typeParameters); + const ctor = getFirstConstructorWithBody(input); + let parameterProperties: PropertyDeclaration[]; + if (ctor) { + const oldDiag = getSymbolAccessibilityDiagnostic; + parameterProperties = compact(flatMap(ctor.parameters, param => { + if (!hasModifier(param, ModifierFlags.ParameterPropertyModifier)) return; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(param); + if (param.name.kind === SyntaxKind.Identifier) { + return preserveJsDoc(createProperty( + /*decorators*/ undefined, + ensureModifiers(param), + param.name, + param.questionToken, + ensureType(param, param.type), + ensureNoInitializer(param)), param); + } + else { + // Pattern - this is currently an error, but we emit declarations for it somewhat correctly + return walkBindingPattern(param.name); + } + + function walkBindingPattern(pattern: BindingPattern) { + let elems: PropertyDeclaration[]; + for (const elem of pattern.elements) { + if (isOmittedExpression(elem)) continue; + if (isBindingPattern(elem.name)) { + elems = concatenate(elems, walkBindingPattern(elem.name)); + } + elems = elems || []; + elems.push(createProperty( + /*decorators*/ undefined, + ensureModifiers(param), + elem.name as Identifier, + /*questionToken*/ undefined, + ensureType(elem, /*type*/ undefined), + /*initializer*/ undefined + )); + } + return elems; + } + })); + getSymbolAccessibilityDiagnostic = oldDiag; + } + const members = createNodeArray(concatenate(parameterProperties, visitNodes(input.members, visitDeclarationSubtree))); + + const extendsClause = getClassExtendsHeritageClauseElement(input); + if (extendsClause && !isEntityNameExpression(extendsClause.expression) && extendsClause.expression.kind !== SyntaxKind.NullKeyword) { + // We must add a temporary declaration for the extends clause expression + + const newId = createOptimisticUniqueName(`${unescapeLeadingUnderscores(input.name.escapedText)}_base`); + getSymbolAccessibilityDiagnostic = () => ({ + diagnosticMessage: Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1, + errorNode: extendsClause, + typeName: input.name + }); + const varDecl = createVariableDeclaration(newId, resolver.createTypeOfExpression(extendsClause.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined); + const statement = createVariableStatement(needsDeclare ? [createModifier(SyntaxKind.DeclareKeyword)] : [], createVariableDeclarationList([varDecl], NodeFlags.Const)); + const heritageClauses = createNodeArray(map(input.heritageClauses, clause => { + if (clause.token === SyntaxKind.ExtendsKeyword) { + const oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]); + const newClause = updateHeritageClause(clause, map(clause.types, t => updateExpressionWithTypeArguments(t, visitNodes(t.typeArguments, visitDeclarationSubtree), newId))); + getSymbolAccessibilityDiagnostic = oldDiag; + return newClause; + } + return updateHeritageClause(clause, visitNodes(createNodeArray(filter(clause.types, t => isEntityNameExpression(t.expression) || t.expression.kind === SyntaxKind.NullKeyword)), visitDeclarationSubtree)); + })); + return [statement, cleanup(updateClassDeclaration( + input, + /*decorators*/ undefined, + modifiers, + input.name, + typeParameters, + heritageClauses, + members + ))]; + } + else { + const heritageClauses = transformHeritageClauses(input.heritageClauses); + return cleanup(updateClassDeclaration( + input, + /*decorators*/ undefined, + modifiers, + input.name, + typeParameters, + heritageClauses, + members + )); + } + } + case SyntaxKind.VariableStatement: { + if (!forEach(input.declarationList.declarations, getBindingNameVisible)) return; + const nodes = visitNodes(input.declarationList.declarations, visitDeclarationSubtree); + if (!length(nodes)) return; + return cleanup(updateVariableStatement(input, createNodeArray(ensureModifiers(input)), updateVariableDeclarationList(input.declarationList, nodes))); + } + case SyntaxKind.EnumDeclaration: { + return cleanup(updateEnumDeclaration(input, /*decorators*/ undefined, createNodeArray(ensureModifiers(input)), input.name, createNodeArray(mapDefined(input.members, m => { + if (shouldStripInternal(m)) return; + // Rewrite enum values to their constants, if available + const constValue = resolver.getConstantValue(m); + return preserveJsDoc(updateEnumMember(m, m.name, constValue !== undefined ? createLiteral(constValue) : undefined), m); + })))); + } + } + + // Anything left unhandled is an error, so this should be unreachable + return Debug.assertNever(input, `Unhandled top-level node in declaration emit: ${(ts as any).SyntaxKind[(input as any).kind]}`); + + function cleanup(returnValue: T | undefined): T { + if (isEnclosingDeclaration(input)) { + enclosingDeclaration = previousEnclosingDeclaration; + } + if (input.kind === SyntaxKind.ModuleDeclaration) { + needsDeclare = previousNeedsDeclare; + possibleImports = concatenate(oldPossibleImports, possibleImports); + } + if (canProdiceDiagnostic) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + if (returnValue) { + if (!resultHasExternalModuleIndicator && hasModifier(input, ModifierFlags.Export) && isSourceFile(input.parent)) { + // Exported top-level member indicates moduleness + resultHasExternalModuleIndicator = true; + } + } + if (returnValue === input) { + return returnValue; + } + return returnValue && setOriginalNode(preserveJsDoc(returnValue, input), input); + } + } + + function recreateBindingPattern(d: BindingPattern): VariableDeclaration[] { + return flatten(mapDefined(d.elements, e => recreateBindingElement(e))); + } + + function recreateBindingElement(e: ArrayBindingElement) { + if (e.kind === SyntaxKind.OmittedExpression) { + return; + } + if (e.name) { + if (!getBindingNameVisible(e)) return; + if (isBindingPattern(e.name)) { + return recreateBindingPattern(e.name); + } + else { + return createVariableDeclaration(e.name, ensureType(e, /*type*/ undefined), /*initializer*/ undefined); + } + } + } + + function checkName(node: DeclarationDiagnosticProducing) { + let oldDiag: typeof getSymbolAccessibilityDiagnostic; + if (!suppressNewDiagnosticContexts) { + oldDiag = getSymbolAccessibilityDiagnostic; + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNodeName(node); + } + errorNameNode = (node as NamedDeclaration).name; + Debug.assert(resolver.isLateBound(getParseTreeNode(node) as Declaration)); // Should only be called with dynamic names + const decl = node as NamedDeclaration as LateBoundDeclaration; + const entityName = decl.name.expression; + checkEntityNameVisibility(entityName, enclosingDeclaration); + if (!suppressNewDiagnosticContexts) { + getSymbolAccessibilityDiagnostic = oldDiag; + } + errorNameNode = undefined; + } + + function hasInternalAnnotation(range: CommentRange) { + const comment = currentSourceFile.text.substring(range.pos, range.end); + return stringContains(comment, "@internal"); + } + + function shouldStripInternal(node: Node) { + if (stripInternal && node) { + const leadingCommentRanges = getLeadingCommentRangesOfNode(getParseTreeNode(node), currentSourceFile); + if (forEach(leadingCommentRanges, hasInternalAnnotation)) { + return true; + } + } + return false; + } + + function ensureModifiers(node: Node): ReadonlyArray { + const currentFlags = getModifierFlags(node); + const newFlags = ensureModifierFlags(node); + if (currentFlags === newFlags) { + return node.modifiers; + } + return createModifiersFromModifierFlags(newFlags); + } + + function ensureModifierFlags(node: Node): ModifierFlags { + let mask = ModifierFlags.All ^ (ModifierFlags.Public | ModifierFlags.Async); // No async modifiers in declaration files + let additions = (needsDeclare && !isAlwaysType(node)) ? ModifierFlags.Ambient : ModifierFlags.None; + const parentIsFile = node.parent.kind === SyntaxKind.SourceFile; + if (!parentIsFile || (isBundledEmit && parentIsFile && isExternalModule(node.parent as SourceFile))) { + mask ^= ((isBundledEmit && parentIsFile ? 0 : ModifierFlags.Export) | ModifierFlags.Default | ModifierFlags.Ambient); + additions = ModifierFlags.None; + } + return maskModifierFlags(node, mask, additions); + } + + function ensureAccessor(node: AccessorDeclaration): PropertyDeclaration | undefined { + const accessors = getAllAccessorDeclarations((node.parent as ClassDeclaration).members, node); + if (node.kind !== accessors.firstAccessor.kind) { + return; + } + let accessorType = getTypeAnnotationFromAccessor(node); + if (!accessorType && accessors.secondAccessor) { + accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor); + // If we end up pulling the type from the second accessor, we also need to change the diagnostic context to get the expected error message + getSymbolAccessibilityDiagnostic = createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor); + } + const prop = createProperty(/*decorators*/ undefined, maskModifiers(node, /*mask*/ undefined, (!accessors.setAccessor) ? ModifierFlags.Readonly : ModifierFlags.None), node.name, node.questionToken, ensureType(node, accessorType), /*initializer*/ undefined); + const leadingsSyntheticCommentRanges = accessors.secondAccessor && getLeadingCommentRangesOfNode(accessors.secondAccessor, currentSourceFile); + if (leadingsSyntheticCommentRanges) { + for (const range of leadingsSyntheticCommentRanges) { + if (range.kind === SyntaxKind.MultiLineCommentTrivia) { + let text = currentSourceFile.text.slice(range.pos + 2, range.end - 2); + const lines = text.split(/\r\n?|\n/g); + if (lines.length > 1) { + const lastLines = lines.slice(1); + const indentation = guessIndentation(lastLines); + text = [lines[0], ...map(lastLines, l => l.slice(indentation))].join(newLine); + } + addSyntheticLeadingComment( + prop, + range.kind, + text, + range.hasTrailingNewLine + ); + } + } + } + return prop; + } + + function transformHeritageClauses(nodes: NodeArray) { + return createNodeArray(filter(map(nodes, clause => updateHeritageClause(clause, visitNodes(createNodeArray(filter(clause.types, t => { + return isEntityNameExpression(t.expression) || (clause.token === SyntaxKind.ExtendsKeyword && t.expression.kind === SyntaxKind.NullKeyword); + })), visitDeclarationSubtree))), clause => clause.types && !!clause.types.length)); + } + } + + function isAlwaysType(node: Node) { + if (node.kind === SyntaxKind.InterfaceDeclaration) { + return true; + } + return false; + } + + // Elide "public" modifier, as it is the default + function maskModifiers(node: Node, modifierMask?: ModifierFlags, modifierAdditions?: ModifierFlags): Modifier[] { + return createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions)); + } + + function maskModifierFlags(node: Node, modifierMask: ModifierFlags = ModifierFlags.All ^ ModifierFlags.Public, modifierAdditions: ModifierFlags = ModifierFlags.None): ModifierFlags { + let flags = (getModifierFlags(node) & modifierMask) | modifierAdditions; + if (flags & ModifierFlags.Default && flags & ModifierFlags.Ambient) { + flags ^= ModifierFlags.Ambient; // `declare` is never required alongside `default` (and would be an error if printed) + } + return flags; + } + + function getTypeAnnotationFromAccessor(accessor: AccessorDeclaration): TypeNode { + if (accessor) { + return accessor.kind === SyntaxKind.GetAccessor + ? accessor.type // Getter - return type + : accessor.parameters.length > 0 + ? accessor.parameters[0].type // Setter parameter type + : undefined; + } + } + + type CanHaveLiteralInitializer = VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration; + function canHaveLiteralInitializer(node: Node): node is CanHaveLiteralInitializer { + switch (node.kind) { + case SyntaxKind.VariableDeclaration: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertySignature: + case SyntaxKind.Parameter: + return true; + } + return false; + } + + type ProcessedDeclarationStatement = + | FunctionDeclaration + | ModuleDeclaration + | ImportEqualsDeclaration + | InterfaceDeclaration + | ClassDeclaration + | TypeAliasDeclaration + | EnumDeclaration + | VariableStatement + | ImportDeclaration + | ExportDeclaration + | ExportAssignment; + + function isPreservedDeclarationStatement(node: Node): node is ProcessedDeclarationStatement { + switch (node.kind) { + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.ModuleDeclaration: + case SyntaxKind.ImportEqualsDeclaration: + case SyntaxKind.InterfaceDeclaration: + case SyntaxKind.ClassDeclaration: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.EnumDeclaration: + case SyntaxKind.VariableStatement: + case SyntaxKind.ImportDeclaration: + case SyntaxKind.ExportDeclaration: + case SyntaxKind.ExportAssignment: + return true; + } + return false; + } + + type ProcessedComponent = + | ConstructSignatureDeclaration + | ConstructorDeclaration + | MethodDeclaration + | GetAccessorDeclaration + | SetAccessorDeclaration + | PropertyDeclaration + | PropertySignature + | MethodSignature + | CallSignatureDeclaration + | IndexSignatureDeclaration + | VariableDeclaration + | TypeParameterDeclaration + | ExpressionWithTypeArguments + | TypeReferenceNode + | ConditionalTypeNode + | FunctionTypeNode + | ConstructorTypeNode; + + function isProcessedComponent(node: Node): node is ProcessedComponent { + switch (node.kind) { + case SyntaxKind.ConstructSignature: + case SyntaxKind.Constructor: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.PropertySignature: + case SyntaxKind.MethodSignature: + case SyntaxKind.CallSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.VariableDeclaration: + case SyntaxKind.TypeParameter: + case SyntaxKind.ExpressionWithTypeArguments: + case SyntaxKind.TypeReference: + case SyntaxKind.ConditionalType: + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + return true; + } + return false; + } +} \ No newline at end of file diff --git a/src/compiler/transformers/declarations/diagnostics.ts b/src/compiler/transformers/declarations/diagnostics.ts new file mode 100644 index 0000000000000..e81539ca92da0 --- /dev/null +++ b/src/compiler/transformers/declarations/diagnostics.ts @@ -0,0 +1,469 @@ +/* @internal */ +namespace ts { + export type GetSymbolAccessibilityDiagnostic = (symbolAccessibilityResult: SymbolAccessibilityResult) => (SymbolAccessibilityDiagnostic | undefined); + + export interface SymbolAccessibilityDiagnostic { + errorNode: Node; + diagnosticMessage: DiagnosticMessage; + typeName?: DeclarationName | QualifiedName; + } + + export type DeclarationDiagnosticProducing = + | VariableDeclaration + | PropertyDeclaration + | PropertySignature + | BindingElement + | SetAccessorDeclaration + | GetAccessorDeclaration + | ConstructSignatureDeclaration + | CallSignatureDeclaration + | MethodDeclaration + | MethodSignature + | FunctionDeclaration + | ParameterDeclaration + | TypeParameterDeclaration + | ExpressionWithTypeArguments + | ImportEqualsDeclaration + | TypeAliasDeclaration + | ConstructorDeclaration + | IndexSignatureDeclaration; + + export function canProduceDiagnostics(node: Node): node is DeclarationDiagnosticProducing { + return isVariableDeclaration(node) || + isPropertyDeclaration(node) || + isPropertySignature(node) || + isBindingElement(node) || + isSetAccessor(node) || + isGetAccessor(node) || + isConstructSignatureDeclaration(node) || + isCallSignatureDeclaration(node) || + isMethodDeclaration(node) || + isMethodSignature(node) || + isFunctionDeclaration(node) || + isParameter(node) || + isTypeParameterDeclaration(node) || + isExpressionWithTypeArguments(node) || + isImportEqualsDeclaration(node) || + isTypeAliasDeclaration(node) || + isConstructorDeclaration(node) || + isIndexSignatureDeclaration(node); + } + + export function createGetSymbolAccessibilityDiagnosticForNodeName(node: DeclarationDiagnosticProducing) { + if (isSetAccessor(node) || isGetAccessor(node)) { + return getAccessorNameVisibilityError; + } + else if (isMethodSignature(node) || isMethodDeclaration(node)) { + return getMethodNameVisibilityError; + } + else { + return createGetSymbolAccessibilityDiagnosticForNode(node); + } + function getAccessorNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult) { + const diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage, + errorNode: node, + typeName: (node as NamedDeclaration).name + } : undefined; + } + + function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { + if (hasModifier(node, ModifierFlags.Static)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === SyntaxKind.ClassDeclaration) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + + function getMethodNameVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage, + errorNode: node, + typeName: (node as NamedDeclaration).name + } : undefined; + } + + function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { + if (hasModifier(node, ModifierFlags.Static)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === SyntaxKind.ClassDeclaration) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + + export function createGetSymbolAccessibilityDiagnosticForNode(node: DeclarationDiagnosticProducing) { + if (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isBindingElement(node) || isConstructorDeclaration(node)) { + return getVariableDeclarationTypeVisibilityError; + } + else if (isSetAccessor(node) || isGetAccessor(node)) { + return getAccessorDeclarationTypeVisibilityError; + } + else if (isConstructSignatureDeclaration(node) || isCallSignatureDeclaration(node) || isMethodDeclaration(node) || isMethodSignature(node) || isFunctionDeclaration(node) || isIndexSignatureDeclaration(node)) { + return getReturnTypeVisibilityError; + } + else if (isParameter(node)) { + if (isParameterPropertyDeclaration(node) && hasModifier(node.parent, ModifierFlags.Private)) { + return getVariableDeclarationTypeVisibilityError; + } + return getParameterDeclarationTypeVisibilityError; + } + else if (isTypeParameterDeclaration(node)) { + return getTypeParameterConstraintVisibilityError; + } + else if (isExpressionWithTypeArguments(node)) { + return getHeritageClauseVisibilityError; + } + else if (isImportEqualsDeclaration(node)) { + return getImportEntityNameVisibilityError; + } + else if (isTypeAliasDeclaration(node)) { + return getTypeAliasDeclarationVisibilityError; + } + else { + Debug.assertNever(node, `Attempted to set a declaration diagnostic context for unhandled node kind: ${(ts as any).SyntaxKind[(node as any).kind]}`); + } + + function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult) { + if (node.kind === SyntaxKind.VariableDeclaration || node.kind === SyntaxKind.BindingElement) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Exported_variable_0_has_or_is_using_private_name_1; + } + // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit + // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all. + else if (node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature || + (node.kind === SyntaxKind.Parameter && hasModifier(node.parent, ModifierFlags.Private))) { + // TODO(jfreeman): Deal with computed properties in error reporting. + if (hasModifier(node, ModifierFlags.Static)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.Parameter) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1; + } + } + } + + function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage, + errorNode: node, + typeName: (node as NamedDeclaration).name + } : undefined; + } + + function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + let diagnosticMessage: DiagnosticMessage; + if (node.kind === SyntaxKind.SetAccessor) { + // Getters can infer the return type from the returned expression, but setters cannot, so the + // "_from_external_module_1_but_cannot_be_named" case cannot occur. + if (hasModifier(node, ModifierFlags.Static)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + else { + if (hasModifier(node, ModifierFlags.Static)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1; + } + } + return { + diagnosticMessage, + errorNode: (node as NamedDeclaration).name, + typeName: (node as NamedDeclaration).name + }; + } + + function getReturnTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + let diagnosticMessage: DiagnosticMessage; + switch (node.kind) { + case SyntaxKind.ConstructSignature: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + + case SyntaxKind.CallSignature: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + + case SyntaxKind.IndexSignature: + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0; + break; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + if (hasModifier(node, ModifierFlags.Static)) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0; + } + else if (node.parent.kind === SyntaxKind.ClassDeclaration) { + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 : + Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0; + } + else { + // Interfaces cannot have return types that cannot be named + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 : + Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0; + } + break; + + case SyntaxKind.FunctionDeclaration: + diagnosticMessage = symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named : + Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 : + Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0; + break; + + default: + Debug.fail("This is unknown kind for signature: " + node.kind); + } + + return { + diagnosticMessage, + errorNode: (node as NamedDeclaration).name || node + }; + } + + function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult: SymbolAccessibilityResult): SymbolAccessibilityDiagnostic { + const diagnosticMessage: DiagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult); + return diagnosticMessage !== undefined ? { + diagnosticMessage, + errorNode: node, + typeName: (node as NamedDeclaration).name + } : undefined; + } + + function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult: SymbolAccessibilityResult): DiagnosticMessage { + switch (node.parent.kind) { + case SyntaxKind.Constructor: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1; + + case SyntaxKind.ConstructSignature: + case SyntaxKind.ConstructorType: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + + case SyntaxKind.CallSignature: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + + case SyntaxKind.IndexSignature: + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + if (hasModifier(node.parent, ModifierFlags.Static)) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + // Interfaces cannot have parameter types that cannot be named + return symbolAccessibilityResult.errorModuleName ? + Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.FunctionType: + return symbolAccessibilityResult.errorModuleName ? + symbolAccessibilityResult.accessibility === SymbolAccessibility.CannotBeNamed ? + Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named : + Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 : + Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1; + + default: + Debug.fail(`Unknown parent for parameter: ${(ts as any).SyntaxKind[node.parent.kind]}`); + } + } + + function getTypeParameterConstraintVisibilityError(): SymbolAccessibilityDiagnostic { + // Type parameter constraints are named by user so we should always be able to name it + let diagnosticMessage: DiagnosticMessage; + switch (node.parent.kind) { + case SyntaxKind.ClassDeclaration: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1; + break; + + case SyntaxKind.InterfaceDeclaration: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1; + break; + + case SyntaxKind.ConstructSignature: + diagnosticMessage = Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + + case SyntaxKind.CallSignature: + diagnosticMessage = Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1; + break; + + case SyntaxKind.MethodDeclaration: + case SyntaxKind.MethodSignature: + if (hasModifier(node.parent, ModifierFlags.Static)) { + diagnosticMessage = Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1; + } + else if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { + diagnosticMessage = Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1; + } + else { + diagnosticMessage = Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1; + } + break; + + case SyntaxKind.FunctionDeclaration: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1; + break; + + case SyntaxKind.TypeAliasDeclaration: + diagnosticMessage = Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1; + break; + + default: + Debug.fail("This is unknown parent for type parameter: " + node.parent.kind); + } + + return { + diagnosticMessage, + errorNode: node, + typeName: (node as NamedDeclaration).name + }; + } + + function getHeritageClauseVisibilityError(): SymbolAccessibilityDiagnostic { + let diagnosticMessage: DiagnosticMessage; + // Heritage clause is written by user so it can always be named + if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) { + // Class or Interface implemented/extended is inaccessible + diagnosticMessage = (node as ExpressionWithTypeArguments).parent.token === SyntaxKind.ImplementsKeyword ? + Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 : + Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1; + } + else { + // interface is inaccessible + diagnosticMessage = Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1; + } + + return { + diagnosticMessage, + errorNode: node, + typeName: getNameOfDeclaration((node as ExpressionWithTypeArguments).parent.parent) + }; + } + + function getImportEntityNameVisibilityError(): SymbolAccessibilityDiagnostic { + return { + diagnosticMessage: Diagnostics.Import_declaration_0_is_using_private_name_1, + errorNode: node, + typeName: (node as NamedDeclaration).name + }; + } + + function getTypeAliasDeclarationVisibilityError(): SymbolAccessibilityDiagnostic { + return { + diagnosticMessage: Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1, + errorNode: (node as TypeAliasDeclaration).type, + typeName: (node as TypeAliasDeclaration).name + }; + } + } +} \ No newline at end of file diff --git a/src/compiler/transformers/es2017.ts b/src/compiler/transformers/es2017.ts index 0c6b25cf0b524..bee99cdf53366 100644 --- a/src/compiler/transformers/es2017.ts +++ b/src/compiler/transformers/es2017.ts @@ -669,8 +669,7 @@ namespace ts { name: "typescript:async-super", scoped: true, text: ` - const _super = name => super[name]; - ` + const _super = name => super[name];` }; export const advancedAsyncSuperHelper: EmitHelper = { @@ -680,7 +679,6 @@ namespace ts { const _super = (function (geti, seti) { const cache = Object.create(null); return name => cache[name] || (cache[name] = { get value() { return geti(name); }, set value(v) { seti(name, v); } }); - })(name => super[name], (name, value) => super[name] = value); - ` + })(name => super[name], (name, value) => super[name] = value);` }; } diff --git a/src/compiler/transformers/esnext.ts b/src/compiler/transformers/esnext.ts index 2b887c9e93b37..b9a73ea97c0ad 100644 --- a/src/compiler/transformers/esnext.ts +++ b/src/compiler/transformers/esnext.ts @@ -887,8 +887,7 @@ namespace ts { name: "typescript:await", scoped: false, text: ` - var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } - ` + var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }` }; function createAwaitHelper(context: TransformationContext, expression: Expression) { @@ -910,8 +909,7 @@ namespace ts { function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - ` + };` }; function createAsyncGeneratorHelper(context: TransformationContext, generatorFunc: FunctionExpression) { @@ -940,8 +938,7 @@ namespace ts { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { if (o[n]) i[n] = function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; }; } - }; - ` + };` }; function createAsyncDelegatorHelper(context: TransformationContext, expression: Expression, location?: TextRange) { @@ -965,8 +962,7 @@ namespace ts { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator]; return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator](); - }; - ` + };` }; function createAsyncValuesHelper(context: TransformationContext, expression: Expression, location?: TextRange) { diff --git a/src/compiler/transformers/module/module.ts b/src/compiler/transformers/module/module.ts index a4f4cb869dc05..45d13357123c7 100644 --- a/src/compiler/transformers/module/module.ts +++ b/src/compiler/transformers/module/module.ts @@ -1698,8 +1698,7 @@ namespace ts { text: ` function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; - } - ` + }` }; function createExportStarHelper(context: TransformationContext, module: Expression) { diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index 92d9f099441f8..58626f2cdc19e 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -31,10 +31,11 @@ "transformers/module/module.ts", "transformers/module/system.ts", "transformers/module/es2015.ts", + "transformers/declarations/diagnostics.ts", + "transformers/declarations.ts", "transformer.ts", "comments.ts", "sourcemap.ts", - "declarationEmitter.ts", "emitter.ts", "watchUtilities.ts", "program.ts", diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 2e7005d912e13..72eb95a23aea9 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -536,6 +536,7 @@ namespace ts { TypeScriptModifier = Ambient | Public | Private | Protected | Readonly | Abstract | Const, ExportDefault = Export | Default, + All = Export | Ambient | Public | Private | Protected | Static | Readonly | Abstract | Async | Default | Const } export const enum JsxFlags { @@ -697,6 +698,7 @@ namespace ts { Loop = 2, // Automatically generated identifier with a preference for '_i'. Unique = 3, // Unique name based on the 'text' property. Node = 4, // Unique name based on the node in the 'original' property. + OptimisticUnique = 5, // Unique name based on the 'text' property, first instance won't use '_#' if there's no conflict KindMask = 7, // Mask to extract the kind of identifier from its flags. // Flags @@ -971,9 +973,9 @@ namespace ts { export type FunctionLikeDeclaration = | FunctionDeclaration | MethodDeclaration - | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration + | ConstructorDeclaration | FunctionExpression | ArrowFunction; /** @deprecated Use SignatureDeclaration */ @@ -2581,6 +2583,8 @@ namespace ts { export interface Bundle extends Node { kind: SyntaxKind.Bundle; sourceFiles: ReadonlyArray; + /* @internal */ syntheticFileReferences?: ReadonlyArray; + /* @internal */ syntheticTypeReferences?: ReadonlyArray; } export interface JsonSourceFile extends SourceFile { @@ -3200,15 +3204,16 @@ namespace ts { isReferencedAliasDeclaration(node: Node, checkChildren?: boolean): boolean; isTopLevelValueImportEqualsWithEntityName(node: ImportEqualsDeclaration): boolean; getNodeCheckFlags(node: Node): NodeCheckFlags; - isDeclarationVisible(node: Declaration): boolean; + isDeclarationVisible(node: Declaration | AnyImportSyntax): boolean; isLateBound(node: Declaration): node is LateBoundDeclaration; collectLinkedAliases(node: Identifier): Node[]; - isImplementationOfOverload(node: FunctionLikeDeclaration): boolean | undefined; + isImplementationOfOverload(node: FunctionLike): boolean | undefined; isRequiredInitializedParameter(node: ParameterDeclaration): boolean; isOptionalUninitializedParameterProperty(node: ParameterDeclaration): boolean; - writeTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: EmitTextWriter): void; - writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: EmitTextWriter): void; - writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: EmitTextWriter): void; + createTypeOfDeclaration(declaration: AccessorDeclaration | VariableLikeDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker, addUndefined?: boolean): TypeNode; + createReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode; + createTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: NodeBuilderFlags, tracker: SymbolTracker): TypeNode; + createLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): Expression; isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; // Returns the constant value this property access resolves to, or 'undefined' for a non-constant @@ -3222,7 +3227,6 @@ namespace ts { getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[]; getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[]; isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean; - writeLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, writer: EmitTextWriter): void; getJsxFactoryEntity(location?: Node): EntityName; } @@ -4862,6 +4866,8 @@ namespace ts { * before returning the `NodeTransformer` callback. */ onEmitNode: (hint: EmitHint, node: Node, emitCallback: (hint: EmitHint, node: Node) => void) => void; + + /* @internal */ addDiagnostic(diag: Diagnostic): void; } export interface TransformationResult { @@ -5005,6 +5011,7 @@ namespace ts { /*@internal*/ sourceMap?: boolean; /*@internal*/ inlineSourceMap?: boolean; /*@internal*/ extendedDiagnostics?: boolean; + /*@internal*/ onlyPrintJsDocStyle?: boolean; } /* @internal */ @@ -5119,10 +5126,10 @@ namespace ts { // Precomputed Formats Modifiers = SingleLine | SpaceBetweenSiblings | NoInterveningComments, HeritageClauses = SingleLine | SpaceBetweenSiblings, - SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings | Indented, - MultiLineTypeLiteralMembers = MultiLine | Indented, + SingleLineTypeLiteralMembers = SingleLine | SpaceBetweenBraces | SpaceBetweenSiblings, + MultiLineTypeLiteralMembers = MultiLine | Indented | OptionalIfEmpty, - TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine | Indented, + TupleTypeElements = CommaDelimited | SpaceBetweenSiblings | SingleLine, UnionTypeConstituents = BarDelimited | SpaceBetweenSiblings | SingleLine, IntersectionTypeConstituents = AmpersandDelimited | SpaceBetweenSiblings | SingleLine, ObjectBindingPatternElements = SingleLine | AllowTrailingComma | SpaceBetweenBraces | CommaDelimited | SpaceBetweenSiblings | NoSpaceIfEmpty, @@ -5143,7 +5150,7 @@ namespace ts { InterfaceMembers = Indented | MultiLine, EnumMembers = CommaDelimited | Indented | MultiLine, CaseBlockClauses = Indented | MultiLine, - NamedImportsOrExportsElements = CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | SingleLine | SpaceBetweenBraces, + NamedImportsOrExportsElements = CommaDelimited | SpaceBetweenSiblings | AllowTrailingComma | SingleLine | SpaceBetweenBraces | NoSpaceIfEmpty, JsxElementOrFragmentChildren = SingleLine | NoInterveningComments, JsxElementAttributes = SingleLine | SpaceBetweenSiblings | NoInterveningComments, CaseOrDefaultClauseStatements = Indented | MultiLine | NoTrailingNewLine | OptionalIfEmpty, diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 631e95fbde406..4077d33933e11 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -274,9 +274,9 @@ namespace ts { return false; } - export function isPinnedComment(text: string, comment: CommentRange) { - return text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk && - text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation; + export function isPinnedComment(text: string, start: number) { + return text.charCodeAt(start + 1) === CharacterCodes.asterisk && + text.charCodeAt(start + 2) === CharacterCodes.exclamation; } export function getTokenPosOfNode(node: Node, sourceFile?: SourceFileLike, includeJsDoc?: boolean): number { @@ -967,6 +967,10 @@ namespace ts { return false; } + export function isVariableLikeOrAccessor(node: Node): node is AccessorDeclaration | VariableLikeDeclaration { + return isVariableLike(node) || isAccessor(node); + } + export function isVariableDeclarationInVariableStatement(node: VariableDeclaration) { return node.parent.kind === SyntaxKind.VariableDeclarationList && node.parent.parent.kind === SyntaxKind.VariableStatement; @@ -1423,6 +1427,10 @@ namespace ts { return isInJavaScriptFile(file); } + export function isSourceFileNotJavaScript(file: SourceFile): boolean { + return !isInJavaScriptFile(file); + } + export function isInJavaScriptFile(node: Node | undefined): boolean { return node && !!(node.flags & NodeFlags.JavaScriptFile); } @@ -3110,7 +3118,7 @@ namespace ts { return currentDetachedCommentInfo; function isPinnedCommentLocal(comment: CommentRange) { - return isPinnedComment(text, comment); + return isPinnedComment(text, comment.pos); } } @@ -5983,6 +5991,45 @@ namespace ts { return !!(node as HasType).type; } + /* True if the node could have a type node a `.type` */ + /* @internal */ + export function couldHaveType(node: Node): node is HasType { + switch (node.kind) { + case SyntaxKind.Parameter: + case SyntaxKind.PropertySignature: + case SyntaxKind.PropertyDeclaration: + case SyntaxKind.MethodSignature: + case SyntaxKind.MethodDeclaration: + case SyntaxKind.Constructor: + case SyntaxKind.GetAccessor: + case SyntaxKind.SetAccessor: + case SyntaxKind.CallSignature: + case SyntaxKind.ConstructSignature: + case SyntaxKind.IndexSignature: + case SyntaxKind.TypePredicate: + case SyntaxKind.FunctionType: + case SyntaxKind.ConstructorType: + case SyntaxKind.ParenthesizedType: + case SyntaxKind.TypeOperator: + case SyntaxKind.MappedType: + case SyntaxKind.TypeAssertionExpression: + case SyntaxKind.FunctionExpression: + case SyntaxKind.ArrowFunction: + case SyntaxKind.AsExpression: + case SyntaxKind.VariableDeclaration: + case SyntaxKind.FunctionDeclaration: + case SyntaxKind.TypeAliasDeclaration: + case SyntaxKind.JSDocTypeExpression: + case SyntaxKind.JSDocNullableType: + case SyntaxKind.JSDocNonNullableType: + case SyntaxKind.JSDocOptionalType: + case SyntaxKind.JSDocFunctionType: + case SyntaxKind.JSDocVariadicType: + return true; + } + return false; + } + /** True if has initializer node attached to it. */ /* @internal */ export function hasInitializer(node: Node): node is HasInitializer { @@ -6015,6 +6062,30 @@ namespace ts { return node.kind === SyntaxKind.TypeReference || node.kind === SyntaxKind.ExpressionWithTypeArguments; } + const MAX_SMI_X86 = 0x3fff_ffff; + /* @internal */ + export function guessIndentation(lines: string[]) { + let indentation = MAX_SMI_X86; + for (const line of lines) { + if (!line.length) { + continue; + } + let i = 0; + for (; i < line.length && i < indentation; i++) { + if (!isWhiteSpaceLike(line.charCodeAt(i))) { + break; + } + } + if (i < indentation) { + indentation = i; + } + if (indentation === 0) { + return 0; + } + } + return indentation === MAX_SMI_X86 ? undefined : indentation; + } + export function isStringLiteralLike(node: Node): node is StringLiteralLike { return node.kind === SyntaxKind.StringLiteral || node.kind === SyntaxKind.NoSubstitutionTemplateLiteral; } diff --git a/src/harness/tsconfig.json b/src/harness/tsconfig.json index cd6dbc5e0bb85..6b5a42c2d98e0 100644 --- a/src/harness/tsconfig.json +++ b/src/harness/tsconfig.json @@ -39,10 +39,11 @@ "../compiler/transformers/module/module.ts", "../compiler/transformers/module/system.ts", "../compiler/transformers/module/es2015.ts", + "../compiler/transformers/declarations/diagnostics.ts", + "../compiler/transformers/declarations.ts", "../compiler/transformer.ts", "../compiler/comments.ts", "../compiler/sourcemap.ts", - "../compiler/declarationEmitter.ts", "../compiler/emitter.ts", "../compiler/program.ts", "../compiler/builder.ts", diff --git a/src/harness/unittests/jsDocParsing.ts b/src/harness/unittests/jsDocParsing.ts index 2d670a2b64791..39416dc5776f8 100644 --- a/src/harness/unittests/jsDocParsing.ts +++ b/src/harness/unittests/jsDocParsing.ts @@ -111,8 +111,6 @@ namespace ts { } describe("parsesIncorrectly", () => { - parsesIncorrectly("emptyComment", "/***/"); - parsesIncorrectly("threeAsterisks", "/*** */"); parsesIncorrectly("multipleTypes", `/** * @type {number} @@ -152,6 +150,8 @@ namespace ts { }); describe("parsesCorrectly", () => { + parsesCorrectly("threeAsterisks", "/*** */"); + parsesCorrectly("emptyComment", "/***/"); parsesCorrectly("noLeadingAsterisk", `/** @type {number} diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index 850c26efd0729..c3ab35c923b1c 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -874,7 +874,7 @@ namespace ts.textChanges { let ranges = getLeadingCommentRanges(text, position); if (!ranges) return position; // However we should still skip a pinned comment at the top - if (ranges.length && ranges[0].kind === SyntaxKind.MultiLineCommentTrivia && isPinnedComment(text, ranges[0])) { + if (ranges.length && ranges[0].kind === SyntaxKind.MultiLineCommentTrivia && isPinnedComment(text, ranges[0].pos)) { position = ranges[0].end; advancePastLineBreak(); ranges = ranges.slice(1); diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 686c3357bc3b9..7ea6c1fa976f1 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -31,10 +31,11 @@ "../compiler/transformers/module/module.ts", "../compiler/transformers/module/system.ts", "../compiler/transformers/module/es2015.ts", + "../compiler/transformers/declarations/diagnostics.ts", + "../compiler/transformers/declarations.ts", "../compiler/transformer.ts", "../compiler/comments.ts", "../compiler/sourcemap.ts", - "../compiler/declarationEmitter.ts", "../compiler/emitter.ts", "../compiler/program.ts", "../compiler/builderState.ts", diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.emptyComment.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.emptyComment.json new file mode 100644 index 0000000000000..bcdae97c94078 --- /dev/null +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.emptyComment.json @@ -0,0 +1,5 @@ +{ + "kind": "JSDocComment", + "pos": 0, + "end": 5 +} \ No newline at end of file diff --git a/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.threeAsterisks.json b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.threeAsterisks.json new file mode 100644 index 0000000000000..a89a36050aa3d --- /dev/null +++ b/tests/baselines/reference/JSDocParsing/DocComments.parsesCorrectly.threeAsterisks.json @@ -0,0 +1,6 @@ +{ + "kind": "JSDocComment", + "pos": 0, + "end": 7, + "comment": "* " +} \ No newline at end of file diff --git a/tests/baselines/reference/ambientConstLiterals.js b/tests/baselines/reference/ambientConstLiterals.js index ca5a5d28699a1..7c7da7321c312 100644 --- a/tests/baselines/reference/ambientConstLiterals.js +++ b/tests/baselines/reference/ambientConstLiterals.js @@ -51,7 +51,7 @@ declare function f(x: T): T; declare enum E { A = 0, B = 1, - C = 2, + C = 2 } declare const c1 = "abc"; declare const c2 = 123; diff --git a/tests/baselines/reference/ambientShorthand_declarationEmit.js b/tests/baselines/reference/ambientShorthand_declarationEmit.js index d758b57efd26d..7220dd2b0a4cf 100644 --- a/tests/baselines/reference/ambientShorthand_declarationEmit.js +++ b/tests/baselines/reference/ambientShorthand_declarationEmit.js @@ -6,4 +6,4 @@ declare module "foo"; //// [ambientShorthand_declarationEmit.d.ts] -declare module "foo"; \ No newline at end of file +declare module "foo"; diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 8b9e078716c8d..3b4767a8a5db8 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -390,7 +390,7 @@ declare namespace ts { FirstJSDocNode = 274, LastJSDocNode = 292, FirstJSDocTagNode = 284, - LastJSDocTagNode = 292, + LastJSDocTagNode = 292 } enum NodeFlags { None = 0, @@ -418,7 +418,7 @@ declare namespace ts { ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 6387712, - TypeExcludesFlags = 20480, + TypeExcludesFlags = 20480 } enum ModifierFlags { None = 0, @@ -439,6 +439,7 @@ declare namespace ts { NonPublicAccessibilityModifier = 24, TypeScriptModifier = 2270, ExportDefault = 513, + All = 3071 } enum JsxFlags { None = 0, @@ -446,7 +447,7 @@ declare namespace ts { IntrinsicNamedElement = 1, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - IntrinsicElement = 3, + IntrinsicElement = 3 } interface Node extends TextRange { kind: SyntaxKind; @@ -644,7 +645,7 @@ declare namespace ts { questionToken?: QuestionToken; body?: Block | Expression; } - type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; /** @deprecated Use SignatureDeclaration */ type FunctionLike = SignatureDeclaration; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { @@ -1555,7 +1556,7 @@ declare namespace ts { PreFinally = 2048, AfterFinally = 4096, Label = 12, - Condition = 96, + Condition = 96 } interface FlowLock { locked?: boolean; @@ -1727,7 +1728,7 @@ declare namespace ts { enum ExitStatus { Success = 0, DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, + DiagnosticsPresent_OutputsGenerated = 2 } interface EmitResult { emitSkipped: boolean; @@ -1752,9 +1753,9 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; - } | undefined; + }) | undefined; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -1849,7 +1850,7 @@ declare namespace ts { InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, - InReverseMappedType = 33554432, + InReverseMappedType = 33554432 } enum TypeFormatFlags { None = 0, @@ -1872,14 +1873,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469291, + NodeBuilderFlagsMask = 9469291 } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8, + UseAliasDefinedOutsideCurrentScope = 8 } /** * @deprecated @@ -1916,7 +1917,7 @@ declare namespace ts { } enum TypePredicateKind { This = 0, - Identifier = 1, + Identifier = 1 } interface TypePredicateBase { kind: TypePredicateKind; @@ -1991,7 +1992,7 @@ declare namespace ts { HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500, + ClassMember = 106500 } interface Symbol { flags: SymbolFlags; @@ -2018,7 +2019,7 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default", + Default = "default" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2093,7 +2094,7 @@ declare namespace ts { Instantiable = 7897088, StructuredOrInstantiable = 8355840, Narrowable = 142575359, - NotUnionOrUnit = 134283777, + NotUnionOrUnit = 134283777 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2134,7 +2135,7 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, - ClassOrInterface = 3, + ClassOrInterface = 3 } interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2220,7 +2221,7 @@ declare namespace ts { } enum SignatureKind { Call = 0, - Construct = 1, + Construct = 1 } interface Signature { declaration?: SignatureDeclaration; @@ -2229,7 +2230,7 @@ declare namespace ts { } enum IndexKind { String = 0, - Number = 1, + Number = 1 } interface IndexInfo { type: Type; @@ -2243,7 +2244,7 @@ declare namespace ts { ReturnType = 8, NoConstraints = 16, AlwaysStrict = 32, - PriorityImpliesUnion = 12, + PriorityImpliesUnion = 12 } interface JsFileExtensionInfo { extension: string; @@ -2281,11 +2282,11 @@ declare namespace ts { Warning = 0, Error = 1, Suggestion = 2, - Message = 3, + Message = 3 } enum ModuleResolutionKind { Classic = 1, - NodeJs = 2, + NodeJs = 2 } interface PluginImport { name: string; @@ -2379,17 +2380,17 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6, + ESNext = 6 } enum JsxEmit { None = 0, Preserve = 1, React = 2, - ReactNative = 3, + ReactNative = 3 } enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, + LineFeed = 1 } interface LineAndCharacter { /** 0-based. */ @@ -2403,7 +2404,7 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6, + JSON = 6 } enum ScriptTarget { ES3 = 0, @@ -2413,11 +2414,11 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, - Latest = 6, + Latest = 6 } enum LanguageVariant { Standard = 0, - JSX = 1, + JSX = 1 } /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { @@ -2431,7 +2432,7 @@ declare namespace ts { } enum WatchDirectoryFlags { None = 0, - Recursive = 1, + Recursive = 1 } interface ExpandResult { fileNames: string[]; @@ -2501,7 +2502,7 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", - Json = ".json", + Json = ".json" } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -2571,7 +2572,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216, + NoAsciiEscaping = 16777216 } interface EmitHelper { readonly name: string; @@ -2584,7 +2585,7 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4, + Unspecified = 4 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2802,9 +2803,9 @@ declare namespace ts { SingleElement = 524288, Modifiers = 131328, HeritageClauses = 256, - SingleLineTypeLiteralMembers = 448, - MultiLineTypeLiteralMembers = 65, - TupleTypeElements = 336, + SingleLineTypeLiteralMembers = 384, + MultiLineTypeLiteralMembers = 16449, + TupleTypeElements = 272, UnionTypeConstituents = 260, IntersectionTypeConstituents = 264, ObjectBindingPatternElements = 262576, @@ -2825,7 +2826,7 @@ declare namespace ts { InterfaceMembers = 65, EnumMembers = 81, CaseBlockClauses = 65, - NamedImportsOrExportsElements = 432, + NamedImportsOrExportsElements = 262576, JsxElementOrFragmentChildren = 131072, JsxElementAttributes = 131328, CaseOrDefaultClauseStatements = 81985, @@ -2835,7 +2836,7 @@ declare namespace ts { TypeArguments = 26896, TypeParameters = 26896, Parameters = 1296, - IndexSignatureParameters = 4432, + IndexSignatureParameters = 4432 } } declare namespace ts { @@ -2853,7 +2854,7 @@ declare namespace ts { enum FileWatcherEventKind { Created = 0, Changed = 1, - Deleted = 2, + Deleted = 2 } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; @@ -3438,6 +3439,8 @@ declare namespace ts { function createLoopVariable(): Identifier; /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; /** Create a unique name generated for a node. */ function getGeneratedNameForNode(node: Node): Identifier; function createToken(token: TKind): Token; @@ -3446,6 +3449,8 @@ declare namespace ts { function createNull(): NullLiteral & Token; function createTrue(): BooleanLiteral & Token; function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; @@ -3700,7 +3705,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -4305,7 +4310,7 @@ declare namespace ts { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference", + writtenReference = "writtenReference" } interface HighlightSpan { fileName?: string; @@ -4327,7 +4332,7 @@ declare namespace ts { enum IndentStyle { None = 0, Block = 1, - Smart = 2, + Smart = 2 } interface EditorOptions { BaseIndentSize?: number; @@ -4422,7 +4427,7 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21, + regularExpressionLiteral = 21 } interface SymbolDisplayPart { text: string; @@ -4533,7 +4538,7 @@ declare namespace ts { enum OutputFileType { JavaScript = 0, SourceMap = 1, - Declaration = 2, + Declaration = 2 } enum EndOfLineState { None = 0, @@ -4542,7 +4547,7 @@ declare namespace ts { InDoubleQuoteStringLiteral = 3, InTemplateHeadOrNoSubstitutionTemplate = 4, InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, + InTemplateSubstitutionPosition = 6 } enum TokenClass { Punctuation = 0, @@ -4553,7 +4558,7 @@ declare namespace ts { Identifier = 5, NumberLiteral = 6, StringLiteral = 7, - RegExpLiteral = 8, + RegExpLiteral = 8 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -4652,7 +4657,7 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute", + jsxAttribute = "JSX attribute" } enum ScriptElementKindModifier { none = "", @@ -4663,7 +4668,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional", + optionalModifier = "optional" } enum ClassificationTypeNames { comment = "comment", @@ -4688,7 +4693,7 @@ declare namespace ts { jsxSelfClosingTagName = "jsx self closing tag name", jsxAttribute = "jsx attribute", jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" } enum ClassificationType { comment = 1, @@ -4714,7 +4719,7 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24, + jsxAttributeStringLiteralValue = 24 } } declare namespace ts { @@ -4952,7 +4957,7 @@ declare namespace ts.server { terse = 0, normal = 1, requestTime = 2, - verbose = 3, + verbose = 3 } const emptyArray: SortedReadonlyArray; interface Logger { @@ -4969,7 +4974,7 @@ declare namespace ts.server { enum Msg { Err = "Err", Info = "Info", - Perf = "Perf", + Perf = "Perf" } namespace Msg { /** @deprecated Only here for backwards-compatibility. Prefer just `Msg`. */ @@ -5076,7 +5081,7 @@ declare namespace ts.server.protocol { GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", GetEditsForRefactor = "getEditsForRefactor", - OrganizeImports = "organizeImports", + OrganizeImports = "organizeImports" } /** * A TypeScript Server message @@ -7065,7 +7070,7 @@ declare namespace ts.server.protocol { enum IndentStyle { None = "None", Block = "Block", - Smart = "Smart", + Smart = "Smart" } interface EditorSettings { baseIndentSize?: number; @@ -7166,7 +7171,7 @@ declare namespace ts.server.protocol { None = "None", Preserve = "Preserve", ReactNative = "ReactNative", - React = "React", + React = "React" } enum ModuleKind { None = "None", @@ -7176,15 +7181,15 @@ declare namespace ts.server.protocol { System = "System", ES6 = "ES6", ES2015 = "ES2015", - ESNext = "ESNext", + ESNext = "ESNext" } enum ModuleResolutionKind { Classic = "Classic", - Node = "Node", + Node = "Node" } enum NewLineKind { Crlf = "Crlf", - Lf = "Lf", + Lf = "Lf" } enum ScriptTarget { ES3 = "ES3", @@ -7193,7 +7198,7 @@ declare namespace ts.server.protocol { ES2015 = "ES2015", ES2016 = "ES2016", ES2017 = "ES2017", - ESNext = "ESNext", + ESNext = "ESNext" } } declare namespace ts.server { @@ -7247,114 +7252,114 @@ declare namespace ts.server { protected canUseEvents: boolean; private eventHandler; constructor(opts: SessionOptions); - private sendRequestCompletedEvent(requestId); - private defaultEventHandler(event); - private projectsUpdatedInBackgroundEvent(openFiles); + private sendRequestCompletedEvent; + private defaultEventHandler; + private projectsUpdatedInBackgroundEvent; logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; event(body: T, eventName: string): void; /** @deprecated */ output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; - private doOutput(info, cmdName, reqSeq, success, message?); - private semanticCheck(file, project); - private syntacticCheck(file, project); - private infoCheck(file, project); - private sendDiagnosticsEvent(file, project, diagnostics, kind); - private updateErrorCheck(next, checkList, ms, requireOpen?); - private cleanProjects(caption, projects); - private cleanup(); - private getEncodedSemanticClassifications(args); - private getProject(projectFileName); - private getConfigFileAndProject(args); - private getConfigFileDiagnostics(configFile, project, includeLinePosition); - private convertToDiagnosticsWithLinePositionFromDiagnosticFile(diagnostics); - private getCompilerOptionsDiagnostics(args); - private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo); - private getDiagnosticsWorker(args, isSemantic, selector, includeLinePosition); - private getDefinition(args, simplifiedResult); - private getDefinitionAndBoundSpan(args, simplifiedResult); - private mapDefinitionInfo(definitions, project); - private toFileSpan(fileName, textSpan, project); - private getTypeDefinition(args); - private getImplementation(args, simplifiedResult); - private getOccurrences(args); - private getSyntacticDiagnosticsSync(args); - private getSemanticDiagnosticsSync(args); - private getSuggestionDiagnosticsSync(args); - private getDocumentHighlights(args, simplifiedResult); - private setCompilerOptionsForInferredProjects(args); - private getProjectInfo(args); - private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList, excludeConfigFiles); - private getRenameInfo(args); - private getProjects(args); - private getDefaultProject(args); - private getRenameLocations(args, simplifiedResult); - private getReferences(args, simplifiedResult); + private doOutput; + private semanticCheck; + private syntacticCheck; + private infoCheck; + private sendDiagnosticsEvent; + private updateErrorCheck; + private cleanProjects; + private cleanup; + private getEncodedSemanticClassifications; + private getProject; + private getConfigFileAndProject; + private getConfigFileDiagnostics; + private convertToDiagnosticsWithLinePositionFromDiagnosticFile; + private getCompilerOptionsDiagnostics; + private convertToDiagnosticsWithLinePosition; + private getDiagnosticsWorker; + private getDefinition; + private getDefinitionAndBoundSpan; + private mapDefinitionInfo; + private toFileSpan; + private getTypeDefinition; + private getImplementation; + private getOccurrences; + private getSyntacticDiagnosticsSync; + private getSemanticDiagnosticsSync; + private getSuggestionDiagnosticsSync; + private getDocumentHighlights; + private setCompilerOptionsForInferredProjects; + private getProjectInfo; + private getProjectInfoWorker; + private getRenameInfo; + private getProjects; + private getDefaultProject; + private getRenameLocations; + private getReferences; /** * @param fileName is the name of the file to be opened * @param fileContent is a version of the file content that is known to be more up to date than the one on disk */ - private openClientFile(fileName, fileContent?, scriptKind?, projectRootPath?); - private getPosition(args, scriptInfo); - private getPositionInFile(args, file); - private getFileAndProject(args); - private getFileAndLanguageServiceForSyntacticOperation(args); - private getFileAndProjectWorker(uncheckedFileName, projectFileName); - private getOutliningSpans(args, simplifiedResult); - private getTodoComments(args); - private getDocCommentTemplate(args); - private getSpanOfEnclosingComment(args); - private getIndentation(args); - private getBreakpointStatement(args); - private getNameOrDottedNameSpan(args); - private isValidBraceCompletion(args); - private getQuickInfoWorker(args, simplifiedResult); - private getFormattingEditsForRange(args); - private getFormattingEditsForRangeFull(args); - private getFormattingEditsForDocumentFull(args); - private getFormattingEditsAfterKeystrokeFull(args); - private getFormattingEditsAfterKeystroke(args); - private getCompletions(args, simplifiedResult); - private getCompletionEntryDetails(args, simplifiedResult); - private getCompileOnSaveAffectedFileList(args); - private emitFile(args); - private getSignatureHelpItems(args, simplifiedResult); - private createCheckList(fileNames, defaultProject?); - private getDiagnostics(next, delay, fileNames); - private change(args); - private reload(args, reqSeq); - private saveToTmp(fileName, tempFileName); - private closeClientFile(fileName); - private mapLocationNavigationBarItems(items, scriptInfo); - private getNavigationBarItems(args, simplifiedResult); - private toLocationNavigationTree(tree, scriptInfo); - private toLocationTextSpan(span, scriptInfo); - private getNavigationTree(args, simplifiedResult); - private getNavigateToItems(args, simplifiedResult); - private getSupportedCodeFixes(); - private isLocation(locationOrSpan); - private extractPositionAndRange(args, scriptInfo); - private getApplicableRefactors(args); - private getEditsForRefactor(args, simplifiedResult); - private organizeImports({scope}, simplifiedResult); - private getCodeFixes(args, simplifiedResult); - private getCombinedCodeFix({scope, fixId}, simplifiedResult); - private applyCodeActionCommand(args); - private getStartAndEndPosition(args, scriptInfo); - private mapCodeAction(project, {description, changes: unmappedChanges, commands, fixId}); - private mapTextChangesToCodeEdits(project, textChanges); - private mapTextChangesToCodeEditsUsingScriptinfo(textChanges, scriptInfo); - private convertTextChangeToCodeEdit(change, scriptInfo); - private getBraceMatching(args, simplifiedResult); - private getDiagnosticsForProject(next, delay, fileName); + private openClientFile; + private getPosition; + private getPositionInFile; + private getFileAndProject; + private getFileAndLanguageServiceForSyntacticOperation; + private getFileAndProjectWorker; + private getOutliningSpans; + private getTodoComments; + private getDocCommentTemplate; + private getSpanOfEnclosingComment; + private getIndentation; + private getBreakpointStatement; + private getNameOrDottedNameSpan; + private isValidBraceCompletion; + private getQuickInfoWorker; + private getFormattingEditsForRange; + private getFormattingEditsForRangeFull; + private getFormattingEditsForDocumentFull; + private getFormattingEditsAfterKeystrokeFull; + private getFormattingEditsAfterKeystroke; + private getCompletions; + private getCompletionEntryDetails; + private getCompileOnSaveAffectedFileList; + private emitFile; + private getSignatureHelpItems; + private createCheckList; + private getDiagnostics; + private change; + private reload; + private saveToTmp; + private closeClientFile; + private mapLocationNavigationBarItems; + private getNavigationBarItems; + private toLocationNavigationTree; + private toLocationTextSpan; + private getNavigationTree; + private getNavigateToItems; + private getSupportedCodeFixes; + private isLocation; + private extractPositionAndRange; + private getApplicableRefactors; + private getEditsForRefactor; + private organizeImports; + private getCodeFixes; + private getCombinedCodeFix; + private applyCodeActionCommand; + private getStartAndEndPosition; + private mapCodeAction; + private mapTextChangesToCodeEdits; + private mapTextChangesToCodeEditsUsingScriptinfo; + private convertTextChangeToCodeEdit; + private getBraceMatching; + private getDiagnosticsForProject; getCanonicalFileName(fileName: string): string; exit(): void; - private notRequired(); - private requiredResponse(response); + private notRequired; + private requiredResponse; private handlers; addProtocolHandler(command: string, handler: (request: protocol.Request) => HandlerResponse): void; - private setCurrentRequest(requestId); - private resetCurrentRequest(requestId); + private setCurrentRequest; + private resetCurrentRequest; executeWithRequestId(requestId: number, f: () => T): T; executeCommand(request: protocol.Request): HandlerResponse; onMessage(message: string): void; @@ -7382,7 +7387,7 @@ declare namespace ts.server { open(newText: string): void; close(fileExists?: boolean): void; getSnapshot(): IScriptSnapshot; - private ensureRealPath(); + private ensureRealPath; getFormatCodeSettings(): FormatCodeSettings; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; @@ -7451,7 +7456,7 @@ declare namespace ts.server { enum ProjectKind { Inferred = 0, Configured = 1, - External = 2, + External = 2 } function allRootFilesAreJsOrDts(project: Project): boolean; function allFilesAreJsOrDts(project: Project): boolean; @@ -7542,7 +7547,7 @@ declare namespace ts.server { getNewLine(): string; getProjectVersion(): string; getScriptFileNames(): string[]; - private getOrCreateScriptInfoAndAttachToProject(fileName); + private getOrCreateScriptInfoAndAttachToProject; getScriptKind(fileName: string): ScriptKind; getScriptVersion(filename: string): string; getScriptSnapshot(filename: string): IScriptSnapshot; @@ -7559,14 +7564,14 @@ declare namespace ts.server { getDirectories(path: string): string[]; log(s: string): void; error(s: string): void; - private setInternalCompilerOptionsForEmittingJsFiles(); + private setInternalCompilerOptionsForEmittingJsFiles; /** * Get the errors that dont have any file name associated */ getGlobalProjectErrors(): ReadonlyArray; getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; - private shouldEmitFile(scriptInfo); + private shouldEmitFile; getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; /** * Returns true if emit was conducted @@ -7580,7 +7585,7 @@ declare namespace ts.server { getExternalFiles(): SortedReadonlyArray; getSourceFile(path: Path): SourceFile; close(): void; - private detachScriptInfoIfNotRoot(uncheckedFilename); + private detachScriptInfoIfNotRoot; isClosed(): boolean; hasRoots(): boolean; getRootFiles(): NormalizedPath[]; @@ -7603,10 +7608,10 @@ declare namespace ts.server { */ updateGraph(): boolean; protected removeExistingTypings(include: string[]): string[]; - private updateGraphWorker(); - private detachScriptInfoFromProject(uncheckedFileName); - private addMissingFileWatcher(missingFilePath); - private isWatchedMissingFile(path); + private updateGraphWorker; + private detachScriptInfoFromProject; + private addMissingFileWatcher; + private isWatchedMissingFile; getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; getScriptInfo(uncheckedFileName: string): ScriptInfo; filesToString(writeProjectFileNames: boolean): string; @@ -7614,7 +7619,7 @@ declare namespace ts.server { protected removeRoot(info: ScriptInfo): void; protected enableGlobalPlugins(): void; protected enablePlugin(pluginConfigEntry: PluginImport, searchPaths: string[]): void; - private enableProxy(pluginModuleFactory, configEntry); + private enableProxy; } /** * If a file is opened and no tsconfig (or jsconfig) is found, @@ -7857,12 +7862,12 @@ declare namespace ts.server { private readonly seenProjects; constructor(opts: ProjectServiceOptions); toPath(fileName: string): Path; - private loadTypesMap(); + private loadTypesMap; updateTypingsForProject(response: SetTypings | InvalidateCachedTypings | PackageInstalledResponse): void; - private delayEnsureProjectForOpenFiles(); - private delayUpdateProjectGraph(project); - private sendProjectsUpdatedInBackgroundEvent(); - private delayUpdateProjectGraphs(projects); + private delayEnsureProjectForOpenFiles; + private delayUpdateProjectGraph; + private sendProjectsUpdatedInBackgroundEvent; + private delayUpdateProjectGraphs; setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions, projectRootPath?: string): void; findProject(projectName: string): Project | undefined; getDefaultProjectForFile(fileName: NormalizedPath, ensureProject: boolean): Project; @@ -7874,47 +7879,47 @@ declare namespace ts.server { * - if updates reflect some change in structure or there was pending request to ensure projects for open files * ensure that each open script info has project */ - private ensureProjectStructuresUptoDate(); - private updateProjectIfDirty(project); + private ensureProjectStructuresUptoDate; + private updateProjectIfDirty; getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; - private onSourceFileChanged(fileName, eventKind, path); - private handleDeletedFile(info); - private onConfigChangedForConfiguredProject(project, eventKind); + private onSourceFileChanged; + private handleDeletedFile; + private onConfigChangedForConfiguredProject; /** * This is the callback function for the config file add/remove/change at any location * that matters to open script info but doesnt have configured project open * for the config file */ - private onConfigFileChangeForOpenScriptInfo(configFileName, eventKind); - private removeProject(project); + private onConfigFileChangeForOpenScriptInfo; + private removeProject; /** * Remove this file from the set of open, non-configured files. * @param info The file that has been closed or newly configured */ - private closeOpenFile(info); - private deleteOrphanScriptInfoNotInAnyProject(); - private deleteScriptInfo(info); - private configFileExists(configFileName, canonicalConfigFilePath, info); - private setConfigFileExistenceByNewConfiguredProject(project); + private closeOpenFile; + private deleteOrphanScriptInfoNotInAnyProject; + private deleteScriptInfo; + private configFileExists; + private setConfigFileExistenceByNewConfiguredProject; /** * Returns true if the configFileExistenceInfo is needed/impacted by open files that are root of inferred project */ - private configFileExistenceImpactsRootOfInferredProject(configFileExistenceInfo); - private setConfigFileExistenceInfoByClosedConfiguredProject(closedProject); - private logConfigFileWatchUpdate(configFileName, canonicalConfigFilePath, configFileExistenceInfo, status); + private configFileExistenceImpactsRootOfInferredProject; + private setConfigFileExistenceInfoByClosedConfiguredProject; + private logConfigFileWatchUpdate; /** * Create the watcher for the configFileExistenceInfo */ - private createConfigFileWatcherOfConfigFileExistence(configFileName, canonicalConfigFilePath, configFileExistenceInfo); + private createConfigFileWatcherOfConfigFileExistence; /** * Close the config file watcher in the cached ConfigFileExistenceInfo * if there arent any open files that are root of inferred project */ - private closeConfigFileWatcherOfConfigFileExistenceInfo(configFileExistenceInfo); + private closeConfigFileWatcherOfConfigFileExistenceInfo; /** * This is called on file close, so that we stop watching the config file for this script info */ - private stopWatchingConfigFilesForClosedScriptInfo(info); + private stopWatchingConfigFilesForClosedScriptInfo; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -7923,7 +7928,7 @@ declare namespace ts.server { * The server must start searching from the directory containing * the newly opened file. */ - private forEachConfigFileLocation(info, action, projectRootPath?); + private forEachConfigFileLocation; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because @@ -7932,31 +7937,31 @@ declare namespace ts.server { * The server must start searching from the directory containing * the newly opened file. */ - private getConfigFileNameForFile(info, projectRootPath); - private printProjects(); - private findConfiguredProjectByProjectName(configFileName); - private getConfiguredProjectByCanonicalConfigFilePath(canonicalConfigFilePath); - private findExternalProjectByProjectName(projectFileName); - private convertConfigFileContentToProjectOptions(configFilename, cachedDirectoryStructureHost); + private getConfigFileNameForFile; + private printProjects; + private findConfiguredProjectByProjectName; + private getConfiguredProjectByCanonicalConfigFilePath; + private findExternalProjectByProjectName; + private convertConfigFileContentToProjectOptions; /** Get a filename if the language service exceeds the maximum allowed program size; otherwise returns undefined. */ - private getFilenameForExceededTotalSizeLimitForNonTsFiles(name, options, fileNames, propertyReader); - private createExternalProject(projectFileName, files, options, typeAcquisition, excludedFiles); - private sendProjectTelemetry(projectKey, project, projectOptions?); - private addFilesToNonInferredProjectAndUpdateGraph(project, files, propertyReader, typeAcquisition); - private createConfiguredProject(configFileName); - private updateNonInferredProjectFiles(project, files, propertyReader); - private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypeAcquisition, compileOnSave); - private sendConfigFileDiagEvent(project, triggerFile); - private getOrCreateInferredProjectForProjectRootPathIfEnabled(info, projectRootPath); - private getOrCreateSingleInferredProjectIfEnabled(); - private createInferredProject(currentDirectory, isSingleInferredProject?, projectRootPath?); + private getFilenameForExceededTotalSizeLimitForNonTsFiles; + private createExternalProject; + private sendProjectTelemetry; + private addFilesToNonInferredProjectAndUpdateGraph; + private createConfiguredProject; + private updateNonInferredProjectFiles; + private updateNonInferredProject; + private sendConfigFileDiagEvent; + private getOrCreateInferredProjectForProjectRootPathIfEnabled; + private getOrCreateSingleInferredProjectIfEnabled; + private createInferredProject; getScriptInfo(uncheckedFileName: string): ScriptInfo; - private watchClosedScriptInfo(info); - private stopWatchingScriptInfo(info); + private watchClosedScriptInfo; + private stopWatchingScriptInfo; getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { fileExists(path: string): boolean; }): ScriptInfo; - private getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent?, scriptKind?, hasMixedContent?, hostToQueryFileExistsOn?); + private getOrCreateScriptInfoWorker; /** * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred */ @@ -7969,7 +7974,7 @@ declare namespace ts.server { * This does not reload contents of open files from disk. But we could do that if needed */ reloadProjects(): void; - private delayReloadConfiguredProjectForFiles(configFileExistenceInfo, ignoreIfNotRootOfInferredProject); + private delayReloadConfiguredProjectForFiles; /** * This function goes through all the openFiles and tries to file the config file for them. * If the config file is found and it refers to existing project, it reloads it either immediately @@ -7977,11 +7982,11 @@ declare namespace ts.server { * If the there is no existing project it just opens the configured project for the config file * reloadForInfo provides a way to filter out files to reload configured project for */ - private reloadConfiguredProjectForFiles(openFiles, delayReload, shouldReloadProjectFor); + private reloadConfiguredProjectForFiles; /** * Remove the root of inferred project if script info is part of another project */ - private removeRootOfInferredProjectIfNowPartOfOtherProject(info); + private removeRootOfInferredProjectIfNowPartOfOtherProject; /** * This function is to update the project structure for every inferred project. * It is called on the premise that all the configured projects are @@ -7989,27 +7994,27 @@ declare namespace ts.server { * This will go through open files and assign them to inferred project if open file is not part of any other project * After that all the inferred project graphs are updated */ - private ensureProjectForOpenFiles(); + private ensureProjectForOpenFiles; /** * Open file whose contents is managed by the client * @param filename is absolute pathname * @param fileContent is a known version of the file content that is more up to date than the one on disk */ openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; - private findExternalProjetContainingOpenScriptInfo(info); + private findExternalProjetContainingOpenScriptInfo; openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; /** * Close file whose contents is managed by the client * @param filename is absolute pathname */ closeClientFile(uncheckedFileName: string): void; - private collectChanges(lastKnownProjectVersions, currentProjects, result); - private closeConfiguredProjectReferencedFromExternalProject(configFile); + private collectChanges; + private closeConfiguredProjectReferencedFromExternalProject; closeExternalProject(uncheckedFileName: string): void; openExternalProjects(projects: protocol.ExternalProject[]): void; /** Makes a filename safe to insert in a RegExp */ private static readonly filenameEscapeRegexp; - private static escapeFilenameForRegex(filename); + private static escapeFilenameForRegex; resetSafeList(): void; applySafeList(proj: protocol.ExternalProject): NormalizedPath[]; openExternalProject(proj: protocol.ExternalProject): void; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 87204f489d805..4d17de3ca426d 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -390,7 +390,7 @@ declare namespace ts { FirstJSDocNode = 274, LastJSDocNode = 292, FirstJSDocTagNode = 284, - LastJSDocTagNode = 292, + LastJSDocTagNode = 292 } enum NodeFlags { None = 0, @@ -418,7 +418,7 @@ declare namespace ts { ReachabilityCheckFlags = 384, ReachabilityAndEmitFlags = 1408, ContextFlags = 6387712, - TypeExcludesFlags = 20480, + TypeExcludesFlags = 20480 } enum ModifierFlags { None = 0, @@ -439,6 +439,7 @@ declare namespace ts { NonPublicAccessibilityModifier = 24, TypeScriptModifier = 2270, ExportDefault = 513, + All = 3071 } enum JsxFlags { None = 0, @@ -446,7 +447,7 @@ declare namespace ts { IntrinsicNamedElement = 1, /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */ IntrinsicIndexedElement = 2, - IntrinsicElement = 3, + IntrinsicElement = 3 } interface Node extends TextRange { kind: SyntaxKind; @@ -644,7 +645,7 @@ declare namespace ts { questionToken?: QuestionToken; body?: Block | Expression; } - type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; + type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | ConstructorDeclaration | FunctionExpression | ArrowFunction; /** @deprecated Use SignatureDeclaration */ type FunctionLike = SignatureDeclaration; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { @@ -1555,7 +1556,7 @@ declare namespace ts { PreFinally = 2048, AfterFinally = 4096, Label = 12, - Condition = 96, + Condition = 96 } interface FlowLock { locked?: boolean; @@ -1727,7 +1728,7 @@ declare namespace ts { enum ExitStatus { Success = 0, DiagnosticsPresent_OutputsSkipped = 1, - DiagnosticsPresent_OutputsGenerated = 2, + DiagnosticsPresent_OutputsGenerated = 2 } interface EmitResult { emitSkipped: boolean; @@ -1752,9 +1753,9 @@ declare namespace ts { /** Note that the resulting nodes cannot be checked. */ typeToTypeNode(type: Type, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeNode; /** Note that the resulting nodes cannot be checked. */ - signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration & { + signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): (SignatureDeclaration & { typeArguments?: NodeArray; - } | undefined; + }) | undefined; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration | undefined; /** Note that the resulting nodes cannot be checked. */ @@ -1849,7 +1850,7 @@ declare namespace ts { InObjectTypeLiteral = 4194304, InTypeAlias = 8388608, InInitialEntityName = 16777216, - InReverseMappedType = 33554432, + InReverseMappedType = 33554432 } enum TypeFormatFlags { None = 0, @@ -1872,14 +1873,14 @@ declare namespace ts { InFirstTypeArgument = 4194304, InTypeAlias = 8388608, /** @deprecated */ WriteOwnNameForAnyLike = 0, - NodeBuilderFlagsMask = 9469291, + NodeBuilderFlagsMask = 9469291 } enum SymbolFormatFlags { None = 0, WriteTypeParametersOrArguments = 1, UseOnlyExternalAliasing = 2, AllowAnyNodeKind = 4, - UseAliasDefinedOutsideCurrentScope = 8, + UseAliasDefinedOutsideCurrentScope = 8 } /** * @deprecated @@ -1916,7 +1917,7 @@ declare namespace ts { } enum TypePredicateKind { This = 0, - Identifier = 1, + Identifier = 1 } interface TypePredicateBase { kind: TypePredicateKind; @@ -1991,7 +1992,7 @@ declare namespace ts { HasMembers = 6240, BlockScoped = 418, PropertyOrAccessor = 98308, - ClassMember = 106500, + ClassMember = 106500 } interface Symbol { flags: SymbolFlags; @@ -2018,7 +2019,7 @@ declare namespace ts { Computed = "__computed", Resolving = "__resolving__", ExportEquals = "export=", - Default = "default", + Default = "default" } /** * This represents a string whose leading underscore have been escaped by adding extra leading underscores. @@ -2093,7 +2094,7 @@ declare namespace ts { Instantiable = 7897088, StructuredOrInstantiable = 8355840, Narrowable = 142575359, - NotUnionOrUnit = 134283777, + NotUnionOrUnit = 134283777 } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -2134,7 +2135,7 @@ declare namespace ts { ReverseMapped = 2048, JsxAttributes = 4096, MarkerType = 8192, - ClassOrInterface = 3, + ClassOrInterface = 3 } interface ObjectType extends Type { objectFlags: ObjectFlags; @@ -2220,7 +2221,7 @@ declare namespace ts { } enum SignatureKind { Call = 0, - Construct = 1, + Construct = 1 } interface Signature { declaration?: SignatureDeclaration; @@ -2229,7 +2230,7 @@ declare namespace ts { } enum IndexKind { String = 0, - Number = 1, + Number = 1 } interface IndexInfo { type: Type; @@ -2243,7 +2244,7 @@ declare namespace ts { ReturnType = 8, NoConstraints = 16, AlwaysStrict = 32, - PriorityImpliesUnion = 12, + PriorityImpliesUnion = 12 } interface JsFileExtensionInfo { extension: string; @@ -2281,11 +2282,11 @@ declare namespace ts { Warning = 0, Error = 1, Suggestion = 2, - Message = 3, + Message = 3 } enum ModuleResolutionKind { Classic = 1, - NodeJs = 2, + NodeJs = 2 } interface PluginImport { name: string; @@ -2379,17 +2380,17 @@ declare namespace ts { UMD = 3, System = 4, ES2015 = 5, - ESNext = 6, + ESNext = 6 } enum JsxEmit { None = 0, Preserve = 1, React = 2, - ReactNative = 3, + ReactNative = 3 } enum NewLineKind { CarriageReturnLineFeed = 0, - LineFeed = 1, + LineFeed = 1 } interface LineAndCharacter { /** 0-based. */ @@ -2403,7 +2404,7 @@ declare namespace ts { TS = 3, TSX = 4, External = 5, - JSON = 6, + JSON = 6 } enum ScriptTarget { ES3 = 0, @@ -2413,11 +2414,11 @@ declare namespace ts { ES2017 = 4, ES2018 = 5, ESNext = 6, - Latest = 6, + Latest = 6 } enum LanguageVariant { Standard = 0, - JSX = 1, + JSX = 1 } /** Either a parsed command line or a parsed tsconfig.json */ interface ParsedCommandLine { @@ -2431,7 +2432,7 @@ declare namespace ts { } enum WatchDirectoryFlags { None = 0, - Recursive = 1, + Recursive = 1 } interface ExpandResult { fileNames: string[]; @@ -2501,7 +2502,7 @@ declare namespace ts { Dts = ".d.ts", Js = ".js", Jsx = ".jsx", - Json = ".json", + Json = ".json" } interface ResolvedModuleWithFailedLookupLocations { readonly resolvedModule: ResolvedModuleFull | undefined; @@ -2571,7 +2572,7 @@ declare namespace ts { NoHoisting = 2097152, HasEndOfDeclarationMarker = 4194304, Iterator = 8388608, - NoAsciiEscaping = 16777216, + NoAsciiEscaping = 16777216 } interface EmitHelper { readonly name: string; @@ -2584,7 +2585,7 @@ declare namespace ts { Expression = 1, IdentifierName = 2, MappedTypeParameter = 3, - Unspecified = 4, + Unspecified = 4 } interface TransformationContext { /** Gets the compiler options supplied to the transformer. */ @@ -2802,9 +2803,9 @@ declare namespace ts { SingleElement = 524288, Modifiers = 131328, HeritageClauses = 256, - SingleLineTypeLiteralMembers = 448, - MultiLineTypeLiteralMembers = 65, - TupleTypeElements = 336, + SingleLineTypeLiteralMembers = 384, + MultiLineTypeLiteralMembers = 16449, + TupleTypeElements = 272, UnionTypeConstituents = 260, IntersectionTypeConstituents = 264, ObjectBindingPatternElements = 262576, @@ -2825,7 +2826,7 @@ declare namespace ts { InterfaceMembers = 65, EnumMembers = 81, CaseBlockClauses = 65, - NamedImportsOrExportsElements = 432, + NamedImportsOrExportsElements = 262576, JsxElementOrFragmentChildren = 131072, JsxElementAttributes = 131328, CaseOrDefaultClauseStatements = 81985, @@ -2835,7 +2836,7 @@ declare namespace ts { TypeArguments = 26896, TypeParameters = 26896, Parameters = 1296, - IndexSignatureParameters = 4432, + IndexSignatureParameters = 4432 } } declare namespace ts { @@ -2853,7 +2854,7 @@ declare namespace ts { enum FileWatcherEventKind { Created = 0, Changed = 1, - Deleted = 2, + Deleted = 2 } type FileWatcherCallback = (fileName: string, eventKind: FileWatcherEventKind) => void; type DirectoryWatcherCallback = (fileName: string) => void; @@ -3385,6 +3386,8 @@ declare namespace ts { function createLoopVariable(): Identifier; /** Create a unique name based on the supplied text. */ function createUniqueName(text: string): Identifier; + /** Create a unique name based on the supplied text. */ + function createOptimisticUniqueName(text: string): Identifier; /** Create a unique name generated for a node. */ function getGeneratedNameForNode(node: Node): Identifier; function createToken(token: TKind): Token; @@ -3393,6 +3396,8 @@ declare namespace ts { function createNull(): NullLiteral & Token; function createTrue(): BooleanLiteral & Token; function createFalse(): BooleanLiteral & Token; + function createModifier(kind: T): Token; + function createModifiersFromModifierFlags(flags: ModifierFlags): Modifier[]; function createQualifiedName(left: EntityName, right: string | Identifier): QualifiedName; function updateQualifiedName(node: QualifiedName, left: EntityName, right: Identifier): QualifiedName; function createComputedPropertyName(expression: Expression): ComputedPropertyName; @@ -3647,7 +3652,7 @@ declare namespace ts { function updateSpreadAssignment(node: SpreadAssignment, expression: Expression): SpreadAssignment; function createEnumMember(name: string | PropertyName, initializer?: Expression): EnumMember; function updateEnumMember(node: EnumMember, name: PropertyName, initializer: Expression | undefined): EnumMember; - function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray): SourceFile; + function updateSourceFileNode(node: SourceFile, statements: ReadonlyArray, isDeclarationFile?: boolean, referencedFiles?: SourceFile["referencedFiles"], typeReferences?: SourceFile["typeReferenceDirectives"]): SourceFile; /** * Creates a shallow, memberwise clone of a node for mutation. */ @@ -4557,7 +4562,7 @@ declare namespace ts { none = "none", definition = "definition", reference = "reference", - writtenReference = "writtenReference", + writtenReference = "writtenReference" } interface HighlightSpan { fileName?: string; @@ -4579,7 +4584,7 @@ declare namespace ts { enum IndentStyle { None = 0, Block = 1, - Smart = 2, + Smart = 2 } interface EditorOptions { BaseIndentSize?: number; @@ -4674,7 +4679,7 @@ declare namespace ts { typeParameterName = 18, enumMemberName = 19, functionName = 20, - regularExpressionLiteral = 21, + regularExpressionLiteral = 21 } interface SymbolDisplayPart { text: string; @@ -4785,7 +4790,7 @@ declare namespace ts { enum OutputFileType { JavaScript = 0, SourceMap = 1, - Declaration = 2, + Declaration = 2 } enum EndOfLineState { None = 0, @@ -4794,7 +4799,7 @@ declare namespace ts { InDoubleQuoteStringLiteral = 3, InTemplateHeadOrNoSubstitutionTemplate = 4, InTemplateMiddleOrTail = 5, - InTemplateSubstitutionPosition = 6, + InTemplateSubstitutionPosition = 6 } enum TokenClass { Punctuation = 0, @@ -4805,7 +4810,7 @@ declare namespace ts { Identifier = 5, NumberLiteral = 6, StringLiteral = 7, - RegExpLiteral = 8, + RegExpLiteral = 8 } interface ClassificationResult { finalLexState: EndOfLineState; @@ -4904,7 +4909,7 @@ declare namespace ts { /** * */ - jsxAttribute = "JSX attribute", + jsxAttribute = "JSX attribute" } enum ScriptElementKindModifier { none = "", @@ -4915,7 +4920,7 @@ declare namespace ts { ambientModifier = "declare", staticModifier = "static", abstractModifier = "abstract", - optionalModifier = "optional", + optionalModifier = "optional" } enum ClassificationTypeNames { comment = "comment", @@ -4940,7 +4945,7 @@ declare namespace ts { jsxSelfClosingTagName = "jsx self closing tag name", jsxAttribute = "jsx attribute", jsxText = "jsx text", - jsxAttributeStringLiteralValue = "jsx attribute string literal value", + jsxAttributeStringLiteralValue = "jsx attribute string literal value" } enum ClassificationType { comment = 1, @@ -4966,7 +4971,7 @@ declare namespace ts { jsxSelfClosingTagName = 21, jsxAttribute = 22, jsxText = 23, - jsxAttributeStringLiteralValue = 24, + jsxAttributeStringLiteralValue = 24 } } declare namespace ts { diff --git a/tests/baselines/reference/classdecl.js b/tests/baselines/reference/classdecl.js index e7076349db381..364473be98d0e 100644 --- a/tests/baselines/reference/classdecl.js +++ b/tests/baselines/reference/classdecl.js @@ -220,11 +220,10 @@ declare class a { x: number; y: number; }; - private static d2(); + private static d2; private static readonly p3; private pv3; - private foo(n); - private foo(s); + private foo; } declare class b extends a { } @@ -259,13 +258,11 @@ declare class aAmbient { static d2(): any; static p3: any; private pv3; - private foo(s); + private foo; } declare class d { - private foo(n); - private foo(s); + private foo; } declare class e { - private foo(s); - private foo(n); + private foo; } diff --git a/tests/baselines/reference/commentsClass.js b/tests/baselines/reference/commentsClass.js index 4c5ac163ee178..69d848593e0f5 100644 --- a/tests/baselines/reference/commentsClass.js +++ b/tests/baselines/reference/commentsClass.js @@ -187,7 +187,7 @@ declare var i7_c: typeof c7; */ declare class c8 { /** s1 comment */ - static s1: number; + static s1: number; /** s1 comment2 */ /** constructor comment */ constructor(); diff --git a/tests/baselines/reference/commentsClassMembers.js b/tests/baselines/reference/commentsClassMembers.js index f53c64060a3d0..9918b0758ae40 100644 --- a/tests/baselines/reference/commentsClassMembers.js +++ b/tests/baselines/reference/commentsClassMembers.js @@ -491,7 +491,7 @@ declare class c1 { /** pp1 is property of c1*/ private pp1; /** sum with property*/ - private pp2(/** number to add*/ b); + private pp2; /** getter property*/ /** setter property*/ private pp3; @@ -508,7 +508,7 @@ declare class c1 { nc_p2(b: number): number; nc_p3: number; private nc_pp1; - private nc_pp2(b); + private nc_pp2; private nc_pp3; static nc_s1: number; static nc_s2(b: number): number; @@ -517,7 +517,7 @@ declare class c1 { a_p2(b: number): number; a_p3: number; private a_pp1; - private a_pp2(b); + private a_pp2; private a_pp3; static a_s1: number; static a_s2(b: number): number; @@ -532,7 +532,7 @@ declare class c1 { /** pp1 is property of c1 */ private b_pp1; /** sum with property */ - private b_pp2(b); + private b_pp2; /** getter property */ /** setter property */ private b_pp3; diff --git a/tests/baselines/reference/commentsEnums.js b/tests/baselines/reference/commentsEnums.js index c8cd4e3820614..8fe7097ad8e36 100644 --- a/tests/baselines/reference/commentsEnums.js +++ b/tests/baselines/reference/commentsEnums.js @@ -30,6 +30,6 @@ declare enum Colors { /** Fancy name for 'blue'*/ Cornflower = 0, /** Fancy name for 'pink'*/ - FancyPink = 1, + FancyPink = 1 } declare var x: Colors; diff --git a/tests/baselines/reference/commentsFunction.js b/tests/baselines/reference/commentsFunction.js index 23aa13aae9131..ab72c95ddcb4f 100644 --- a/tests/baselines/reference/commentsFunction.js +++ b/tests/baselines/reference/commentsFunction.js @@ -104,8 +104,8 @@ function foo2() { declare function foo(): void; /** This is comment for function signature*/ declare function fooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; +/** this is comment for b*/ +b: number): void; /** fooFunc * comment */ @@ -115,6 +115,6 @@ declare var lambddaNoVarComment: (a: number, b: number) => number; declare function blah(a: string): void; declare function blah2(a: string): void; declare function blah3(a: string): void; -declare function blah4(a: string, b: string): void; +declare function blah4(/*1*/ a: string, /*3*/ b: string): void; declare function foo1(): void; declare function foo2(): void; diff --git a/tests/baselines/reference/commentsTypeParameters.js b/tests/baselines/reference/commentsTypeParameters.js index 8ac22556f0dc4..9eabe866ec52e 100644 --- a/tests/baselines/reference/commentsTypeParameters.js +++ b/tests/baselines/reference/commentsTypeParameters.js @@ -38,7 +38,7 @@ function compare(a, b) { declare class C { method(a: U): void; static staticmethod(a: U): void; - private privatemethod(a); - private static privatestaticmethod(a); + private privatemethod; + private static privatestaticmethod; } declare function compare(a: T, b: T): boolean; diff --git a/tests/baselines/reference/commentsdoNotEmitComments.js b/tests/baselines/reference/commentsdoNotEmitComments.js index d4d57a7c35f84..ae7442f109a64 100644 --- a/tests/baselines/reference/commentsdoNotEmitComments.js +++ b/tests/baselines/reference/commentsdoNotEmitComments.js @@ -169,6 +169,6 @@ declare var x: any; declare const enum color { red = 0, green = 1, - blue = 2, + blue = 2 } declare var shade: color; diff --git a/tests/baselines/reference/commentsemitComments.js b/tests/baselines/reference/commentsemitComments.js index afd57477627f8..dd8f3608cf33f 100644 --- a/tests/baselines/reference/commentsemitComments.js +++ b/tests/baselines/reference/commentsemitComments.js @@ -178,7 +178,7 @@ interface i1 { /**indexer property*/ [a: number]: string; /** function property;*/ - myFoo(a: number): string; + myFoo(/*param prop*/ a: number): string; /** prop*/ prop: string; } diff --git a/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES5.js b/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES5.js index c57c0384afc3a..2dbf3f4f00cc0 100644 --- a/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES5.js +++ b/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES5.js @@ -8,5 +8,4 @@ var v; //// [computedPropertyNamesDeclarationEmit4_ES5.d.ts] -declare var v: { -}; +declare var v: {}; diff --git a/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES6.js b/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES6.js index 903687d078073..e16df6e8f6d5a 100644 --- a/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES6.js +++ b/tests/baselines/reference/computedPropertyNamesDeclarationEmit4_ES6.js @@ -8,5 +8,4 @@ var v; //// [computedPropertyNamesDeclarationEmit4_ES6.d.ts] -declare var v: { -}; +declare var v: {}; diff --git a/tests/baselines/reference/constEnum1.js b/tests/baselines/reference/constEnum1.js index 7065c12d8cf73..81418d54918ac 100644 --- a/tests/baselines/reference/constEnum1.js +++ b/tests/baselines/reference/constEnum1.js @@ -29,5 +29,5 @@ declare const enum E { d = -13, f = 20, g = 20, - h = 10, + h = 10 } diff --git a/tests/baselines/reference/constEnum2.js b/tests/baselines/reference/constEnum2.js index 66a44f6a1befd..8ae6a84f690cd 100644 --- a/tests/baselines/reference/constEnum2.js +++ b/tests/baselines/reference/constEnum2.js @@ -27,5 +27,5 @@ declare const enum D { d = 10, e, f, - g, + g } diff --git a/tests/baselines/reference/constEnumDeclarations.js b/tests/baselines/reference/constEnumDeclarations.js index f24769c462067..0c522d81f0f9f 100644 --- a/tests/baselines/reference/constEnumDeclarations.js +++ b/tests/baselines/reference/constEnumDeclarations.js @@ -18,10 +18,10 @@ const enum E2 { declare const enum E { A = 1, B = 2, - C = 3, + C = 3 } declare const enum E2 { A = 1, B = 2, - C = 3, + C = 3 } diff --git a/tests/baselines/reference/constEnumPropertyAccess1.js b/tests/baselines/reference/constEnumPropertyAccess1.js index 66ac7b4a45982..db733e44b1de3 100644 --- a/tests/baselines/reference/constEnumPropertyAccess1.js +++ b/tests/baselines/reference/constEnumPropertyAccess1.js @@ -54,7 +54,7 @@ declare const enum G { A = 1, B = 2, C = 3, - D = 2, + D = 2 } declare var o: { [idx: number]: boolean; diff --git a/tests/baselines/reference/constEnumPropertyAccess2.js b/tests/baselines/reference/constEnumPropertyAccess2.js index f16eda4bf2dac..5d04466fbd05b 100644 --- a/tests/baselines/reference/constEnumPropertyAccess2.js +++ b/tests/baselines/reference/constEnumPropertyAccess2.js @@ -37,7 +37,7 @@ declare const enum G { A = 1, B = 2, C = 3, - D = 2, + D = 2 } declare var z: typeof G; declare var z1: any; diff --git a/tests/baselines/reference/declFileCallSignatures.js b/tests/baselines/reference/declFileCallSignatures.js index 7c0e6d8b0a526..a0a015591a980 100644 --- a/tests/baselines/reference/declFileCallSignatures.js +++ b/tests/baselines/reference/declFileCallSignatures.js @@ -78,8 +78,8 @@ export interface ICallSignature { export interface ICallSignatureWithParameters { /** This is comment for function signature*/ (/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; } export interface ICallSignatureWithRestParameters { (a: string, ...rests: string[]): string; @@ -103,8 +103,8 @@ interface IGlobalCallSignature { interface IGlobalCallSignatureWithParameters { /** This is comment for function signature*/ (/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; } interface IGlobalCallSignatureWithRestParameters { (a: string, ...rests: string[]): string; diff --git a/tests/baselines/reference/declFileConstructSignatures.js b/tests/baselines/reference/declFileConstructSignatures.js index dd9dd7f8908ea..f3b38442381fe 100644 --- a/tests/baselines/reference/declFileConstructSignatures.js +++ b/tests/baselines/reference/declFileConstructSignatures.js @@ -78,8 +78,8 @@ export interface IConstructSignature { export interface IConstructSignatureWithParameters { /** This is comment for function signature*/ new (/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): any; + /** this is comment for b*/ + b: number): any; } export interface IConstructSignatureWithRestParameters { new (a: string, ...rests: string[]): string; @@ -103,8 +103,8 @@ interface IGlobalConstructSignature { interface IGlobalConstructSignatureWithParameters { /** This is comment for function signature*/ new (/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): any; + /** this is comment for b*/ + b: number): any; } interface IGlobalConstructSignatureWithRestParameters { new (a: string, ...rests: string[]): string; diff --git a/tests/baselines/reference/declFileConstructors.js b/tests/baselines/reference/declFileConstructors.js index f40ae2d5382fb..abf4a51d84072 100644 --- a/tests/baselines/reference/declFileConstructors.js +++ b/tests/baselines/reference/declFileConstructors.js @@ -228,8 +228,8 @@ export declare class SimpleConstructor { export declare class ConstructorWithParameters { /** This is comment for function signature*/ constructor(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number); + /** this is comment for b*/ + b: number); } export declare class ConstructorWithRestParamters { constructor(a: string, ...rests: string[]); @@ -247,7 +247,7 @@ export declare class ConstructorWithPrivateParameterProperty { constructor(x: string); } export declare class ConstructorWithOptionalParameterProperty { - x: string; + x?: string; constructor(x?: string); } export declare class ConstructorWithParameterInitializer { @@ -262,8 +262,8 @@ declare class GlobalSimpleConstructor { declare class GlobalConstructorWithParameters { /** This is comment for function signature*/ constructor(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number); + /** this is comment for b*/ + b: number); } declare class GlobalConstructorWithRestParamters { constructor(a: string, ...rests: string[]); @@ -281,7 +281,7 @@ declare class GlobalConstructorWithPrivateParameterProperty { constructor(x: string); } declare class GlobalConstructorWithOptionalParameterProperty { - x: string; + x?: string; constructor(x?: string); } declare class GlobalConstructorWithParameterInitializer { diff --git a/tests/baselines/reference/declFileEnumUsedAsValue.js b/tests/baselines/reference/declFileEnumUsedAsValue.js index 23afd5da8b0d3..ad5a859a047fb 100644 --- a/tests/baselines/reference/declFileEnumUsedAsValue.js +++ b/tests/baselines/reference/declFileEnumUsedAsValue.js @@ -20,6 +20,6 @@ var x = e; declare enum e { a = 0, b = 1, - c = 2, + c = 2 } declare var x: typeof e; diff --git a/tests/baselines/reference/declFileEnums.js b/tests/baselines/reference/declFileEnums.js index d8027ca442f12..e643f26e1d97b 100644 --- a/tests/baselines/reference/declFileEnums.js +++ b/tests/baselines/reference/declFileEnums.js @@ -75,28 +75,28 @@ var e5; declare enum e1 { a = 0, b = 1, - c = 2, + c = 2 } declare enum e2 { a = 10, b = 12, - c = 10, + c = 10 } declare enum e3 { a = 10, b, - c = 13, + c = 13 } declare enum e4 { a = 0, b = 1, c = 2, d = 10, - e = 11, + e = 11 } declare enum e5 { "Friday" = 0, "Saturday" = 1, "Sunday" = 2, - "Weekend days" = 3, + "Weekend days" = 3 } diff --git a/tests/baselines/reference/declFileForClassWithPrivateOverloadedFunction.js b/tests/baselines/reference/declFileForClassWithPrivateOverloadedFunction.js index d7e0579a4911e..5885487325dc0 100644 --- a/tests/baselines/reference/declFileForClassWithPrivateOverloadedFunction.js +++ b/tests/baselines/reference/declFileForClassWithPrivateOverloadedFunction.js @@ -16,6 +16,5 @@ var C = /** @class */ (function () { //// [declFileForClassWithPrivateOverloadedFunction.d.ts] declare class C { - private foo(x); - private foo(x); + private foo; } diff --git a/tests/baselines/reference/declFileFunctions.js b/tests/baselines/reference/declFileFunctions.js index 3e5c8af32ec00..b21210c2de565 100644 --- a/tests/baselines/reference/declFileFunctions.js +++ b/tests/baselines/reference/declFileFunctions.js @@ -172,8 +172,8 @@ function globalfooWithOverloads(a) { export declare function foo(): void; /** This is comment for function signature*/ export declare function fooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; +/** this is comment for b*/ +b: number): void; export declare function fooWithRestParameters(a: string, ...rests: string[]): string; export declare function fooWithOverloads(a: string): string; export declare function fooWithOverloads(a: number): number; @@ -187,8 +187,8 @@ export declare function fooWithTypeTypePredicateAndRestParam(a: any, ...rest: an declare function globalfoo(): void; /** This is comment for function signature*/ declare function globalfooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; +/** this is comment for b*/ +b: number): void; declare function globalfooWithRestParameters(a: string, ...rests: string[]): string; declare function globalfooWithOverloads(a: string): string; declare function globalfooWithOverloads(a: number): number; diff --git a/tests/baselines/reference/declFileGenericType2.js b/tests/baselines/reference/declFileGenericType2.js index 05424d0d024c5..ad9ec95d70042 100644 --- a/tests/baselines/reference/declFileGenericType2.js +++ b/tests/baselines/reference/declFileGenericType2.js @@ -117,7 +117,7 @@ declare module templa.dom.mvc { } } declare module templa.dom.mvc { - class AbstractElementController extends templa.mvc.AbstractController implements IElementController { + class AbstractElementController extends templa.mvc.AbstractController implements IElementController { constructor(); } } diff --git a/tests/baselines/reference/declFileMethods.js b/tests/baselines/reference/declFileMethods.js index a70dde6c3ee0c..22cfb800ef871 100644 --- a/tests/baselines/reference/declFileMethods.js +++ b/tests/baselines/reference/declFileMethods.js @@ -364,46 +364,40 @@ export declare class c1 { foo(): void; /** This is comment for function signature*/ fooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; fooWithRestParameters(a: string, ...rests: string[]): string; fooWithOverloads(a: string): string; fooWithOverloads(a: number): number; /** This comment should appear for privateFoo*/ - private privateFoo(); + private privateFoo; /** This is comment for function signature*/ - private privateFooWithParameters(/** this is comment about a*/ a, - /** this is comment for b*/ - b); - private privateFooWithRestParameters(a, ...rests); - private privateFooWithOverloads(a); - private privateFooWithOverloads(a); + private privateFooWithParameters; + private privateFooWithRestParameters; + private privateFooWithOverloads; /** This comment should appear for static foo*/ static staticFoo(): void; /** This is comment for function signature*/ static staticFooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; static staticFooWithRestParameters(a: string, ...rests: string[]): string; static staticFooWithOverloads(a: string): string; static staticFooWithOverloads(a: number): number; /** This comment should appear for privateStaticFoo*/ - private static privateStaticFoo(); + private static privateStaticFoo; /** This is comment for function signature*/ - private static privateStaticFooWithParameters(/** this is comment about a*/ a, - /** this is comment for b*/ - b); - private static privateStaticFooWithRestParameters(a, ...rests); - private static privateStaticFooWithOverloads(a); - private static privateStaticFooWithOverloads(a); + private static privateStaticFooWithParameters; + private static privateStaticFooWithRestParameters; + private static privateStaticFooWithOverloads; } export interface I1 { /** This comment should appear for foo*/ foo(): string; /** This is comment for function signature*/ fooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; fooWithRestParameters(a: string, ...rests: string[]): string; fooWithOverloads(a: string): string; fooWithOverloads(a: number): number; @@ -414,46 +408,40 @@ declare class c2 { foo(): void; /** This is comment for function signature*/ fooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; fooWithRestParameters(a: string, ...rests: string[]): string; fooWithOverloads(a: string): string; fooWithOverloads(a: number): number; /** This comment should appear for privateFoo*/ - private privateFoo(); + private privateFoo; /** This is comment for function signature*/ - private privateFooWithParameters(/** this is comment about a*/ a, - /** this is comment for b*/ - b); - private privateFooWithRestParameters(a, ...rests); - private privateFooWithOverloads(a); - private privateFooWithOverloads(a); + private privateFooWithParameters; + private privateFooWithRestParameters; + private privateFooWithOverloads; /** This comment should appear for static foo*/ static staticFoo(): void; /** This is comment for function signature*/ static staticFooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; static staticFooWithRestParameters(a: string, ...rests: string[]): string; static staticFooWithOverloads(a: string): string; static staticFooWithOverloads(a: number): number; /** This comment should appear for privateStaticFoo*/ - private static privateStaticFoo(); + private static privateStaticFoo; /** This is comment for function signature*/ - private static privateStaticFooWithParameters(/** this is comment about a*/ a, - /** this is comment for b*/ - b); - private static privateStaticFooWithRestParameters(a, ...rests); - private static privateStaticFooWithOverloads(a); - private static privateStaticFooWithOverloads(a); + private static privateStaticFooWithParameters; + private static privateStaticFooWithRestParameters; + private static privateStaticFooWithOverloads; } interface I2 { /** This comment should appear for foo*/ foo(): string; /** This is comment for function signature*/ fooWithParameters(/** this is comment about a*/ a: string, - /** this is comment for b*/ - b: number): void; + /** this is comment for b*/ + b: number): void; fooWithRestParameters(a: string, ...rests: string[]): string; fooWithOverloads(a: string): string; fooWithOverloads(a: number): number; diff --git a/tests/baselines/reference/declFileObjectLiteralWithAccessors.js b/tests/baselines/reference/declFileObjectLiteralWithAccessors.js index 8a6ebfec004db..2849617959de1 100644 --- a/tests/baselines/reference/declFileObjectLiteralWithAccessors.js +++ b/tests/baselines/reference/declFileObjectLiteralWithAccessors.js @@ -29,8 +29,8 @@ declare function makePoint(x: number): { b: number; x: number; }; -declare var point: { +declare var /*4*/ point: { b: number; x: number; }; -declare var x: number; +declare var /*2*/ x: number; diff --git a/tests/baselines/reference/declFileObjectLiteralWithOnlyGetter.js b/tests/baselines/reference/declFileObjectLiteralWithOnlyGetter.js index 1552386b3cda9..756cd3d4587df 100644 --- a/tests/baselines/reference/declFileObjectLiteralWithOnlyGetter.js +++ b/tests/baselines/reference/declFileObjectLiteralWithOnlyGetter.js @@ -23,7 +23,7 @@ var /*2*/ x = point. /*3*/x; declare function makePoint(x: number): { readonly x: number; }; -declare var point: { +declare var /*4*/ point: { readonly x: number; }; -declare var x: number; +declare var /*2*/ x: number; diff --git a/tests/baselines/reference/declFileObjectLiteralWithOnlySetter.js b/tests/baselines/reference/declFileObjectLiteralWithOnlySetter.js index 03174e7714f7c..cb8ef881d9318 100644 --- a/tests/baselines/reference/declFileObjectLiteralWithOnlySetter.js +++ b/tests/baselines/reference/declFileObjectLiteralWithOnlySetter.js @@ -25,7 +25,7 @@ declare function makePoint(x: number): { b: number; x: number; }; -declare var point: { +declare var /*3*/ point: { b: number; x: number; }; diff --git a/tests/baselines/reference/declFilePrivateMethodOverloads.js b/tests/baselines/reference/declFilePrivateMethodOverloads.js index 1a8215dced71e..0c8c49e1be278 100644 --- a/tests/baselines/reference/declFilePrivateMethodOverloads.js +++ b/tests/baselines/reference/declFilePrivateMethodOverloads.js @@ -41,13 +41,10 @@ interface IContext { someMethod(): any; } declare class c1 { - private _forEachBindingContext(bindingContext, fn); - private _forEachBindingContext(bindingContextArray, fn); - private overloadWithArityDifference(bindingContext); - private overloadWithArityDifference(bindingContextArray, fn); + private _forEachBindingContext; + private overloadWithArityDifference; } declare class c2 { - private overload1(context, fn); - private overload2(context); - private overload2(context, fn); + private overload1; + private overload2; } diff --git a/tests/baselines/reference/declFilePrivateStatic.js b/tests/baselines/reference/declFilePrivateStatic.js index 78be32e356e47..67469327265b5 100644 --- a/tests/baselines/reference/declFilePrivateStatic.js +++ b/tests/baselines/reference/declFilePrivateStatic.js @@ -49,7 +49,7 @@ var C = /** @class */ (function () { declare class C { private static x; static y: number; - private static a(); + private static a; static b(): void; private static readonly c; static readonly d: number; diff --git a/tests/baselines/reference/declFileRestParametersOfFunctionAndFunctionType.js b/tests/baselines/reference/declFileRestParametersOfFunctionAndFunctionType.js index fb0d984dbb2ec..71d7bfc0fb259 100644 --- a/tests/baselines/reference/declFileRestParametersOfFunctionAndFunctionType.js +++ b/tests/baselines/reference/declFileRestParametersOfFunctionAndFunctionType.js @@ -25,12 +25,12 @@ var f6 = function () { return [10]; }; //// [declFileRestParametersOfFunctionAndFunctionType.d.ts] declare function f1(...args: any[]): void; -declare function f2(x: (...args) => void): void; +declare function f2(x: (...args: any[]) => void): void; declare function f3(x: { - (...args): void; + (...args: any[]): void; }): void; -declare function f4 void>(): void; +declare function f4 void>(): void; declare function f5(): void; declare var f6: () => any[]; diff --git a/tests/baselines/reference/declFileTypeofEnum.js b/tests/baselines/reference/declFileTypeofEnum.js index 0e31a7c35114b..467e264dab79f 100644 --- a/tests/baselines/reference/declFileTypeofEnum.js +++ b/tests/baselines/reference/declFileTypeofEnum.js @@ -37,7 +37,7 @@ declare enum days { thursday = 3, friday = 4, saturday = 5, - sunday = 6, + sunday = 6 } declare var weekendDay: days; declare var daysOfMonth: typeof days; diff --git a/tests/baselines/reference/declFileTypeofInAnonymousType.js b/tests/baselines/reference/declFileTypeofInAnonymousType.js index 214717c248681..da8f7df5bf867 100644 --- a/tests/baselines/reference/declFileTypeofInAnonymousType.js +++ b/tests/baselines/reference/declFileTypeofInAnonymousType.js @@ -58,7 +58,7 @@ declare module m1 { enum e { weekday = 0, weekend = 1, - holiday = 2, + holiday = 2 } } declare var a: { diff --git a/tests/baselines/reference/declarationEmitBindingPatterns.js b/tests/baselines/reference/declarationEmitBindingPatterns.js index 70ac7f437d34c..a8550f5473809 100644 --- a/tests/baselines/reference/declarationEmitBindingPatterns.js +++ b/tests/baselines/reference/declarationEmitBindingPatterns.js @@ -22,4 +22,4 @@ declare const k: ({ x: z }: { x?: string; }) => void; declare var a: any; -declare function f({}?: any, []?: any, {p: {}}?: any): void; +declare function f({}?: any, []?: any, { p: {} }?: any): void; diff --git a/tests/baselines/reference/declarationEmitClassMemberNameConflict2.js b/tests/baselines/reference/declarationEmitClassMemberNameConflict2.js index 42945116527ea..4c928b0cfcb29 100644 --- a/tests/baselines/reference/declarationEmitClassMemberNameConflict2.js +++ b/tests/baselines/reference/declarationEmitClassMemberNameConflict2.js @@ -46,10 +46,10 @@ var Foo = /** @class */ (function () { //// [declarationEmitClassMemberNameConflict2.d.ts] declare const Bar = "bar"; declare enum Hello { - World = 0, + World = 0 } declare enum Hello1 { - World1 = 0, + World1 = 0 } declare class Foo { Bar: string; diff --git a/tests/baselines/reference/declarationEmitDefaultExport2.js b/tests/baselines/reference/declarationEmitDefaultExport2.js index 687c6d67cdbaf..558ba07acd6a5 100644 --- a/tests/baselines/reference/declarationEmitDefaultExport2.js +++ b/tests/baselines/reference/declarationEmitDefaultExport2.js @@ -8,5 +8,5 @@ export default class { //// [declarationEmitDefaultExport2.d.ts] -export default class { +export default class { } diff --git a/tests/baselines/reference/declarationEmitDestructuring1.js b/tests/baselines/reference/declarationEmitDestructuring1.js index 9ac08032a0dd2..6038accbc9a07 100644 --- a/tests/baselines/reference/declarationEmitDestructuring1.js +++ b/tests/baselines/reference/declarationEmitDestructuring1.js @@ -23,12 +23,12 @@ function baz(_a) { //// [declarationEmitDestructuring1.d.ts] declare function foo([a, b, c]: [string, string, string]): void; declare function far([a, [b], [[c]]]: [number, boolean[], string[][]]): void; -declare function bar({a1, b1, c1}: { +declare function bar({ a1, b1, c1 }: { a1: number; b1: boolean; c1: string; }): void; -declare function baz({a2, b2: {b1, c1}}: { +declare function baz({ a2, b2: { b1, c1 } }: { a2: number; b2: { b1: boolean; diff --git a/tests/baselines/reference/declarationEmitDestructuring2.js b/tests/baselines/reference/declarationEmitDestructuring2.js index c979b65496032..17603481ee354 100644 --- a/tests/baselines/reference/declarationEmitDestructuring2.js +++ b/tests/baselines/reference/declarationEmitDestructuring2.js @@ -20,24 +20,24 @@ function h1(_a) { //// [declarationEmitDestructuring2.d.ts] -declare function f({x, y: [a, b, c, d]}?: { +declare function f({ x, y: [a, b, c, d] }?: { x?: number; y?: [number, number, number, number]; }): void; declare function g([a, b, c, d]?: [number, number, number, number]): void; -declare function h([a, [b], [[c]], {x, y: [a, b, c], z: {a1, b1}}]: [any, [any], [[any]], { - x?: number; - y: [any, any, any]; - z: { - a1: any; - b1: any; - }; - }]): void; -declare function h1([a, [b], [[c]], {x, y, z: {a1, b1}}]: [any, [any], [[any]], { - x?: number; - y?: number[]; - z: { - a1: any; - b1: any; - }; - }]): void; +declare function h([a, [b], [[c]], { x, y: [a, b, c], z: { a1, b1 } }]: [any, [any], [[any]], { + x?: number; + y: [any, any, any]; + z: { + a1: any; + b1: any; + }; +}]): void; +declare function h1([a, [b], [[c]], { x, y, z: { a1, b1 } }]: [any, [any], [[any]], { + x?: number; + y?: number[]; + z: { + a1: any; + b1: any; + }; +}]): void; diff --git a/tests/baselines/reference/declarationEmitDestructuring5.js b/tests/baselines/reference/declarationEmitDestructuring5.js index 32c9b5667d180..e5089bb209767 100644 --- a/tests/baselines/reference/declarationEmitDestructuring5.js +++ b/tests/baselines/reference/declarationEmitDestructuring5.js @@ -24,8 +24,8 @@ function bar2(_a) { //// [declarationEmitDestructuring5.d.ts] -declare function baz([ , z, , ]: [any, any, any]): void; -declare function foo([ , b, ]: [any, any]): void; -declare function bar([z, , , ]: [any, any, any]): void; -declare function bar1([z, , , ]?: [number, number, number, number, number]): void; -declare function bar2([ , , z, , , ]: [any, any, any, any, any]): void; +declare function baz([, z, ,]: [any, any, any]): void; +declare function foo([, b,]: [any, any]): void; +declare function bar([z, , ,]: [any, any, any]): void; +declare function bar1([z, , ,]?: [number, number, number, number, number]): void; +declare function bar2([, , z, , ,]: [any, any, any, any, any]): void; diff --git a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js index c64148f8e508a..35c5439273f14 100644 --- a/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js +++ b/tests/baselines/reference/declarationEmitDestructuringOptionalBindingParametersInOverloads.js @@ -25,7 +25,7 @@ function foo2() { //// [declarationEmitDestructuringOptionalBindingParametersInOverloads.d.ts] declare function foo([x, y, z]?: [string, number, boolean]): any; -declare function foo2({x, y, z}?: { +declare function foo2({ x, y, z }?: { x: string; y: number; z: boolean; diff --git a/tests/baselines/reference/declarationEmitDestructuringParameterProperties.js b/tests/baselines/reference/declarationEmitDestructuringParameterProperties.js index 032722208cf3e..8f5650a296bc7 100644 --- a/tests/baselines/reference/declarationEmitDestructuringParameterProperties.js +++ b/tests/baselines/reference/declarationEmitDestructuringParameterProperties.js @@ -39,12 +39,16 @@ var C3 = /** @class */ (function () { //// [declarationEmitDestructuringParameterProperties.d.ts] declare class C1 { - x: string, y: string, z: string; + x: string; + y: string; + z: string; constructor([x, y, z]: string[]); } declare type TupleType1 = [string, number, boolean]; declare class C2 { - x: string, y: number, z: boolean; + x: string; + y: number; + z: boolean; constructor([x, y, z]: TupleType1); } declare type ObjType1 = { @@ -53,6 +57,8 @@ declare type ObjType1 = { z: boolean; }; declare class C3 { - x: number, y: string, z: boolean; - constructor({x, y, z}: ObjType1); + x: number; + y: string; + z: boolean; + constructor({ x, y, z }: ObjType1); } diff --git a/tests/baselines/reference/declarationEmitDestructuringWithOptionalBindingParameters.js b/tests/baselines/reference/declarationEmitDestructuringWithOptionalBindingParameters.js index 5c7f4d2cec593..094deb3b701ac 100644 --- a/tests/baselines/reference/declarationEmitDestructuringWithOptionalBindingParameters.js +++ b/tests/baselines/reference/declarationEmitDestructuringWithOptionalBindingParameters.js @@ -15,7 +15,7 @@ function foo1(_a) { //// [declarationEmitDestructuringWithOptionalBindingParameters.d.ts] declare function foo([x, y, z]?: [string, number, boolean]): void; -declare function foo1({x, y, z}?: { +declare function foo1({ x, y, z }?: { x: string; y: number; z: boolean; diff --git a/tests/baselines/reference/declarationEmitInferredTypeAlias1.js b/tests/baselines/reference/declarationEmitInferredTypeAlias1.js index 9c0fe631b123b..8b2a5bf39545d 100644 --- a/tests/baselines/reference/declarationEmitInferredTypeAlias1.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias1.js @@ -25,7 +25,7 @@ exports.v = v; //// [0.d.ts] -export { }; +export {}; //// [1.d.ts] declare let v: string | boolean; export { v }; diff --git a/tests/baselines/reference/declarationEmitInferredTypeAlias2.js b/tests/baselines/reference/declarationEmitInferredTypeAlias2.js index 73aae9d8a4080..be22f7c56491c 100644 --- a/tests/baselines/reference/declarationEmitInferredTypeAlias2.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias2.js @@ -32,7 +32,7 @@ exports.bar = bar; //// [0.d.ts] -export { }; +export {}; //// [1.d.ts] declare let v: string | boolean; declare function bar(): string | boolean; diff --git a/tests/baselines/reference/declarationEmitInferredTypeAlias3.js b/tests/baselines/reference/declarationEmitInferredTypeAlias3.js index 665cab9f9be20..1eee981140cfb 100644 --- a/tests/baselines/reference/declarationEmitInferredTypeAlias3.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias3.js @@ -25,7 +25,7 @@ exports["default"] = x; //// [0.d.ts] -export { }; +export {}; //// [1.d.ts] declare var x: string | number; export default x; diff --git a/tests/baselines/reference/declarationEmitInferredTypeAlias6.js b/tests/baselines/reference/declarationEmitInferredTypeAlias6.js index d0709cc596254..3692c2b65a921 100644 --- a/tests/baselines/reference/declarationEmitInferredTypeAlias6.js +++ b/tests/baselines/reference/declarationEmitInferredTypeAlias6.js @@ -25,7 +25,7 @@ exports.v = v; //// [0.d.ts] -export { }; +export {}; //// [1.d.ts] declare let v: string | boolean; export { v }; diff --git a/tests/baselines/reference/declarationEmitNameConflicts3.js b/tests/baselines/reference/declarationEmitNameConflicts3.js index f9c1d6266b03e..090b80836cb70 100644 --- a/tests/baselines/reference/declarationEmitNameConflicts3.js +++ b/tests/baselines/reference/declarationEmitNameConflicts3.js @@ -105,7 +105,7 @@ declare module M.P { class E extends C { } enum D { - f = 0, + f = 0 } var v: M.D; var w: typeof M.D.f; diff --git a/tests/baselines/reference/declarationEmitParameterProperty.js b/tests/baselines/reference/declarationEmitParameterProperty.js index b6e79eeee8586..2b65475419c5b 100644 --- a/tests/baselines/reference/declarationEmitParameterProperty.js +++ b/tests/baselines/reference/declarationEmitParameterProperty.js @@ -19,6 +19,6 @@ exports.Foo = Foo; //// [declarationEmitParameterProperty.d.ts] export declare class Foo { - bar: string | undefined; + bar?: string | undefined; constructor(bar?: string | undefined); } diff --git a/tests/baselines/reference/declareDottedModuleName.js b/tests/baselines/reference/declareDottedModuleName.js index 19427e941aa5b..afe7352b5bec1 100644 --- a/tests/baselines/reference/declareDottedModuleName.js +++ b/tests/baselines/reference/declareDottedModuleName.js @@ -17,8 +17,7 @@ module T.U { // This needs to be emitted declare module M { } declare module M { - module R.S { - } + module R.S { } } declare module T.U { } diff --git a/tests/baselines/reference/destructureOptionalParameter.js b/tests/baselines/reference/destructureOptionalParameter.js index 18239bddc4e98..e5424e7d00981 100644 --- a/tests/baselines/reference/destructureOptionalParameter.js +++ b/tests/baselines/reference/destructureOptionalParameter.js @@ -32,11 +32,11 @@ function f2(_a) { //// [destructureOptionalParameter.d.ts] -declare function f1({a, b}?: { +declare function f1({ a, b }?: { a: number; b: string; }): void; -declare function f2({a, b}?: { +declare function f2({ a, b }?: { a: number; b: number; }): void; @@ -47,11 +47,11 @@ interface QueryMetadata { q: void; } interface QueryMetadataFactory { - (selector: Type | string, {descendants, read}?: { + (selector: Type | string, { descendants, read }?: { descendants?: boolean; read?: any; }): ParameterDecorator; - new (selector: Type | string, {descendants, read}?: { + new (selector: Type | string, { descendants, read }?: { descendants?: boolean; read?: any; }): QueryMetadata; diff --git a/tests/baselines/reference/destructuringInFunctionType.js b/tests/baselines/reference/destructuringInFunctionType.js index 8490a14c91e19..1844e8e5a8d21 100644 --- a/tests/baselines/reference/destructuringInFunctionType.js +++ b/tests/baselines/reference/destructuringInFunctionType.js @@ -40,21 +40,31 @@ interface c { c: any; } declare type T1 = ([a, b, c]); -declare type F1 = ([a, b, c]) => void; +declare type F1 = ([a, b, c]: [any, any, any]) => void; declare type T2 = ({ - a; + a: any; }); -declare type F2 = ({a}) => void; +declare type F2 = ({ a }: { + a: any; +}) => void; declare type T3 = ([{ a: b; }, { b: a; }]); -declare type F3 = ([{a: b}, {b: a}]) => void; +declare type F3 = ([{ a: b }, { b: a }]: [{ + a: any; +}, { + b: any; +}]) => void; declare type T4 = ([{ a: [b, c]; }]); -declare type F4 = ([{a: [b, c]}]) => void; -declare type C1 = new ([{a: [b, c]}]) => void; +declare type F4 = ([{ a: [b, c] }]: [{ + a: [any, any]; +}]) => void; +declare type C1 = new ([{ a: [b, c] }]: [{ + a: [any, any]; +}]) => void; declare var v1: ([a, b, c]: [any, any, any]) => string; -declare var v2: ([a, b, c]) => string; +declare var v2: ([a, b, c]: [any, any, any]) => string; diff --git a/tests/baselines/reference/enumClassification.js b/tests/baselines/reference/enumClassification.js index 0a046dc60d2cd..5b6269ec3fdfe 100644 --- a/tests/baselines/reference/enumClassification.js +++ b/tests/baselines/reference/enumClassification.js @@ -160,28 +160,28 @@ var E20; //// [enumClassification.d.ts] declare enum E01 { - A = 0, + A = 0 } declare enum E02 { - A = 123, + A = 123 } declare enum E03 { - A = "hello", + A = "hello" } declare enum E04 { A = 0, B = 1, - C = 2, + C = 2 } declare enum E05 { A = 0, B = 10, - C = 11, + C = 11 } declare enum E06 { A = "one", B = "two", - C = "three", + C = "three" } declare enum E07 { A = 0, @@ -189,30 +189,30 @@ declare enum E07 { C = "hi", D = 10, E = 11, - F = "bye", + F = "bye" } declare enum E08 { A = 10, B = "hello", C = 10, D = "hello", - E = 10, + E = 10 } declare enum E10 { } declare enum E11 { A = 0, B = 1, - C = 2, + C = 2 } declare enum E12 { A = 1, B = 2, - C = 4, + C = 4 } declare enum E20 { A, B, C, - D, + D } diff --git a/tests/baselines/reference/enumDecl1.js b/tests/baselines/reference/enumDecl1.js index 383f463d51c93..64f1ece1c3741 100644 --- a/tests/baselines/reference/enumDecl1.js +++ b/tests/baselines/reference/enumDecl1.js @@ -16,6 +16,6 @@ declare module mAmbient { enum e { x, y, - z, + z } } diff --git a/tests/baselines/reference/es5ExportDefaultClassDeclaration2.js b/tests/baselines/reference/es5ExportDefaultClassDeclaration2.js index 979a9531590c7..0dda2fea0d93a 100644 --- a/tests/baselines/reference/es5ExportDefaultClassDeclaration2.js +++ b/tests/baselines/reference/es5ExportDefaultClassDeclaration2.js @@ -17,6 +17,6 @@ exports.default = default_1; //// [es5ExportDefaultClassDeclaration2.d.ts] -export default class { +export default class { method(): void; } diff --git a/tests/baselines/reference/es6ExportDefaultClassDeclaration2.js b/tests/baselines/reference/es6ExportDefaultClassDeclaration2.js index 3b7cb476dfdcc..33cbc9bd91009 100644 --- a/tests/baselines/reference/es6ExportDefaultClassDeclaration2.js +++ b/tests/baselines/reference/es6ExportDefaultClassDeclaration2.js @@ -11,6 +11,6 @@ export default class { //// [es6ExportDefaultClassDeclaration2.d.ts] -export default class { +export default class { method(): void; } diff --git a/tests/baselines/reference/functionDeclarationWithArgumentOfTypeFunctionTypeArray.js b/tests/baselines/reference/functionDeclarationWithArgumentOfTypeFunctionTypeArray.js index a959e52bdae54..37bcf84669c1b 100644 --- a/tests/baselines/reference/functionDeclarationWithArgumentOfTypeFunctionTypeArray.js +++ b/tests/baselines/reference/functionDeclarationWithArgumentOfTypeFunctionTypeArray.js @@ -12,5 +12,5 @@ function foo(args) { //// [functionDeclarationWithArgumentOfTypeFunctionTypeArray.d.ts] declare function foo(args: { - (x): number; + (x: any): number; }[]): number; diff --git a/tests/baselines/reference/giant.js b/tests/baselines/reference/giant.js index a3d325f5884ce..e76937b00ab7a 100644 --- a/tests/baselines/reference/giant.js +++ b/tests/baselines/reference/giant.js @@ -1118,14 +1118,14 @@ export declare class eC { pV: any; private rV; pF(): void; - private rF(); + private rF; pgF(): void; readonly pgF: any; psF(param: any): void; psF: any; - private rgF(); + private rgF; private readonly rgF; - private rsF(param); + private rsF; private rsF; static tV: any; static tF(): void; @@ -1170,14 +1170,14 @@ export declare module eM { pV: any; private rV; pF(): void; - private rF(); + private rF; pgF(): void; readonly pgF: any; psF(param: any): void; psF: any; - private rgF(); + private rgF; private readonly rgF; - private rsF(param); + private rsF; private rsF; static tV: any; static tF(): void; @@ -1221,14 +1221,12 @@ export declare module eM { } interface eI { } - module eM { - } + module eM { } var eaV: any; function eaF(): void; class eaC { } - module eaM { - } + module eaM { } } var eaV: any; function eaF(): void; @@ -1237,14 +1235,14 @@ export declare module eM { pV: any; private rV; pF(): void; - private rF(); + private rF; pgF(): void; readonly pgF: any; psF(param: any): void; psF: any; - private rgF(); + private rgF; private readonly rgF; - private rsF(param); + private rsF; private rsF; static tV: any; static tF(): void; @@ -1260,16 +1258,14 @@ export declare module eM { } interface I { } - module M { - } + module M { } var eV: any; function eF(): void; class eC { } interface eI { } - module eM { - } + module eM { } } } export declare var eaV: any; @@ -1279,14 +1275,14 @@ export declare class eaC { pV: any; private rV; pF(): void; - private rF(); + private rF; pgF(): void; readonly pgF: any; psF(param: any): void; psF: any; - private rgF(); + private rgF; private readonly rgF; - private rsF(param); + private rsF; private rsF; static tV: any; static tF(): void; @@ -1340,22 +1336,19 @@ export declare module eaM { } interface I { } - module M { - } + module M { } var eV: any; function eF(): void; class eC { } interface eI { } - module eM { - } + module eM { } var eaV: any; function eaF(): void; class eaC { } - module eaM { - } + module eaM { } } var eV: any; function eF(): void; @@ -1400,15 +1393,13 @@ export declare module eaM { function F(): void; class C { } - module M { - } + module M { } var eV: any; function eF(): void; class eC { } interface eI { } - module eM { - } + module eM { } } } diff --git a/tests/baselines/reference/importAliasFromNamespace.js b/tests/baselines/reference/importAliasFromNamespace.js index 57bfab58d9a91..56a53d6e84716 100644 --- a/tests/baselines/reference/importAliasFromNamespace.js +++ b/tests/baselines/reference/importAliasFromNamespace.js @@ -55,7 +55,7 @@ declare namespace My.Internal { const enum WhichThing { A = 0, B = 1, - C = 2, + C = 2 } } //// [usage.d.ts] diff --git a/tests/baselines/reference/internalAliasEnum.js b/tests/baselines/reference/internalAliasEnum.js index 40fac82eb4d46..9e4b7362f0f09 100644 --- a/tests/baselines/reference/internalAliasEnum.js +++ b/tests/baselines/reference/internalAliasEnum.js @@ -35,7 +35,7 @@ declare module a { enum weekend { Friday = 0, Saturday = 1, - Sunday = 2, + Sunday = 2 } } declare module c { diff --git a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js index c387fa6e2c415..f2810fec5b645 100644 --- a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithExport.js @@ -37,7 +37,7 @@ export declare module a { enum weekend { Friday = 0, Saturday = 1, - Sunday = 2, + Sunday = 2 } } export declare module c { diff --git a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js index 717652283cf96..7762bbea74104 100644 --- a/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideLocalModuleWithoutExport.js @@ -37,7 +37,7 @@ export declare module a { enum weekend { Friday = 0, Saturday = 1, - Sunday = 2, + Sunday = 2 } } export declare module c { diff --git a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js index ad07b9bd33f1c..2c8c6c308b138 100644 --- a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithExport.js @@ -34,7 +34,7 @@ export declare module a { enum weekend { Friday = 0, Saturday = 1, - Sunday = 2, + Sunday = 2 } } export import b = a.weekend; diff --git a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js index 6b5f5b17a26de..e8111a37cdd94 100644 --- a/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js +++ b/tests/baselines/reference/internalAliasEnumInsideTopLevelModuleWithoutExport.js @@ -34,7 +34,7 @@ export declare module a { enum weekend { Friday = 0, Saturday = 1, - Sunday = 2, + Sunday = 2 } } import b = a.weekend; diff --git a/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithOut.js b/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithOut.js index d160cf0a456d8..e10b3e43fb854 100644 --- a/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithOut.js +++ b/tests/baselines/reference/jsFileCompilationErrorOnDeclarationsWithJsFileReferenceWithOut.js @@ -29,6 +29,7 @@ function foo() { //// [out.d.ts] +/// declare class c { } declare function foo(): void; diff --git a/tests/baselines/reference/keepImportsInDts2.js b/tests/baselines/reference/keepImportsInDts2.js index 6e659f489dafb..f40c078a1201e 100644 --- a/tests/baselines/reference/keepImportsInDts2.js +++ b/tests/baselines/reference/keepImportsInDts2.js @@ -18,6 +18,6 @@ define(["require", "exports", "./folder/test"], function (require, exports) { //// [test.d.ts] -export { }; +export {}; //// [main.d.ts] import "./folder/test"; diff --git a/tests/baselines/reference/keepImportsInDts3.js b/tests/baselines/reference/keepImportsInDts3.js index 6589c675eaa40..fd123a40f2972 100644 --- a/tests/baselines/reference/keepImportsInDts3.js +++ b/tests/baselines/reference/keepImportsInDts3.js @@ -18,7 +18,7 @@ define("app/main", ["require", "exports", "test"], function (require, exports) { //// [outputfile.d.ts] declare module "test" { - export { }; + export {}; } declare module "app/main" { import "test"; diff --git a/tests/baselines/reference/keepImportsInDts4.js b/tests/baselines/reference/keepImportsInDts4.js index 41c07e836684e..8c8cd8e3015e8 100644 --- a/tests/baselines/reference/keepImportsInDts4.js +++ b/tests/baselines/reference/keepImportsInDts4.js @@ -18,7 +18,7 @@ define("main", ["require", "exports", "folder/test"], function (require, exports //// [outputfile.d.ts] declare module "folder/test" { - export { }; + export {}; } declare module "main" { import "folder/test"; diff --git a/tests/baselines/reference/keyofAndIndexedAccess.js b/tests/baselines/reference/keyofAndIndexedAccess.js index f059f77b17aea..1ee6bfc218b3d 100644 --- a/tests/baselines/reference/keyofAndIndexedAccess.js +++ b/tests/baselines/reference/keyofAndIndexedAccess.js @@ -976,7 +976,7 @@ declare type NumericallyIndexed = { declare const enum E { A = 0, B = 1, - C = 2, + C = 2 } declare type K00 = keyof any; declare type K01 = keyof string; diff --git a/tests/baselines/reference/moduleAugmentationGlobal1.js b/tests/baselines/reference/moduleAugmentationGlobal1.js index 80ad240fa8c2b..68e504d5019f2 100644 --- a/tests/baselines/reference/moduleAugmentationGlobal1.js +++ b/tests/baselines/reference/moduleAugmentationGlobal1.js @@ -39,7 +39,7 @@ export declare class A { } //// [f2.d.ts] import { A } from "./f1"; -declare global { +declare global { interface Array { getA(): A; } diff --git a/tests/baselines/reference/moduleAugmentationGlobal2.js b/tests/baselines/reference/moduleAugmentationGlobal2.js index 2d5be71bcd705..41cf9457d2580 100644 --- a/tests/baselines/reference/moduleAugmentationGlobal2.js +++ b/tests/baselines/reference/moduleAugmentationGlobal2.js @@ -37,7 +37,7 @@ var y = x.getCountAsString().toLowerCase(); export declare class A { } //// [f2.d.ts] -declare global { +declare global { interface Array { getCountAsString(): string; } diff --git a/tests/baselines/reference/moduleAugmentationGlobal3.js b/tests/baselines/reference/moduleAugmentationGlobal3.js index 4fa5f5bbd93c6..f1df42ad8cc8f 100644 --- a/tests/baselines/reference/moduleAugmentationGlobal3.js +++ b/tests/baselines/reference/moduleAugmentationGlobal3.js @@ -44,7 +44,7 @@ var y = x.getCountAsString().toLowerCase(); export declare class A { } //// [f2.d.ts] -declare global { +declare global { interface Array { getCountAsString(): string; } diff --git a/tests/baselines/reference/moduleAugmentationGlobal4.js b/tests/baselines/reference/moduleAugmentationGlobal4.js index dd1c589e43b0d..2f15ceeb48f19 100644 --- a/tests/baselines/reference/moduleAugmentationGlobal4.js +++ b/tests/baselines/reference/moduleAugmentationGlobal4.js @@ -30,19 +30,19 @@ require("./f2"); //// [f1.d.ts] -declare global { +declare global { interface Something { x: any; } } -export { }; +export {}; //// [f2.d.ts] -declare global { +declare global { interface Something { y: any; } } -export { }; +export {}; //// [f3.d.ts] import "./f1"; import "./f2"; diff --git a/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.js b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.js index 77b1b5f8ff430..f123c66504d05 100644 --- a/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.js +++ b/tests/baselines/reference/moduleDeclarationExportStarShadowingGlobalIsNameable.js @@ -48,7 +48,7 @@ export { Account2 as Acc }; //// [index.d.ts] export * from "./account"; //// [index.d.ts] -declare global { +declare global { interface Account { someProp: number; } diff --git a/tests/baselines/reference/moduleSymbolMerging.js b/tests/baselines/reference/moduleSymbolMerging.js index 9381e47cacf35..02421199ce60e 100644 --- a/tests/baselines/reference/moduleSymbolMerging.js +++ b/tests/baselines/reference/moduleSymbolMerging.js @@ -33,8 +33,7 @@ declare module A { } //// [B.d.ts] /// -declare module A { -} +declare module A { } declare module B { function f(): A.I; } diff --git a/tests/baselines/reference/moduledecl.js b/tests/baselines/reference/moduledecl.js index cfb0bf7c2482a..de7a5434e4df6 100644 --- a/tests/baselines/reference/moduledecl.js +++ b/tests/baselines/reference/moduledecl.js @@ -451,12 +451,12 @@ declare module "m3" { } declare module exportTests { class C1_public { - private f2(); + private f2; f3(): string; } class C3_public { - private getC2_private(); - private setC2_private(arg); + private getC2_private; + private setC2_private; private readonly c2; getC1_public(): C1_public; setC1_public(arg: C1_public): void; @@ -476,7 +476,7 @@ declare module mAmbient { enum e { x, y, - z, + z } module m3 { class C { @@ -491,7 +491,7 @@ declare module mAmbient { enum e { x, y, - z, + z } } } diff --git a/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.js b/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.js index 9cb8d0d921520..0c58b8cc7873f 100644 --- a/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.js +++ b/tests/baselines/reference/noImplicitAnyDestructuringInPrivateMethod.js @@ -28,8 +28,8 @@ exports.Bar = Bar; //// [noImplicitAnyDestructuringInPrivateMethod.d.ts] export declare class Bar { - private bar({a}); + private bar; } export declare class Bar2 { - private bar({a}); + private bar; } diff --git a/tests/baselines/reference/optionalMethods.js b/tests/baselines/reference/optionalMethods.js index 242af9bcfbab1..31b9ef03296a3 100644 --- a/tests/baselines/reference/optionalMethods.js +++ b/tests/baselines/reference/optionalMethods.js @@ -131,7 +131,7 @@ interface Foo { } declare function test1(x: Foo): void; declare class Bar { - d: number | undefined; + d?: number | undefined; e: number; a: number; b?: number; diff --git a/tests/baselines/reference/paramterDestrcuturingDeclaration.js b/tests/baselines/reference/paramterDestrcuturingDeclaration.js index a969939fdc2ca..3ce2527f57226 100644 --- a/tests/baselines/reference/paramterDestrcuturingDeclaration.js +++ b/tests/baselines/reference/paramterDestrcuturingDeclaration.js @@ -10,10 +10,10 @@ interface C { //// [paramterDestrcuturingDeclaration.d.ts] interface C { - ({p: name}: { + ({ p: name }: { p: any; }): any; - new ({p: boolean}: { + new ({ p: boolean }: { p: any; }): any; } diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/mapRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/mapRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/maprootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/maprootUrlsourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/outMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/sourceRootAbsolutePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/sourceRootRelativePathMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/sourcemapMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts index 984a65ed100f7..d61b4c3b876cd 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFile/node/bin/test.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts index 984a65ed100f7..9b9cdd4a21417 100644 --- a/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts +++ b/tests/baselines/reference/project/sourcerootUrlMixedSubfolderSpecifyOutputFileAndOutputDirectory/node/bin/outAndOutDirFile.d.ts @@ -1,3 +1,4 @@ +/// declare var m1_a1: number; declare class m1_c1 { m1_c1_p1: number; diff --git a/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.js b/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.js index 8de323b866751..dcc31f0d5caf5 100644 --- a/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.js +++ b/tests/baselines/reference/specializedSignatureIsNotSubtypeOfNonSpecializedSignature.js @@ -121,20 +121,20 @@ interface I3 { foo(x: T): any; } declare var a: { - (x: 'a'); - (x: number); - foo(x: 'a'); - foo(x: number); + (x: 'a'): any; + (x: number): any; + foo(x: 'a'): any; + foo(x: number): any; }; declare var a2: { - (x: 'a'); - (x: T); - foo(x: 'a'); - foo(x: T); + (x: 'a'): any; + (x: T): any; + foo(x: 'a'): any; + foo(x: T): any; }; declare var a3: { - (x: 'a'); - (x: T); - foo(x: 'a'); - foo(x: T); + (x: 'a'): any; + (x: T): any; + foo(x: 'a'): any; + foo(x: T): any; }; diff --git a/tests/baselines/reference/staticMethodWithTypeParameterExtendsClauseDeclFile.js b/tests/baselines/reference/staticMethodWithTypeParameterExtendsClauseDeclFile.js index 4881d3a5814c4..234b8f935d552 100644 --- a/tests/baselines/reference/staticMethodWithTypeParameterExtendsClauseDeclFile.js +++ b/tests/baselines/reference/staticMethodWithTypeParameterExtendsClauseDeclFile.js @@ -59,10 +59,10 @@ exports.publicClassWithWithPrivateTypeParameters = publicClassWithWithPrivateTyp export declare class publicClass { } export declare class publicClassWithWithPrivateTypeParameters { - private static myPrivateStaticMethod1(); - private myPrivateMethod1(); - private static myPrivateStaticMethod2(); - private myPrivateMethod2(); + private static myPrivateStaticMethod1; + private myPrivateMethod1; + private static myPrivateStaticMethod2; + private myPrivateMethod2; static myPublicStaticMethod(): void; myPublicMethod(): void; } diff --git a/tests/cases/fourslash/commentsCommentParsing.ts b/tests/cases/fourslash/commentsCommentParsing.ts index f26d2f569f8c8..0cf239bf1ff67 100644 --- a/tests/cases/fourslash/commentsCommentParsing.ts +++ b/tests/cases/fourslash/commentsCommentParsing.ts @@ -48,7 +48,7 @@ ////} ////jsDocMi/*7q*/xedComments2(/*7*/); //// -/////** jsdoc comment */ /*** malformed jsDocComment*/ +/////** jsdoc comment */ /*** triplestar jsDocComment*/ /////// Triple slash comment ////function jsDocMixedComments3() { ////} @@ -231,8 +231,8 @@ verify.currentSignatureHelpDocCommentIs("jsdoc comment \nanother jsDocComment"); verify.quickInfoAt("7q", "function jsDocMixedComments2(): void", "jsdoc comment \nanother jsDocComment"); goTo.marker('8'); -verify.currentSignatureHelpDocCommentIs("jsdoc comment "); -verify.quickInfoAt("8q", "function jsDocMixedComments3(): void", "jsdoc comment "); +verify.currentSignatureHelpDocCommentIs("jsdoc comment \n* triplestar jsDocComment"); +verify.quickInfoAt("8q", "function jsDocMixedComments3(): void", "jsdoc comment \n* triplestar jsDocComment"); goTo.marker('9'); verify.currentSignatureHelpDocCommentIs("jsdoc comment \nanother jsDocComment");