Merge remote-tracking branch 'origin/master' into javaScriptModules

# Conflicts:
#	src/compiler/parser.ts
This commit is contained in:
Ryan Cavanaugh
2015-11-09 14:48:37 -08:00
1018 changed files with 13255 additions and 24717 deletions

View File

@@ -3003,7 +3003,7 @@ namespace ts {
(<GenericType>type).typeArguments = type.typeParameters;
type.thisType = <TypeParameter>createType(TypeFlags.TypeParameter | TypeFlags.ThisType);
type.thisType.symbol = symbol;
type.thisType.constraint = getTypeWithThisArgument(type);
type.thisType.constraint = type;
}
}
return <InterfaceType>links.declaredType;
@@ -3546,6 +3546,21 @@ namespace ts {
return type.flags & TypeFlags.UnionOrIntersection ? getPropertiesOfUnionOrIntersectionType(<UnionType>type) : getPropertiesOfObjectType(type);
}
/**
* The apparent type of a type parameter is the base constraint instantiated with the type parameter
* as the type argument for the 'this' type.
*/
function getApparentTypeOfTypeParameter(type: TypeParameter) {
if (!type.resolvedApparentType) {
let constraintType = getConstraintOfTypeParameter(type);
while (constraintType && constraintType.flags & TypeFlags.TypeParameter) {
constraintType = getConstraintOfTypeParameter(<TypeParameter>constraintType);
}
type.resolvedApparentType = getTypeWithThisArgument(constraintType || emptyObjectType, type);
}
return type.resolvedApparentType;
}
/**
* For a type parameter, return the base constraint of the type parameter. For the string, number,
* boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
@@ -3553,12 +3568,7 @@ namespace ts {
*/
function getApparentType(type: Type): Type {
if (type.flags & TypeFlags.TypeParameter) {
do {
type = getConstraintOfTypeParameter(<TypeParameter>type);
} while (type && type.flags & TypeFlags.TypeParameter);
if (!type) {
type = emptyObjectType;
}
type = getApparentTypeOfTypeParameter(<TypeParameter>type);
}
if (type.flags & TypeFlags.StringLike) {
type = globalStringType;
@@ -5099,9 +5109,6 @@ namespace ts {
}
function typeParameterIdenticalTo(source: TypeParameter, target: TypeParameter): Ternary {
if (source.symbol.name !== target.symbol.name) {
return Ternary.False;
}
// covers case when both type parameters does not have constraint (both equal to noConstraintType)
if (source.constraint === target.constraint) {
return Ternary.True;
@@ -6462,9 +6469,10 @@ namespace ts {
function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type {
// Check that type is not any, assumed result is true, and we have variable symbol on the left
if (isTypeAny(type) || !assumeTrue || expr.left.kind !== SyntaxKind.Identifier || getResolvedSymbol(<Identifier>expr.left) !== symbol) {
if (isTypeAny(type) || expr.left.kind !== SyntaxKind.Identifier || getResolvedSymbol(<Identifier>expr.left) !== symbol) {
return type;
}
// Check that right operand is a function type with a prototype property
const rightType = checkExpression(expr.right);
if (!isTypeSubtypeOf(rightType, globalFunctionType)) {
@@ -6496,6 +6504,13 @@ namespace ts {
}
if (targetType) {
if (!assumeTrue) {
if (type.flags & TypeFlags.Union) {
return getUnionType(filter((<UnionType>type).types, t => !isTypeSubtypeOf(t, targetType)));
}
return type;
}
return getNarrowedType(type, targetType);
}
@@ -14944,10 +14959,20 @@ namespace ts {
getReferencedValueDeclaration,
getTypeReferenceSerializationKind,
isOptionalParameter,
isArgumentsLocalBinding
isArgumentsLocalBinding,
getExternalModuleFileFromDeclaration
};
}
function getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): SourceFile {
const specifier = getExternalModuleName(declaration);
const moduleSymbol = getSymbolAtLocation(specifier);
if (!moduleSymbol) {
return undefined;
}
return getDeclarationOfKind(moduleSymbol, SyntaxKind.SourceFile) as SourceFile;
}
function initializeTypeChecker() {
// Bind all source files and propagate errors
forEach(host.getSourceFiles(), file => {

View File

@@ -780,7 +780,8 @@ namespace ts {
};
export interface ObjectAllocator {
getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node;
getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node;
getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile;
getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol;
getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type;
getSignatureConstructor(): new (checker: TypeChecker) => Signature;
@@ -799,17 +800,17 @@ namespace ts {
function Signature(checker: TypeChecker) {
}
function Node(kind: SyntaxKind, pos: number, end: number) {
this.kind = kind;
this.pos = pos;
this.end = end;
this.flags = NodeFlags.None;
this.parent = undefined;
}
export let objectAllocator: ObjectAllocator = {
getNodeConstructor: kind => {
function Node(pos: number, end: number) {
this.pos = pos;
this.end = end;
this.flags = NodeFlags.None;
this.parent = undefined;
}
Node.prototype = { kind };
return <any>Node;
},
getNodeConstructor: () => <any>Node,
getSourceFileConstructor: () => <any>Node,
getSymbolConstructor: () => <any>Symbol,
getTypeConstructor: () => <any>Type,
getSignatureConstructor: () => <any>Signature

View File

@@ -45,18 +45,22 @@ namespace ts {
let writeLine: () => void;
let increaseIndent: () => void;
let decreaseIndent: () => void;
let writeTextOfNode: (sourceFile: SourceFile, node: Node) => void;
let writeTextOfNode: (text: string, node: Node) => void;
let writer = createAndSetNewTextWriterWithSymbolWriter();
let enclosingDeclaration: Node;
let currentSourceFile: SourceFile;
let currentText: string;
let currentLineMap: number[];
let currentIdentifiers: Map<string>;
let isCurrentFileExternalModule: boolean;
let reportedDeclarationError = false;
let errorNameNode: DeclarationName;
const emitJsDocComments = compilerOptions.removeComments ? function (declaration: Node) { } : writeJsDocComments;
const emit = compilerOptions.stripInternal ? stripInternal : emitNode;
let noDeclare = !root;
const moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = [];
let moduleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = [];
let asynchronousSubModuleDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[];
// Contains the reference paths that needs to go in the declaration file.
@@ -104,15 +108,16 @@ namespace ts {
else {
// Emit references corresponding to this file
const emittedReferencedFiles: SourceFile[] = [];
let prevModuleElementDeclarationEmitInfo: ModuleElementDeclarationEmitInfo[] = [];
forEach(host.getSourceFiles(), sourceFile => {
if (!isExternalModuleOrDeclarationFile(sourceFile)) {
if (!isDeclarationFile(sourceFile)) {
// Check what references need to be added
if (!compilerOptions.noResolve) {
forEach(sourceFile.referencedFiles, fileReference => {
const referencedFile = tryResolveScriptReference(host, sourceFile, fileReference);
// If the reference file is a declaration file or an external module, emit that reference
if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) &&
// If the reference file is a declaration file, emit that reference
if (referencedFile && (isDeclarationFile(referencedFile) &&
!contains(emittedReferencedFiles, referencedFile))) { // If the file reference was not already emitted
writeReferencePath(referencedFile);
@@ -120,10 +125,43 @@ namespace ts {
}
});
}
}
if (!isExternalModuleOrDeclarationFile(sourceFile)) {
noDeclare = false;
emitSourceFile(sourceFile);
}
else if (isExternalModule(sourceFile)) {
noDeclare = true;
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 === 1);
increaseIndent();
writeImportDeclaration(<ImportDeclaration>aliasEmitInfo.node);
aliasEmitInfo.asynchronousOutput = writer.getText();
decreaseIndent();
}
});
setWriter(oldWriter);
}
prevModuleElementDeclarationEmitInfo = prevModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo);
moduleElementDeclarationEmitInfo = [];
}
});
moduleElementDeclarationEmitInfo = moduleElementDeclarationEmitInfo.concat(prevModuleElementDeclarationEmitInfo);
}
return {
@@ -134,14 +172,13 @@ namespace ts {
};
function hasInternalAnnotation(range: CommentRange) {
const text = currentSourceFile.text;
const comment = text.substring(range.pos, range.end);
const comment = currentText.substring(range.pos, range.end);
return comment.indexOf("@internal") >= 0;
}
function stripInternal(node: Node) {
if (node) {
const leadingCommentRanges = getLeadingCommentRanges(currentSourceFile.text, node.pos);
const leadingCommentRanges = getLeadingCommentRanges(currentText, node.pos);
if (forEach(leadingCommentRanges, hasInternalAnnotation)) {
return;
}
@@ -243,7 +280,7 @@ namespace ts {
if (errorInfo.typeName) {
diagnostics.push(createDiagnosticForNode(symbolAccesibilityResult.errorNode || errorInfo.errorNode,
errorInfo.diagnosticMessage,
getSourceTextOfNodeFromSourceFile(currentSourceFile, errorInfo.typeName),
getTextOfNodeFromSourceText(currentText, errorInfo.typeName),
symbolAccesibilityResult.errorSymbolName,
symbolAccesibilityResult.errorModuleName));
}
@@ -321,10 +358,10 @@ namespace ts {
function writeJsDocComments(declaration: Node) {
if (declaration) {
const jsDocComments = getJsDocComments(declaration, currentSourceFile);
emitNewLineBeforeLeadingComments(currentSourceFile, writer, declaration, jsDocComments);
const jsDocComments = getJsDocCommentsFromText(declaration, currentText);
emitNewLineBeforeLeadingComments(currentLineMap, writer, declaration, jsDocComments);
// jsDoc comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentSourceFile, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange);
emitComments(currentText, currentLineMap, writer, jsDocComments, /*trailingSeparator*/ true, newLine, writeCommentRange);
}
}
@@ -343,7 +380,7 @@ namespace ts {
case SyntaxKind.VoidKeyword:
case SyntaxKind.ThisKeyword:
case SyntaxKind.StringLiteral:
return writeTextOfNode(currentSourceFile, type);
return writeTextOfNode(currentText, type);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>type);
case SyntaxKind.TypeReference:
@@ -375,14 +412,14 @@ namespace ts {
function writeEntityName(entityName: EntityName | Expression) {
if (entityName.kind === SyntaxKind.Identifier) {
writeTextOfNode(currentSourceFile, entityName);
writeTextOfNode(currentText, entityName);
}
else {
const left = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).left : (<PropertyAccessExpression>entityName).expression;
const right = entityName.kind === SyntaxKind.QualifiedName ? (<QualifiedName>entityName).right : (<PropertyAccessExpression>entityName).name;
writeEntityName(left);
write(".");
writeTextOfNode(currentSourceFile, right);
writeTextOfNode(currentText, right);
}
}
@@ -417,7 +454,7 @@ namespace ts {
}
function emitTypePredicate(type: TypePredicateNode) {
writeTextOfNode(currentSourceFile, type.parameterName);
writeTextOfNode(currentText, type.parameterName);
write(" is ");
emitType(type.type);
}
@@ -466,9 +503,12 @@ namespace ts {
}
function emitSourceFile(node: SourceFile) {
currentSourceFile = node;
currentText = node.text;
currentLineMap = getLineStarts(node);
currentIdentifiers = node.identifiers;
isCurrentFileExternalModule = isExternalModule(node);
enclosingDeclaration = node;
emitDetachedComments(currentSourceFile, writer, writeCommentRange, node, newLine, true /* remove comments */);
emitDetachedComments(currentText, currentLineMap, writer, writeCommentRange, node, newLine, true /* remove comments */);
emitLines(node.statements);
}
@@ -478,13 +518,13 @@ namespace ts {
// do not need to keep track of created temp names.
function getExportDefaultTempVariableName(): string {
const baseName = "_default";
if (!hasProperty(currentSourceFile.identifiers, baseName)) {
if (!hasProperty(currentIdentifiers, baseName)) {
return baseName;
}
let count = 0;
while (true) {
const name = baseName + "_" + (++count);
if (!hasProperty(currentSourceFile.identifiers, name)) {
if (!hasProperty(currentIdentifiers, name)) {
return name;
}
}
@@ -493,7 +533,7 @@ namespace ts {
function emitExportAssignment(node: ExportAssignment) {
if (node.expression.kind === SyntaxKind.Identifier) {
write(node.isExportEquals ? "export = " : "export default ");
writeTextOfNode(currentSourceFile, node.expression);
writeTextOfNode(currentText, node.expression);
}
else {
// Expression
@@ -537,7 +577,7 @@ namespace ts {
}
// 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 && isExternalModule(currentSourceFile))) {
(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
@@ -593,7 +633,7 @@ namespace ts {
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 === currentSourceFile) {
if (node.parent.kind === SyntaxKind.SourceFile) {
// If the node is exported
if (node.flags & NodeFlags.Export) {
write("export ");
@@ -602,7 +642,7 @@ namespace ts {
if (node.flags & NodeFlags.Default) {
write("default ");
}
else if (node.kind !== SyntaxKind.InterfaceDeclaration) {
else if (node.kind !== SyntaxKind.InterfaceDeclaration && !noDeclare) {
write("declare ");
}
}
@@ -632,7 +672,7 @@ namespace ts {
write("export ");
}
write("import ");
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
write(" = ");
if (isInternalModuleImportEqualsDeclaration(node)) {
emitTypeWithNewGetSymbolAccessibilityDiagnostic(<EntityName>node.moduleReference, getImportEntityNameVisibilityError);
@@ -640,7 +680,7 @@ namespace ts {
}
else {
write("require(");
writeTextOfNode(currentSourceFile, getExternalModuleImportEqualsDeclarationExpression(node));
writeTextOfNode(currentText, getExternalModuleImportEqualsDeclarationExpression(node));
write(");");
}
writer.writeLine();
@@ -678,7 +718,7 @@ namespace ts {
if (node.importClause) {
const currentWriterPos = writer.getTextPos();
if (node.importClause.name && resolver.isDeclarationVisible(node.importClause)) {
writeTextOfNode(currentSourceFile, node.importClause.name);
writeTextOfNode(currentText, node.importClause.name);
}
if (node.importClause.namedBindings && isVisibleNamedBinding(node.importClause.namedBindings)) {
if (currentWriterPos !== writer.getTextPos()) {
@@ -687,7 +727,7 @@ namespace ts {
}
if (node.importClause.namedBindings.kind === SyntaxKind.NamespaceImport) {
write("* as ");
writeTextOfNode(currentSourceFile, (<NamespaceImport>node.importClause.namedBindings).name);
writeTextOfNode(currentText, (<NamespaceImport>node.importClause.namedBindings).name);
}
else {
write("{ ");
@@ -697,17 +737,31 @@ namespace ts {
}
write(" from ");
}
writeTextOfNode(currentSourceFile, node.moduleSpecifier);
emitExternalModuleSpecifier(node.moduleSpecifier);
write(";");
writer.writeLine();
}
function emitExternalModuleSpecifier(moduleSpecifier: Expression) {
if (moduleSpecifier.kind === SyntaxKind.StringLiteral && (!root) && (compilerOptions.out || compilerOptions.outFile)) {
const moduleName = getExternalModuleNameFromDeclaration(host, resolver, moduleSpecifier.parent as (ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration));
if (moduleName) {
write("\"");
write(moduleName);
write("\"");
return;
}
}
writeTextOfNode(currentText, moduleSpecifier);
}
function emitImportOrExportSpecifier(node: ImportOrExportSpecifier) {
if (node.propertyName) {
writeTextOfNode(currentSourceFile, node.propertyName);
writeTextOfNode(currentText, node.propertyName);
write(" as ");
}
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
}
function emitExportSpecifier(node: ExportSpecifier) {
@@ -733,7 +787,7 @@ namespace ts {
}
if (node.moduleSpecifier) {
write(" from ");
writeTextOfNode(currentSourceFile, node.moduleSpecifier);
emitExternalModuleSpecifier(node.moduleSpecifier);
}
write(";");
writer.writeLine();
@@ -748,11 +802,11 @@ namespace ts {
else {
write("module ");
}
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
while (node.body.kind !== SyntaxKind.ModuleBlock) {
node = <ModuleDeclaration>node.body;
write(".");
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
}
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
@@ -772,7 +826,7 @@ namespace ts {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("type ");
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
emitTypeParameters(node.typeParameters);
write(" = ");
emitTypeWithNewGetSymbolAccessibilityDiagnostic(node.type, getTypeAliasDeclarationVisibilityError);
@@ -796,7 +850,7 @@ namespace ts {
write("const ");
}
write("enum ");
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
write(" {");
writeLine();
increaseIndent();
@@ -808,7 +862,7 @@ namespace ts {
function emitEnumMemberDeclaration(node: EnumMember) {
emitJsDocComments(node);
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
const enumMemberValue = resolver.getConstantValue(node);
if (enumMemberValue !== undefined) {
write(" = ");
@@ -827,7 +881,7 @@ namespace ts {
increaseIndent();
emitJsDocComments(node);
decreaseIndent();
writeTextOfNode(currentSourceFile, node.name);
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 ");
@@ -958,7 +1012,7 @@ namespace ts {
}
write("class ");
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -982,7 +1036,7 @@ namespace ts {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("interface ");
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node;
emitTypeParameters(node.typeParameters);
@@ -1020,7 +1074,7 @@ namespace ts {
// 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(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
// If optional property emit ?
if ((node.kind === SyntaxKind.PropertyDeclaration || node.kind === SyntaxKind.PropertySignature) && hasQuestionToken(node)) {
write("?");
@@ -1107,7 +1161,7 @@ namespace ts {
emitBindingPattern(<BindingPattern>bindingElement.name);
}
else {
writeTextOfNode(currentSourceFile, bindingElement.name);
writeTextOfNode(currentText, bindingElement.name);
writeTypeOfDeclaration(bindingElement, /*type*/ undefined, getBindingElementTypeVisibilityError);
}
}
@@ -1157,7 +1211,7 @@ namespace ts {
emitJsDocComments(accessors.getAccessor);
emitJsDocComments(accessors.setAccessor);
emitClassMemberDeclarationFlags(node);
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
if (!(node.flags & NodeFlags.Private)) {
accessorWithTypeAnnotation = node;
let type = getTypeAnnotationFromAccessor(node);
@@ -1247,13 +1301,13 @@ namespace ts {
}
if (node.kind === SyntaxKind.FunctionDeclaration) {
write("function ");
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
}
else if (node.kind === SyntaxKind.Constructor) {
write("constructor");
}
else {
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
if (hasQuestionToken(node)) {
write("?");
}
@@ -1393,7 +1447,7 @@ namespace ts {
emitBindingPattern(<BindingPattern>node.name);
}
else {
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
}
if (resolver.isOptionalParameter(node)) {
write("?");
@@ -1519,7 +1573,7 @@ namespace ts {
// Example:
// original: function foo({y: [a,b,c]}) {}
// emit : declare function foo({y: [a, b, c]}: { y: [any, any, any] }) void;
writeTextOfNode(currentSourceFile, bindingElement.propertyName);
writeTextOfNode(currentText, bindingElement.propertyName);
write(": ");
}
if (bindingElement.name) {
@@ -1542,7 +1596,7 @@ namespace ts {
if (bindingElement.dotDotDotToken) {
write("...");
}
writeTextOfNode(currentSourceFile, bindingElement.name);
writeTextOfNode(currentText, bindingElement.name);
}
}
}

View File

@@ -2310,7 +2310,6 @@
"category": "Message",
"code": 6078
},
"Specify JSX code generation: 'preserve' or 'react'": {
"category": "Message",
"code": 6080
@@ -2319,7 +2318,10 @@
"category": "Message",
"code": 6081
},
"Only 'amd' and 'system' modules are supported alongside --{0}.": {
"category": "Error",
"code": 6082
},
"Variable '{0}' implicitly has an '{1}' type.": {
"category": "Error",
"code": 7005

View File

@@ -7,6 +7,18 @@ namespace ts {
return isExternalModule(sourceFile) || isDeclarationFile(sourceFile);
}
export function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string {
return file.moduleName || getExternalModuleNameFromPath(host, file.fileName);
}
export function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string {
const file = resolver.getExternalModuleFileFromDeclaration(declaration);
if (!file || isDeclarationFile(file)) {
return undefined;
}
return getResolvedExternalModuleName(host, file);
}
type DependencyGroup = Array<ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration>;
const enum Jump {
@@ -332,17 +344,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
const newLine = host.getNewLine();
const jsxDesugaring = host.getCompilerOptions().jsx !== JsxEmit.Preserve;
const shouldEmitJsx = (s: SourceFile) => (s.languageVariant === LanguageVariant.JSX && !jsxDesugaring);
const outFile = compilerOptions.outFile || compilerOptions.out;
const emitJavaScript = createFileEmitter();
if (targetSourceFile === undefined) {
forEach(host.getSourceFiles(), sourceFile => {
if (shouldEmitToOwnFile(sourceFile, compilerOptions)) {
const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, sourceFile);
}
});
if (compilerOptions.outFile || compilerOptions.out) {
emitFile(compilerOptions.outFile || compilerOptions.out);
if (outFile) {
emitFile(outFile);
}
else {
forEach(host.getSourceFiles(), sourceFile => {
if (shouldEmitToOwnFile(sourceFile, compilerOptions)) {
const jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, sourceFile);
}
});
}
}
else {
@@ -351,8 +367,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
const jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, shouldEmitJsx(targetSourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, targetSourceFile);
}
else if (!isDeclarationFile(targetSourceFile) && (compilerOptions.outFile || compilerOptions.out)) {
emitFile(compilerOptions.outFile || compilerOptions.out);
else if (!isDeclarationFile(targetSourceFile) && outFile) {
emitFile(outFile);
}
}
@@ -470,11 +486,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function emitJavaScript(jsFilePath: string, root?: SourceFile) {
const writer = createTextWriter(newLine);
function createFileEmitter(): (jsFilePath: string, root?: SourceFile) => void {
const writer: EmitTextWriter = createTextWriter(newLine);
const { write, writeTextOfNode, writeLine, increaseIndent, decreaseIndent } = writer;
let currentSourceFile: SourceFile;
let currentText: string;
let currentLineMap: number[];
let currentFileIdentifiers: Map<string>;
let renamedDependencies: Map<string>;
let isEs6Module: boolean;
let isCurrentFileExternalModule: boolean;
// name of an exporter function if file is a System external module
// System.register([...], function (<exporter>) {...})
// exporting in System modules looks like:
@@ -483,17 +506,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// var x;... exporter("x", x = 1)
let exportFunctionForFile: string;
const generatedNameSet: Map<string> = {};
const nodeToGeneratedName: string[] = [];
let generatedNameSet: Map<string>;
let nodeToGeneratedName: string[];
let computedPropertyNamesToGeneratedNames: string[];
let convertedLoopState: ConvertedLoopState;
let extendsEmitted = false;
let decorateEmitted = false;
let paramEmitted = false;
let awaiterEmitted = false;
let tempFlags = 0;
let extendsEmitted: boolean;
let decorateEmitted: boolean;
let paramEmitted: boolean;
let awaiterEmitted: boolean;
let tempFlags: TempFlags;
let tempVariables: Identifier[];
let tempParameters: Identifier[];
let externalImports: (ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration)[];
@@ -536,10 +559,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
/** Sourcemap data that will get encoded */
let sourceMapData: SourceMapData;
/** The root file passed to the emit function (if present) */
let root: SourceFile;
/** If removeComments is true, no leading-comments needed to be emitted **/
const emitLeadingCommentsOfPosition = compilerOptions.removeComments ? function (pos: number) { } : emitLeadingCommentsOfPositionWorker;
const moduleEmitDelegates: Map<(node: SourceFile) => void> = {
const moduleEmitDelegates: Map<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
[ModuleKind.ES6]: emitES6Module,
[ModuleKind.AMD]: emitAMDModule,
[ModuleKind.System]: emitSystemModule,
@@ -547,35 +573,86 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
[ModuleKind.CommonJS]: emitCommonJSModule,
};
if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
initializeEmitterWithSourceMaps();
}
const bundleEmitDelegates: Map<(node: SourceFile, emitRelativePathAsModuleName?: boolean) => void> = {
[ModuleKind.ES6]() {},
[ModuleKind.AMD]: emitAMDModule,
[ModuleKind.System]: emitSystemModule,
[ModuleKind.UMD]() {},
[ModuleKind.CommonJS]() {},
};
if (root) {
// Do not call emit directly. It does not set the currentSourceFile.
emitSourceFile(root);
}
else {
forEach(host.getSourceFiles(), sourceFile => {
if (!isExternalModuleOrDeclarationFile(sourceFile)) {
emitSourceFile(sourceFile);
return doEmit;
function doEmit(jsFilePath: string, rootFile?: SourceFile) {
// reset the state
writer.reset();
currentSourceFile = undefined;
currentText = undefined;
currentLineMap = undefined;
exportFunctionForFile = undefined;
generatedNameSet = {};
nodeToGeneratedName = [];
computedPropertyNamesToGeneratedNames = undefined;
convertedLoopState = undefined;
extendsEmitted = false;
decorateEmitted = false;
paramEmitted = false;
awaiterEmitted = false;
tempFlags = 0;
tempVariables = undefined;
tempParameters = undefined;
externalImports = undefined;
exportSpecifiers = undefined;
exportEquals = undefined;
hasExportStars = undefined;
detachedCommentsInfo = undefined;
sourceMapData = undefined;
isEs6Module = false;
renamedDependencies = undefined;
isCurrentFileExternalModule = false;
root = rootFile;
if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) {
initializeEmitterWithSourceMaps(jsFilePath, root);
}
if (root) {
// Do not call emit directly. It does not set the currentSourceFile.
emitSourceFile(root);
}
else {
if (modulekind) {
forEach(host.getSourceFiles(), emitEmitHelpers);
}
});
}
forEach(host.getSourceFiles(), sourceFile => {
if ((!isExternalModuleOrDeclarationFile(sourceFile)) || (modulekind && isExternalModule(sourceFile))) {
emitSourceFile(sourceFile);
}
});
}
writeLine();
writeEmittedFiles(writer.getText(), /*writeByteOrderMark*/ compilerOptions.emitBOM);
return;
writeLine();
writeEmittedFiles(writer.getText(), jsFilePath, /*writeByteOrderMark*/ compilerOptions.emitBOM);
}
function emitSourceFile(sourceFile: SourceFile): void {
currentSourceFile = sourceFile;
currentText = sourceFile.text;
currentLineMap = getLineStarts(sourceFile);
exportFunctionForFile = undefined;
isEs6Module = sourceFile.symbol && sourceFile.symbol.exports && !!sourceFile.symbol.exports["___esModule"];
renamedDependencies = sourceFile.renamedDependencies;
currentFileIdentifiers = sourceFile.identifiers;
isCurrentFileExternalModule = isExternalModule(sourceFile);
emit(sourceFile);
}
function isUniqueName(name: string): boolean {
return !resolver.hasGlobalName(name) &&
!hasProperty(currentSourceFile.identifiers, name) &&
!hasProperty(currentFileIdentifiers, name) &&
!hasProperty(generatedNameSet, name);
}
@@ -667,7 +744,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return nodeToGeneratedName[id] || (nodeToGeneratedName[id] = unescapeIdentifier(generateNameForNode(node)));
}
function initializeEmitterWithSourceMaps() {
function initializeEmitterWithSourceMaps(jsFilePath: string, root?: SourceFile) {
let sourceMapDir: string; // The directory in which sourcemap will be
// Current source map file and its index in the sources list
@@ -771,7 +848,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function recordSourceMapSpan(pos: number) {
const sourceLinePos = getLineAndCharacterOfPosition(currentSourceFile, pos);
const sourceLinePos = computeLineAndCharacterOfPosition(currentLineMap, pos);
// Convert the location to be one-based.
sourceLinePos.line++;
@@ -810,7 +887,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function recordEmitNodeStartSpan(node: Node) {
// Get the token pos after skipping to the token (ignoring the leading trivia)
recordSourceMapSpan(skipTrivia(currentSourceFile.text, node.pos));
recordSourceMapSpan(skipTrivia(currentText, node.pos));
}
function recordEmitNodeEndSpan(node: Node) {
@@ -818,7 +895,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function writeTextWithSpanRecord(tokenKind: SyntaxKind, startPos: number, emitFn?: () => void) {
const tokenStartPos = ts.skipTrivia(currentSourceFile.text, startPos);
const tokenStartPos = ts.skipTrivia(currentText, startPos);
recordSourceMapSpan(tokenStartPos);
const tokenEndPos = emitTokenText(tokenKind, tokenStartPos, emitFn);
recordSourceMapSpan(tokenEndPos);
@@ -912,9 +989,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
sourceMapNameIndices.pop();
};
function writeCommentRangeWithMap(curentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) {
function writeCommentRangeWithMap(currentText: string, currentLineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) {
recordSourceMapSpan(comment.pos);
writeCommentRange(currentSourceFile, writer, comment, newLine);
writeCommentRange(currentText, currentLineMap, writer, comment, newLine);
recordSourceMapSpan(comment.end);
}
@@ -950,7 +1027,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function writeJavaScriptAndSourceMapFile(emitOutput: string, writeByteOrderMark: boolean) {
function writeJavaScriptAndSourceMapFile(emitOutput: string, jsFilePath: string, writeByteOrderMark: boolean) {
encodeLastRecordedSourceMapSpan();
const sourceMapText = serializeSourceMapContents(
@@ -977,7 +1054,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
// Write sourcemap url to the js file and write the js file
writeJavaScriptFile(emitOutput + sourceMapUrl, writeByteOrderMark);
writeJavaScriptFile(emitOutput + sourceMapUrl, jsFilePath, writeByteOrderMark);
}
// Initialize source map data
@@ -1059,7 +1136,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
writeComment = writeCommentRangeWithMap;
}
function writeJavaScriptFile(emitOutput: string, writeByteOrderMark: boolean) {
function writeJavaScriptFile(emitOutput: string, jsFilePath: string, writeByteOrderMark: boolean) {
writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
}
@@ -1269,7 +1346,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// If we don't need to downlevel and we can reach the original source text using
// the node's parent reference, then simply get the text as it was originally written.
if (node.parent) {
return getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
return getTextOfNodeFromSourceText(currentText, node);
}
// If we can't reach the original source text, use the canonical form if it's a number,
@@ -1300,7 +1377,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Find original source text, since we need to emit the raw strings of the tagged template.
// The raw strings contain the (escaped) strings of what the user wrote.
// Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
let text = getTextOfNodeFromSourceText(currentText, node);
// text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
// thus we need to remove those characters.
@@ -1772,7 +1849,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write((<LiteralExpression>node).text);
}
else {
writeTextOfNode(currentSourceFile, node);
writeTextOfNode(currentText, node);
}
write("\"");
@@ -1876,7 +1953,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Identifier references named import
write(getGeneratedNameForNode(<ImportDeclaration>declaration.parent.parent.parent));
const name = (<ImportSpecifier>declaration).propertyName || (<ImportSpecifier>declaration).name;
const identifier = getSourceTextOfNodeFromSourceFile(currentSourceFile, name);
const identifier = getTextOfNodeFromSourceText(currentText, name);
if (languageVersion === ScriptTarget.ES3 && identifier === "default") {
write(`["default"]`);
}
@@ -1902,7 +1979,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(node.text);
}
else {
writeTextOfNode(currentSourceFile, node);
writeTextOfNode(currentText, node);
}
}
@@ -1943,7 +2020,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(node.text);
}
else {
writeTextOfNode(currentSourceFile, node);
writeTextOfNode(currentText, node);
}
}
@@ -2403,7 +2480,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitShorthandPropertyAssignment(node: ShorthandPropertyAssignment) {
// The name property of a short-hand property assignment is considered an expression position, so here
// we manually emit the identifier to avoid rewriting.
writeTextOfNode(currentSourceFile, node.name);
writeTextOfNode(currentText, node.name);
// If emitting pre-ES6 code, or if the name requires rewriting when resolved as an expression identifier,
// we emit a normal property assignment. For example:
// module m {
@@ -2480,11 +2557,11 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// 1 .toString is a valid property access, emit a space after the literal
// Also emit a space if expression is a integer const enum value - it will appear in generated code as numeric literal
let shouldEmitSpace: boolean;
let shouldEmitSpace = false;
if (!indentedBeforeDot) {
if (node.expression.kind === SyntaxKind.NumericLiteral) {
// check if numeric literal was originally written with a dot
const text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
const text = getTextOfNodeFromSourceText(currentText, node.expression);
shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
}
else {
@@ -3815,18 +3892,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function nodeStartPositionsAreOnSameLine(node1: Node, node2: Node) {
return getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node1.pos)) ===
getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node2.pos));
return getLineOfLocalPositionFromLineMap(currentLineMap, skipTrivia(currentText, node1.pos)) ===
getLineOfLocalPositionFromLineMap(currentLineMap, skipTrivia(currentText, node2.pos));
}
function nodeEndPositionsAreOnSameLine(node1: Node, node2: Node) {
return getLineOfLocalPosition(currentSourceFile, node1.end) ===
getLineOfLocalPosition(currentSourceFile, node2.end);
return getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
getLineOfLocalPositionFromLineMap(currentLineMap, node2.end);
}
function nodeEndIsOnSameLineAsNodeStart(node1: Node, node2: Node) {
return getLineOfLocalPosition(currentSourceFile, node1.end) ===
getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node2.pos));
return getLineOfLocalPositionFromLineMap(currentLineMap, node1.end) ===
getLineOfLocalPositionFromLineMap(currentLineMap, skipTrivia(currentText, node2.pos));
}
function emitCaseOrDefaultClause(node: CaseOrDefaultClause) {
@@ -3948,7 +4025,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
Debug.assert(!!(node.flags & NodeFlags.Default) || node.kind === SyntaxKind.ExportAssignment);
// only allow export default at a source file level
if (modulekind === ModuleKind.CommonJS || modulekind === ModuleKind.AMD || modulekind === ModuleKind.UMD) {
if (!currentSourceFile.symbol.exports["___esModule"]) {
if (!isEs6Module) {
if (languageVersion === ScriptTarget.ES5) {
// default value of configurable, enumerable, writable are `false`.
write("Object.defineProperty(exports, \"__esModule\", { value: true });");
@@ -6304,8 +6381,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
* Here we check if alternative name was provided for a given moduleName and return it if possible.
*/
function tryRenameExternalModule(moduleName: LiteralExpression): string {
if (currentSourceFile.renamedDependencies && hasProperty(currentSourceFile.renamedDependencies, moduleName.text)) {
return `"${currentSourceFile.renamedDependencies[moduleName.text]}"`;
if (renamedDependencies && hasProperty(renamedDependencies, moduleName.text)) {
return `"${renamedDependencies[moduleName.text]}"`;
}
return undefined;
}
@@ -6467,7 +6544,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// - current file is not external module
// - import declaration is top level and target is value imported by entity name
if (resolver.isReferencedAliasDeclaration(node) ||
(!isExternalModule(currentSourceFile) && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
(!isCurrentFileExternalModule && resolver.isTopLevelValueImportEqualsWithEntityName(node))) {
emitLeadingComments(node);
emitStart(node);
@@ -6708,7 +6785,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function getLocalNameForExternalImport(node: ImportDeclaration | ExportDeclaration | ImportEqualsDeclaration): string {
const namespaceDeclaration = getNamespaceDeclarationNode(node);
if (namespaceDeclaration && !isDefaultImport(node)) {
return getSourceTextOfNodeFromSourceFile(currentSourceFile, namespaceDeclaration.name);
return getTextOfNodeFromSourceText(currentText, namespaceDeclaration.name);
}
if (node.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>node).importClause) {
return getGeneratedNameForNode(node);
@@ -7064,7 +7141,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function isCurrentFileSystemExternalModule() {
return modulekind === ModuleKind.System && isExternalModule(currentSourceFile);
return modulekind === ModuleKind.System && isCurrentFileExternalModule;
}
function emitSystemModuleBody(node: SourceFile, dependencyGroups: DependencyGroup[], startIndex: number): void {
@@ -7249,7 +7326,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("}"); // execute
}
function emitSystemModule(node: SourceFile): void {
function writeModuleName(node: SourceFile, emitRelativePathAsModuleName?: boolean): void {
let moduleName = node.moduleName;
if (moduleName || (emitRelativePathAsModuleName && (moduleName = getResolvedExternalModuleName(host, node)))) {
write(`"${moduleName}", `);
}
}
function emitSystemModule(node: SourceFile, emitRelativePathAsModuleName?: boolean): void {
collectExternalModuleInfo(node);
// System modules has the following shape
// System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
@@ -7264,16 +7348,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
exportFunctionForFile = makeUniqueName("exports");
writeLine();
write("System.register(");
if (node.moduleName) {
write(`"${node.moduleName}", `);
}
writeModuleName(node, emitRelativePathAsModuleName);
write("[");
const groupIndices: Map<number> = {};
const dependencyGroups: DependencyGroup[] = [];
for (let i = 0; i < externalImports.length; ++i) {
const text = getExternalModuleNameText(externalImports[i]);
let text = getExternalModuleNameText(externalImports[i]);
if (hasProperty(groupIndices, text)) {
// deduplicate/group entries in dependency list by the dependency name
const groupIndex = groupIndices[text];
@@ -7289,6 +7371,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(", ");
}
if (emitRelativePathAsModuleName) {
const name = getExternalModuleNameFromDeclaration(host, resolver, externalImports[i]);
if (name) {
text = `"${name}"`;
}
}
write(text);
}
write(`], function(${exportFunctionForFile}) {`);
@@ -7309,7 +7397,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
importAliasNames: string[];
}
function getAMDDependencyNames(node: SourceFile, includeNonAmdDependencies: boolean): AMDDependencyNames {
function getAMDDependencyNames(node: SourceFile, includeNonAmdDependencies: boolean, emitRelativePathAsModuleName?: boolean): AMDDependencyNames {
// names of modules with corresponding parameter in the factory function
const aliasedModuleNames: string[] = [];
// names of modules with no corresponding parameters in factory function
@@ -7331,7 +7419,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
for (const importNode of externalImports) {
// Find the name of the external module
const externalModuleName = getExternalModuleNameText(importNode);
let externalModuleName = getExternalModuleNameText(importNode);
if (emitRelativePathAsModuleName) {
const name = getExternalModuleNameFromDeclaration(host, resolver, importNode);
if (name) {
externalModuleName = `"${name}"`;
}
}
// Find the name of the module alias, if there is one
const importAliasName = getLocalNameForExternalImport(importNode);
@@ -7347,7 +7442,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return { aliasedModuleNames, unaliasedModuleNames, importAliasNames };
}
function emitAMDDependencies(node: SourceFile, includeNonAmdDependencies: boolean) {
function emitAMDDependencies(node: SourceFile, includeNonAmdDependencies: boolean, emitRelativePathAsModuleName?: boolean) {
// An AMD define function has the following shape:
// define(id?, dependencies?, factory);
//
@@ -7360,7 +7455,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// `import "module"` or `<amd-dependency path= "a.css" />`
// we need to add modules without alias names to the end of the dependencies list
const dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies);
const dependencyNames = getAMDDependencyNames(node, includeNonAmdDependencies, emitRelativePathAsModuleName);
emitAMDDependencyList(dependencyNames);
write(", ");
emitAMDFactoryHeader(dependencyNames);
@@ -7388,16 +7483,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(") {");
}
function emitAMDModule(node: SourceFile) {
function emitAMDModule(node: SourceFile, emitRelativePathAsModuleName?: boolean) {
emitEmitHelpers(node);
collectExternalModuleInfo(node);
writeLine();
write("define(");
if (node.moduleName) {
write("\"" + node.moduleName + "\", ");
}
emitAMDDependencies(node, /*includeNonAmdDependencies*/ true);
writeModuleName(node, emitRelativePathAsModuleName);
emitAMDDependencies(node, /*includeNonAmdDependencies*/ true, emitRelativePathAsModuleName);
increaseIndent();
const startIndex = emitDirectivePrologues(node.statements, /*startWithNewLine*/ true);
emitExportStarHelper();
@@ -7646,8 +7739,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitDetachedCommentsAndUpdateCommentsInfo(node);
if (isExternalModule(node) || compilerOptions.isolatedModules) {
const emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ModuleKind.CommonJS];
emitModule(node);
if (root || (!isExternalModule(node) && compilerOptions.isolatedModules)) {
const emitModule = moduleEmitDelegates[modulekind] || moduleEmitDelegates[ModuleKind.CommonJS];
emitModule(node);
}
else {
bundleEmitDelegates[modulekind](node, /*emitRelativePathAsModuleName*/true);
}
}
else {
// emit prologue directives prior to __extends
@@ -7927,7 +8025,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function getLeadingCommentsWithoutDetachedComments() {
// get the leading comments from detachedPos
const leadingComments = getLeadingCommentRanges(currentSourceFile.text,
const leadingComments = getLeadingCommentRanges(currentText,
lastOrUndefined(detachedCommentsInfo).detachedCommentEndPos);
if (detachedCommentsInfo.length - 1) {
detachedCommentsInfo.pop();
@@ -7947,10 +8045,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function isTripleSlashComment(comment: CommentRange) {
// Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
// so that we don't end up computing comment string and doing match for all // comments
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.slash &&
if (currentText.charCodeAt(comment.pos + 1) === CharacterCodes.slash &&
comment.pos + 2 < comment.end &&
currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.slash) {
const textSubStr = currentSourceFile.text.substring(comment.pos, comment.end);
currentText.charCodeAt(comment.pos + 2) === CharacterCodes.slash) {
const textSubStr = currentText.substring(comment.pos, comment.end);
return textSubStr.match(fullTripleSlashReferencePathRegEx) ||
textSubStr.match(fullTripleSlashAMDReferencePathRegEx) ?
true : false;
@@ -7968,7 +8066,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else {
// get the leading comments from the node
return getLeadingCommentRangesOfNode(node, currentSourceFile);
return getLeadingCommentRangesOfNodeFromText(node, currentText);
}
}
}
@@ -7978,7 +8076,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// Emit the trailing comments only if the parent's pos doesn't match because parent should take care of emitting these comments
if (node.parent) {
if (node.parent.kind === SyntaxKind.SourceFile || node.end !== node.parent.end) {
return getTrailingCommentRanges(currentSourceFile.text, node.end);
return getTrailingCommentRanges(currentText, node.end);
}
}
}
@@ -8017,10 +8115,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
emitNewLineBeforeLeadingComments(currentLineMap, writer, node, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator:*/ true, newLine, writeComment);
}
function emitTrailingComments(node: Node) {
@@ -8032,7 +8130,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
const trailingComments = getTrailingCommentsToEmit(node);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
}
/**
@@ -8045,10 +8143,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return;
}
const trailingComments = getTrailingCommentRanges(currentSourceFile.text, pos);
const trailingComments = getTrailingCommentRanges(currentText, pos);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
emitComments(currentText, currentLineMap, writer, trailingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitLeadingCommentsOfPositionWorker(pos: number) {
@@ -8063,17 +8161,17 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
else {
// get the leading comments from the node
leadingComments = getLeadingCommentRanges(currentSourceFile.text, pos);
leadingComments = getLeadingCommentRanges(currentText, pos);
}
emitNewLineBeforeLeadingComments(currentSourceFile, writer, { pos: pos, end: pos }, leadingComments);
emitNewLineBeforeLeadingComments(currentLineMap, writer, { pos: pos, end: pos }, leadingComments);
// Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
emitComments(currentSourceFile, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
emitComments(currentText, currentLineMap, writer, leadingComments, /*trailingSeparator*/ true, newLine, writeComment);
}
function emitDetachedCommentsAndUpdateCommentsInfo(node: TextRange) {
const currentDetachedCommentInfo = emitDetachedComments(currentSourceFile, writer, writeComment, node, newLine, compilerOptions.removeComments);
const currentDetachedCommentInfo = emitDetachedComments(currentText, currentLineMap, writer, writeComment, node, newLine, compilerOptions.removeComments);
if (currentDetachedCommentInfo) {
if (detachedCommentsInfo) {
@@ -8086,7 +8184,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function emitShebang() {
const shebang = getShebang(currentSourceFile.text);
const shebang = getShebang(currentText);
if (shebang) {
write(shebang);
}

View File

@@ -2,15 +2,18 @@
/// <reference path="scanner.ts"/>
namespace ts {
const nodeConstructors = new Array<new (pos: number, end: number) => Node>(SyntaxKind.Count);
/* @internal */ export let parseTime = 0;
export function getNodeConstructor(kind: SyntaxKind): new (pos?: number, end?: number) => Node {
return nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind));
}
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
export function createNode(kind: SyntaxKind, pos?: number, end?: number): Node {
return new (getNodeConstructor(kind))(pos, end);
if (kind === SyntaxKind.SourceFile) {
return new (SourceFileConstructor || (SourceFileConstructor = objectAllocator.getSourceFileConstructor()))(kind, pos, end);
}
else {
return new (NodeConstructor || (NodeConstructor = objectAllocator.getNodeConstructor()))(kind, pos, end);
}
}
function visitNode<T>(cbNode: (node: Node) => T, node: Node): T {
@@ -437,6 +440,10 @@ namespace ts {
const scanner = createScanner(ScriptTarget.Latest, /*skipTrivia*/ true);
const disallowInAndDecoratorContext = ParserContextFlags.DisallowIn | ParserContextFlags.Decorator;
// capture constructors in 'initializeState' to avoid null checks
let NodeConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let SourceFileConstructor: new (kind: SyntaxKind, pos: number, end: number) => Node;
let sourceFile: SourceFile;
let parseDiagnostics: Diagnostic[];
let syntaxCursor: IncrementalParser.SyntaxCursor;
@@ -538,6 +545,9 @@ namespace ts {
}
function initializeState(fileName: string, _sourceText: string, languageVersion: ScriptTarget, isJavaScriptFile: boolean, _syntaxCursor: IncrementalParser.SyntaxCursor) {
NodeConstructor = objectAllocator.getNodeConstructor();
SourceFileConstructor = objectAllocator.getSourceFileConstructor();
sourceText = _sourceText;
syntaxCursor = _syntaxCursor;
@@ -662,10 +672,11 @@ namespace ts {
}
function createSourceFile(fileName: string, languageVersion: ScriptTarget): SourceFile {
const sourceFile = <SourceFile>createNode(SyntaxKind.SourceFile, /*pos*/ 0);
// code from createNode is inlined here so createNode won't have to deal with special case of creating source files
// this is quite rare comparing to other nodes and createNode should be as fast as possible
const sourceFile = <SourceFile>new SourceFileConstructor(SyntaxKind.SourceFile, /*pos*/ 0, /* end */ sourceText.length);
nodeCount++;
sourceFile.pos = 0;
sourceFile.end = sourceText.length;
sourceFile.text = sourceText;
sourceFile.bindDiagnostics = [];
sourceFile.languageVersion = languageVersion;
@@ -676,7 +687,7 @@ namespace ts {
return sourceFile;
}
function setContextFlag(val: Boolean, flag: ParserContextFlags) {
function setContextFlag(val: boolean, flag: ParserContextFlags) {
if (val) {
contextFlags |= flag;
}
@@ -996,12 +1007,14 @@ namespace ts {
}
}
// note: this function creates only node
function createNode(kind: SyntaxKind, pos?: number): Node {
nodeCount++;
if (!(pos >= 0)) {
pos = scanner.getStartPos();
}
return new (nodeConstructors[kind] || (nodeConstructors[kind] = objectAllocator.getNodeConstructor(kind)))(pos, pos);
return new NodeConstructor(kind, pos, pos);
}
function finishNode<T extends Node>(node: T, end?: number): T {

View File

@@ -939,6 +939,10 @@ namespace ts {
}
});
if (!commonPathComponents) { // Can happen when all input files are .d.ts files
return currentDirectory;
}
return getNormalizedPathFromPathComponents(commonPathComponents);
}
@@ -1040,12 +1044,16 @@ namespace ts {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Cannot_compile_modules_into_es2015_when_targeting_ES5_or_lower));
}
// Cannot specify module gen that isn't amd or system with --out
if (outFile && options.module && !(options.module === ModuleKind.AMD || options.module === ModuleKind.System)) {
programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile"));
}
// there has to be common source directory if user specified --outdir || --sourceRoot
// if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
if (options.outDir || // there is --outDir specified
options.sourceRoot || // there is --sourceRoot specified
(options.mapRoot && // there is --mapRoot specified and there would be multiple js files generated
(!outFile || firstExternalModuleSourceFile !== undefined))) {
options.mapRoot) { // there is --mapRoot specified
if (options.rootDir && checkSourceFilesBelongToPath(files, options.rootDir)) {
// If a rootDir is specified and is valid use it as the commonSourceDirectory

View File

@@ -580,7 +580,7 @@ namespace ts {
function getCommentRanges(text: string, pos: number, trailing: boolean): CommentRange[] {
let result: CommentRange[];
let collecting = trailing || pos === 0;
while (true) {
while (pos < text.length) {
const ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
@@ -650,6 +650,8 @@ namespace ts {
}
return result;
}
return result;
}
export function getLeadingCommentRanges(text: string, pos: number): CommentRange[] {
@@ -741,7 +743,7 @@ namespace ts {
}
}
function scanNumber(): number {
function scanNumber(): string {
const start = pos;
while (isDigit(text.charCodeAt(pos))) pos++;
if (text.charCodeAt(pos) === CharacterCodes.dot) {
@@ -761,7 +763,7 @@ namespace ts {
error(Diagnostics.Digit_expected);
}
}
return +(text.substring(start, end));
return "" + +(text.substring(start, end));
}
function scanOctalDigits(): number {
@@ -1229,7 +1231,7 @@ namespace ts {
return pos++, token = SyntaxKind.MinusToken;
case CharacterCodes.dot:
if (isDigit(text.charCodeAt(pos + 1))) {
tokenValue = "" + scanNumber();
tokenValue = scanNumber();
return token = SyntaxKind.NumericLiteral;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.dot && text.charCodeAt(pos + 2) === CharacterCodes.dot) {
@@ -1343,7 +1345,7 @@ namespace ts {
case CharacterCodes._7:
case CharacterCodes._8:
case CharacterCodes._9:
tokenValue = "" + scanNumber();
tokenValue = scanNumber();
return token = SyntaxKind.NumericLiteral;
case CharacterCodes.colon:
return pos++, token = SyntaxKind.ColonToken;

View File

@@ -1625,6 +1625,7 @@ namespace ts {
getTypeReferenceSerializationKind(typeName: EntityName): TypeReferenceSerializationKind;
isOptionalParameter(node: ParameterDeclaration): boolean;
isArgumentsLocalBinding(node: Identifier): boolean;
getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): SourceFile;
}
export const enum SymbolFlags {
@@ -1959,6 +1960,8 @@ namespace ts {
target?: TypeParameter; // Instantiation target
/* @internal */
mapper?: TypeMapper; // Instantiation mapper
/* @internal */
resolvedApparentType: Type;
}
export const enum SignatureKind {

View File

@@ -424,18 +424,26 @@ namespace ts {
return getLeadingCommentRanges(sourceFileOfNode.text, node.pos);
}
export function getLeadingCommentRangesOfNodeFromText(node: Node, text: string) {
return getLeadingCommentRanges(text, node.pos);
}
export function getJsDocComments(node: Node, sourceFileOfNode: SourceFile) {
return getJsDocCommentsFromText(node, sourceFileOfNode.text);
}
export function getJsDocCommentsFromText(node: Node, text: string) {
const commentRanges = (node.kind === SyntaxKind.Parameter || node.kind === SyntaxKind.TypeParameter) ?
concatenate(getTrailingCommentRanges(sourceFileOfNode.text, node.pos),
getLeadingCommentRanges(sourceFileOfNode.text, node.pos)) :
getLeadingCommentRangesOfNode(node, sourceFileOfNode);
concatenate(getTrailingCommentRanges(text, node.pos),
getLeadingCommentRanges(text, node.pos)) :
getLeadingCommentRangesOfNodeFromText(node, text);
return filter(commentRanges, isJsDocComment);
function isJsDocComment(comment: CommentRange) {
// True if the comment starts with '/**' but not if it is '/**/'
return sourceFileOfNode.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk &&
sourceFileOfNode.text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash;
return text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
text.charCodeAt(comment.pos + 2) === CharacterCodes.asterisk &&
text.charCodeAt(comment.pos + 3) !== CharacterCodes.slash;
}
}
@@ -1437,8 +1445,8 @@ namespace ts {
export function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult {
const simpleReferenceRegEx = /^\/\/\/\s*<reference\s+/gim;
const isNoDefaultLibRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/gim;
if (simpleReferenceRegEx.exec(comment)) {
if (isNoDefaultLibRegEx.exec(comment)) {
if (simpleReferenceRegEx.test(comment)) {
if (isNoDefaultLibRegEx.test(comment)) {
return {
isNoDefaultLib: true
};
@@ -1706,6 +1714,7 @@ namespace ts {
"\u0085": "\\u0085" // nextLine
};
/**
* Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
* but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
@@ -1743,7 +1752,7 @@ namespace ts {
export interface EmitTextWriter {
write(s: string): void;
writeTextOfNode(sourceFile: SourceFile, node: Node): void;
writeTextOfNode(text: string, node: Node): void;
writeLine(): void;
increaseIndent(): void;
decreaseIndent(): void;
@@ -1754,6 +1763,7 @@ namespace ts {
getLine(): number;
getColumn(): number;
getIndent(): number;
reset(): void;
}
const indentStrings: string[] = ["", " "];
@@ -1769,11 +1779,11 @@ namespace ts {
}
export function createTextWriter(newLine: String): EmitTextWriter {
let output = "";
let indent = 0;
let lineStart = true;
let lineCount = 0;
let linePos = 0;
let output: string;
let indent: number;
let lineStart: boolean;
let lineCount: number;
let linePos: number;
function write(s: string) {
if (s && s.length) {
@@ -1785,6 +1795,14 @@ namespace ts {
}
}
function reset(): void {
output = "";
indent = 0;
lineStart = true;
lineCount = 0;
linePos = 0;
}
function rawWrite(s: string) {
if (s !== undefined) {
if (lineStart) {
@@ -1814,10 +1832,12 @@ namespace ts {
}
}
function writeTextOfNode(sourceFile: SourceFile, node: Node) {
write(getSourceTextOfNodeFromSourceFile(sourceFile, node));
function writeTextOfNode(text: string, node: Node) {
write(getTextOfNodeFromSourceText(text, node));
}
reset();
return {
write,
rawWrite,
@@ -1831,9 +1851,19 @@ namespace ts {
getLine: () => lineCount + 1,
getColumn: () => lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1,
getText: () => output,
reset
};
}
/**
* Resolves a local path to a path which is absolute to the base of the emit
*/
export function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string {
const dir = host.getCurrentDirectory();
const relativePath = getRelativePathToDirectoryOrUrl(dir, fileName, dir, f => host.getCanonicalFileName(f), /*isAbsolutePathAnUrl*/ false);
return removeFileExtension(relativePath);
}
export function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string) {
const compilerOptions = host.getCompilerOptions();
let emitOutputFilePathWithoutExtension: string;
@@ -1863,6 +1893,10 @@ namespace ts {
return getLineAndCharacterOfPosition(currentSourceFile, pos).line;
}
export function getLineOfLocalPositionFromLineMap(lineMap: number[], pos: number) {
return computeLineAndCharacterOfPosition(lineMap, pos).line;
}
export function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration {
return forEach(node.members, member => {
if (member.kind === SyntaxKind.Constructor && nodeIsPresent((<ConstructorDeclaration>member).body)) {
@@ -1937,23 +1971,23 @@ namespace ts {
};
}
export function emitNewLineBeforeLeadingComments(currentSourceFile: SourceFile, writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]) {
export function emitNewLineBeforeLeadingComments(lineMap: number[], writer: EmitTextWriter, node: TextRange, leadingComments: CommentRange[]) {
// If the leading comments start on different line than the start of node, write new line
if (leadingComments && leadingComments.length && node.pos !== leadingComments[0].pos &&
getLineOfLocalPosition(currentSourceFile, node.pos) !== getLineOfLocalPosition(currentSourceFile, leadingComments[0].pos)) {
getLineOfLocalPositionFromLineMap(lineMap, node.pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
writer.writeLine();
}
}
export function emitComments(currentSourceFile: SourceFile, writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string,
writeComment: (currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) => void) {
export function emitComments(text: string, lineMap: number[], writer: EmitTextWriter, comments: CommentRange[], trailingSeparator: boolean, newLine: string,
writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) => void) {
let emitLeadingSpace = !trailingSeparator;
forEach(comments, comment => {
if (emitLeadingSpace) {
writer.write(" ");
emitLeadingSpace = false;
}
writeComment(currentSourceFile, writer, comment, newLine);
writeComment(text, lineMap, writer, comment, newLine);
if (comment.hasTrailingNewLine) {
writer.writeLine();
}
@@ -1971,8 +2005,8 @@ namespace ts {
* Detached comment is a comment at the top of file or function body that is separated from
* the next statement by space.
*/
export function emitDetachedComments(currentSourceFile: SourceFile, writer: EmitTextWriter,
writeComment: (currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) => void,
export function emitDetachedComments(text: string, lineMap: number[], writer: EmitTextWriter,
writeComment: (text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) => void,
node: TextRange, newLine: string, removeComments: boolean) {
let leadingComments: CommentRange[];
let currentDetachedCommentInfo: {nodePos: number, detachedCommentEndPos: number};
@@ -1983,12 +2017,12 @@ namespace ts {
//
// var x = 10;
if (node.pos === 0) {
leadingComments = filter(getLeadingCommentRanges(currentSourceFile.text, node.pos), isPinnedComment);
leadingComments = filter(getLeadingCommentRanges(text, node.pos), isPinnedComment);
}
}
else {
// removeComments is false, just get detached as normal and bypass the process to filter comment
leadingComments = getLeadingCommentRanges(currentSourceFile.text, node.pos);
leadingComments = getLeadingCommentRanges(text, node.pos);
}
if (leadingComments) {
@@ -1997,8 +2031,8 @@ namespace ts {
for (const comment of leadingComments) {
if (lastComment) {
const lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastComment.end);
const commentLine = getLineOfLocalPosition(currentSourceFile, comment.pos);
const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
const commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
if (commentLine >= lastCommentLine + 2) {
// There was a blank line between the last comment and this comment. This
@@ -2016,12 +2050,12 @@ namespace ts {
// All comments look like they could have been part of the copyright header. Make
// sure there is at least one blank line between it and the node. If not, it's not
// a copyright header.
const lastCommentLine = getLineOfLocalPosition(currentSourceFile, lastOrUndefined(detachedComments).end);
const nodeLine = getLineOfLocalPosition(currentSourceFile, skipTrivia(currentSourceFile.text, node.pos));
const lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastOrUndefined(detachedComments).end);
const nodeLine = getLineOfLocalPositionFromLineMap(lineMap, skipTrivia(text, node.pos));
if (nodeLine >= lastCommentLine + 2) {
// Valid detachedComments
emitNewLineBeforeLeadingComments(currentSourceFile, writer, node, leadingComments);
emitComments(currentSourceFile, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);
emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
emitComments(text, lineMap, writer, detachedComments, /*trailingSeparator*/ true, newLine, writeComment);
currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: lastOrUndefined(detachedComments).end };
}
}
@@ -2030,25 +2064,26 @@ namespace ts {
return currentDetachedCommentInfo;
function isPinnedComment(comment: CommentRange) {
return currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
currentSourceFile.text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation;
return text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk &&
text.charCodeAt(comment.pos + 2) === CharacterCodes.exclamation;
}
}
export function writeCommentRange(currentSourceFile: SourceFile, writer: EmitTextWriter, comment: CommentRange, newLine: string) {
if (currentSourceFile.text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
const firstCommentLineAndCharacter = getLineAndCharacterOfPosition(currentSourceFile, comment.pos);
const lineCount = getLineStarts(currentSourceFile).length;
export function writeCommentRange(text: string, lineMap: number[], writer: EmitTextWriter, comment: CommentRange, newLine: string) {
if (text.charCodeAt(comment.pos + 1) === CharacterCodes.asterisk) {
const firstCommentLineAndCharacter = computeLineAndCharacterOfPosition(lineMap, comment.pos);
const lineCount = lineMap.length;
let firstCommentLineIndent: number;
for (let pos = comment.pos, currentLine = firstCommentLineAndCharacter.line; pos < comment.end; currentLine++) {
const nextLineStart = (currentLine + 1) === lineCount
? currentSourceFile.text.length + 1
: getStartPositionOfLine(currentLine + 1, currentSourceFile);
? text.length + 1
: lineMap[currentLine + 1];
if (pos !== comment.pos) {
// If we are not emitting first line, we need to write the spaces to adjust the alignment
if (firstCommentLineIndent === undefined) {
firstCommentLineIndent = calculateIndent(getStartPositionOfLine(firstCommentLineAndCharacter.line, currentSourceFile), comment.pos);
firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], comment.pos);
}
// These are number of spaces writer is going to write at current indent
@@ -2068,7 +2103,7 @@ namespace ts {
// More right indented comment */ --4 = 8 - 4 + 11
// class c { }
// }
const spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(pos, nextLineStart);
const spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
if (spacesToEmit > 0) {
let numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
const indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
@@ -2089,47 +2124,47 @@ namespace ts {
}
// Write the comment line text
writeTrimmedCurrentLine(pos, nextLineStart);
writeTrimmedCurrentLine(text, comment, writer, newLine, pos, nextLineStart);
pos = nextLineStart;
}
}
else {
// Single line comment of style //....
writer.write(currentSourceFile.text.substring(comment.pos, comment.end));
writer.write(text.substring(comment.pos, comment.end));
}
}
function writeTrimmedCurrentLine(pos: number, nextLineStart: number) {
const end = Math.min(comment.end, nextLineStart - 1);
const currentLineText = currentSourceFile.text.substring(pos, end).replace(/^\s+|\s+$/g, "");
if (currentLineText) {
// trimmed forward and ending spaces text
writer.write(currentLineText);
if (end !== comment.end) {
writer.writeLine();
}
function writeTrimmedCurrentLine(text: string, comment: CommentRange, writer: EmitTextWriter, newLine: string, pos: number, nextLineStart: number) {
const end = Math.min(comment.end, nextLineStart - 1);
const currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
if (currentLineText) {
// trimmed forward and ending spaces text
writer.write(currentLineText);
if (end !== comment.end) {
writer.writeLine();
}
}
else {
// Empty string - make sure we write empty line
writer.writeLiteral(newLine);
}
}
function calculateIndent(text: string, pos: number, end: number) {
let currentLineIndent = 0;
for (; pos < end && isWhiteSpace(text.charCodeAt(pos)); pos++) {
if (text.charCodeAt(pos) === CharacterCodes.tab) {
// Tabs = TabSize = indent size and go to next tabStop
currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
}
else {
// Empty string - make sure we write empty line
writer.writeLiteral(newLine);
// Single space
currentLineIndent++;
}
}
function calculateIndent(pos: number, end: number) {
let currentLineIndent = 0;
for (; pos < end && isWhiteSpace(currentSourceFile.text.charCodeAt(pos)); pos++) {
if (currentSourceFile.text.charCodeAt(pos) === CharacterCodes.tab) {
// Tabs = TabSize = indent size and go to next tabStop
currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
}
else {
// Single space
currentLineIndent++;
}
}
return currentLineIndent;
}
return currentLineIndent;
}
export function modifierToFlag(token: SyntaxKind): NodeFlags {