Merge branch 'master' into emitArrowFunctionES6

This commit is contained in:
Yui T committed 2015-01-29 15:37:45 -08:00
commit e4b206c4a2
140 files changed
+1699 -5155

No files matched your search

+61 -18
View File
@@ -3408,9 +3408,9 @@ module ts {
// TYPE CHECKING
var subtypeRelation: Map<boolean> = {};
var assignableRelation: Map<boolean> = {};
var identityRelation: Map<boolean> = {};
var subtypeRelation: Map<RelationComparisonResult> = {};
var assignableRelation: Map<RelationComparisonResult> = {};
var identityRelation: Map<RelationComparisonResult> = {};
function isTypeIdenticalTo(source: Type, target: Type): boolean {
return checkTypeRelatedTo(source, target, identityRelation, /*errorNode*/ undefined);
@@ -3445,7 +3445,7 @@ module ts {
function checkTypeRelatedTo(
source: Type,
target: Type,
relation: Map<boolean>,
relation: Map<RelationComparisonResult>,
errorNode: Node,
headMessage?: DiagnosticMessage,
containingMessageChain?: DiagnosticMessageChain): boolean {
@@ -3453,7 +3453,7 @@ module ts {
var errorInfo: DiagnosticMessageChain;
var sourceStack: ObjectType[];
var targetStack: ObjectType[];
var maybeStack: Map<boolean>[];
var maybeStack: Map<RelationComparisonResult>[];
var expandingFlags: number;
var depth = 0;
var overflow = false;
@@ -3465,6 +3465,14 @@ module ts {
error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
}
else if (errorInfo) {
// If we already computed this relation, but in a context where we didn't want to report errors (e.g. overload resolution),
// then we'll only have a top-level error (e.g. 'Class X does not implement interface Y') without any details. If this happened,
// request a recompuation to get a complete error message. This will be skipped if we've already done this computation in a context
// where errors were being reported.
if (errorInfo.next === undefined) {
errorInfo = undefined;
isRelatedTo(source, target, errorNode !== undefined, headMessage, /* elaborateErrors */ true);
}
if (containingMessageChain) {
errorInfo = concatenateDiagnosticMessageChains(containingMessageChain, errorInfo);
}
@@ -3480,7 +3488,7 @@ module ts {
// Ternary.True if they are related with no assumptions,
// Ternary.Maybe if they are related with assumptions of other relationships, or
// Ternary.False if they are not related.
function isRelatedTo(source: Type, target: Type, reportErrors?: boolean, headMessage?: DiagnosticMessage): Ternary {
function isRelatedTo(source: Type, target: Type, reportErrors?: boolean, headMessage?: DiagnosticMessage, elaborateErrors = false): Ternary {
var result: Ternary;
// both types are the same - covers 'they are the same primitive type or both are Any' or the same type parameter cases
if (source === target) return Ternary.True;
@@ -3547,7 +3555,7 @@ module ts {
// identity relation does not use apparent type
var sourceOrApparentType = relation === identityRelation ? source : getApparentType(source);
if (sourceOrApparentType.flags & TypeFlags.ObjectType && target.flags & TypeFlags.ObjectType &&
(result = objectTypeRelatedTo(sourceOrApparentType, <ObjectType>target, reportStructuralErrors))) {
(result = objectTypeRelatedTo(sourceOrApparentType, <ObjectType>target, reportStructuralErrors, elaborateErrors))) {
errorInfo = saveErrorInfo;
return result;
}
@@ -3638,14 +3646,19 @@ module ts {
// Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
// equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
// and issue an error. Otherwise, actually compare the structure of the two types.
function objectTypeRelatedTo(source: ObjectType, target: ObjectType, reportErrors: boolean): Ternary {
function objectTypeRelatedTo(source: ObjectType, target: ObjectType, reportErrors: boolean, elaborateErrors = false): Ternary {
if (overflow) {
return Ternary.False;
}
var id = relation !== identityRelation || source.id < target.id ? source.id + "," + target.id : target.id + "," + source.id;
var related = relation[id];
//var related: RelationComparisonResult = undefined; // relation[id];
if (related !== undefined) {
return related ? Ternary.True : Ternary.False;
// If we computed this relation already and it was failed and reported, or if we're not being asked to elaborate
// errors, we can use the cached value. Otherwise, recompute the relation
if (!elaborateErrors || (related === RelationComparisonResult.FailedAndReported)) {
return related === RelationComparisonResult.Succeeded ? Ternary.True : Ternary.False;
}
}
if (depth > 0) {
for (var i = 0; i < depth; i++) {
@@ -3668,7 +3681,7 @@ module ts {
sourceStack[depth] = source;
targetStack[depth] = target;
maybeStack[depth] = {};
maybeStack[depth][id] = true;
maybeStack[depth][id] = RelationComparisonResult.Succeeded;
depth++;
var saveExpandingFlags = expandingFlags;
if (!(expandingFlags & 1) && isDeeplyNestedGeneric(source, sourceStack)) expandingFlags |= 1;
@@ -3696,13 +3709,13 @@ module ts {
if (result) {
var maybeCache = maybeStack[depth];
// If result is definitely true, copy assumptions to global cache, else copy to next level up
var destinationCache = result === Ternary.True || depth === 0 ? relation : maybeStack[depth - 1];
copyMap(/*source*/maybeCache, /*target*/destinationCache);
var destinationCache = (result === Ternary.True || depth === 0) ? relation : maybeStack[depth - 1];
copyMap(maybeCache, destinationCache);
}
else {
// A false result goes straight into global cache (when something is false under assumptions it
// will also be false without assumptions)
relation[id] = false;
relation[id] = reportErrors ? RelationComparisonResult.FailedAndReported : RelationComparisonResult.Failed;
}
return result;
}
@@ -5966,7 +5979,7 @@ module ts {
return typeArgumentsAreAssignable;
}
function checkApplicableSignature(node: CallLikeExpression, args: Node[], signature: Signature, relation: Map<boolean>, excludeArgument: boolean[], reportErrors: boolean) {
function checkApplicableSignature(node: CallLikeExpression, args: Node[], signature: Signature, relation: Map<RelationComparisonResult>, excludeArgument: boolean[], reportErrors: boolean) {
for (var i = 0; i < args.length; i++) {
var arg = args[i];
var argType: Type;
@@ -6026,11 +6039,41 @@ module ts {
return args;
}
/**
* In a 'super' call, type arguments are not provided within the CallExpression node itself.
* Instead, they must be fetched from the class declaration's base type node.
*
* If 'node' is a 'super' call (e.g. super(...), new super(...)), then we attempt to fetch
* the type arguments off the containing class's first heritage clause (if one exists). Note that if
* type arguments are supplied on the 'super' call, they are ignored (though this is syntactically incorrect).
*
* In all other cases, the call's explicit type arguments are returned.
*/
function getEffectiveTypeArguments(callExpression: CallExpression): TypeNode[] {
if (callExpression.expression.kind === SyntaxKind.SuperKeyword) {
var containingClass = <ClassDeclaration>getAncestor(callExpression, SyntaxKind.ClassDeclaration);
var baseClassTypeNode = containingClass && getClassBaseTypeNode(containingClass);
return baseClassTypeNode && baseClassTypeNode.typeArguments;
}
else {
// Ordinary case - simple function invocation.
return callExpression.typeArguments;
}
}
function resolveCall(node: CallLikeExpression, signatures: Signature[], candidatesOutArray: Signature[]): Signature {
var isTaggedTemplate = node.kind === SyntaxKind.TaggedTemplateExpression;
var typeArguments = isTaggedTemplate ? undefined : (<CallExpression>node).typeArguments;
forEach(typeArguments, checkSourceElement);
var typeArguments: TypeNode[];
if (!isTaggedTemplate) {
typeArguments = getEffectiveTypeArguments(<CallExpression>node);
// We already perform checking on the type arguments on the class declaration itself.
if ((<CallExpression>node).expression.kind !== SyntaxKind.SuperKeyword) {
forEach(typeArguments, checkSourceElement);
}
}
var candidates = candidatesOutArray || [];
// collectCandidates fills up the candidates array directly
@@ -6160,7 +6203,7 @@ module ts {
return resolveErrorCall(node);
function chooseOverload(candidates: Signature[], relation: Map<boolean>) {
function chooseOverload(candidates: Signature[], relation: Map<RelationComparisonResult>) {
for (var i = 0; i < candidates.length; i++) {
if (!hasCorrectArity(node, args, candidates[i])) {
continue;
@@ -6296,7 +6339,7 @@ module ts {
// Another error has already been reported
return resolveErrorCall(node);
}
// Technically, this signatures list may be incomplete. We are taking the apparent type,
// but we are not including call signatures that may have been added to the Object or
// Function interface, since they have none by default. This is a bit of a leap of faith
+99 -73
View File
@@ -2427,28 +2427,20 @@ module ts {
}
function emitMethod(node: MethodDeclaration) {
if (!isObjectLiteralMethod(node)) {
return;
}
emitLeadingComments(node);
emit(node.name);
if (languageVersion < ScriptTarget.ES6) {
write(": function ");
}
emitSignatureAndBody(node);
emitTrailingComments(node);
}
function emitPropertyAssignment(node: PropertyDeclaration) {
emitLeadingComments(node);
emit(node.name);
write(": ");
emit(node.initializer);
emitTrailingComments(node);
}
function emitShorthandPropertyAssignment(node: ShorthandPropertyAssignment) {
emitLeadingComments(node);
emit(node.name);
// If short-hand property has a prefix, then regardless of the target version, we will emit it as normal property assignment. For example:
// module m {
@@ -2465,7 +2457,6 @@ module ts {
// Short-hand, { x }, is equivalent of normal form { x: x }
emitExpressionIdentifier(node.name);
}
emitTrailingComments(node);
}
function tryEmitConstantValue(node: PropertyAccessExpression | ElementAccessExpression): boolean {
@@ -2685,14 +2676,11 @@ module ts {
}
function emitExpressionStatement(node: ExpressionStatement) {
emitLeadingComments(node);
emitParenthesized(node.expression, /*parenthesized*/ node.expression.kind === SyntaxKind.ArrowFunction);
write(";");
emitTrailingComments(node);
}
function emitIfStatement(node: IfStatement) {
emitLeadingComments(node);
var endPos = emitToken(SyntaxKind.IfKeyword, node.pos);
write(" ");
endPos = emitToken(SyntaxKind.OpenParenToken, endPos);
@@ -2710,7 +2698,6 @@ module ts {
emitEmbeddedStatement(node.elseStatement);
}
}
emitTrailingComments(node);
}
function emitDoStatement(node: DoStatement) {
@@ -2798,11 +2785,9 @@ module ts {
}
function emitReturnStatement(node: ReturnStatement) {
emitLeadingComments(node);
emitToken(SyntaxKind.ReturnKeyword, node.pos);
emitOptional(" ", node.expression);
write(";");
emitTrailingComments(node);
}
function emitWithStatement(node: WhileStatement) {
@@ -3126,7 +3111,6 @@ module ts {
}
function emitVariableDeclaration(node: VariableDeclaration) {
emitLeadingComments(node);
if (isBindingPattern(node.name)) {
if (languageVersion < ScriptTarget.ES6) {
emitDestructuring(node);
@@ -3140,11 +3124,9 @@ module ts {
emitModuleMemberName(node);
emitOptional(" = ", node.initializer);
}
emitTrailingComments(node);
}
function emitVariableStatement(node: VariableStatement) {
emitLeadingComments(node);
if (!(node.flags & NodeFlags.Export)) {
if (isLet(node.declarationList)) {
write("let ");
@@ -3158,11 +3140,9 @@ module ts {
}
emitCommaList(node.declarationList.declarations);
write(";");
emitTrailingComments(node);
}
function emitParameter(node: ParameterDeclaration) {
emitLeadingComments(node);
if (languageVersion < ScriptTarget.ES6) {
if (isBindingPattern(node.name)) {
var name = createTempVariable(node);
@@ -3183,7 +3163,6 @@ module ts {
emit(node.name);
emitOptional(" = ", node.initializer);
}
emitTrailingComments(node);
}
function emitDefaultValueAssignments(node: FunctionLikeDeclaration) {
@@ -3256,11 +3235,9 @@ module ts {
}
function emitAccessor(node: AccessorDeclaration) {
emitLeadingComments(node);
write(node.kind === SyntaxKind.GetAccessor ? "get " : "set ");
emit(node.name);
emitSignatureAndBody(node);
emitTrailingComments(node);
}
function shouldEmitAsArrowFunction(node: FunctionLikeDeclaration): boolean {
@@ -3364,7 +3341,10 @@ module ts {
write(" ");
emitStart(node.body);
write("return ");
emitNode(node.body);
// Don't emit comments on this body. We'll have already taken care of it above
// when we called emitDetachedComments.
emitNode(node.body, /*disableComments:*/ true);
emitEnd(node.body);
write(";");
emitTempDeclarations(/*newLine*/ false);
@@ -3381,7 +3361,7 @@ module ts {
writeLine();
emitLeadingComments(node.body);
write("return ");
emit(node.body);
emit(node.body, /*disableComments:*/ true);
write(";");
emitTrailingComments(node.body);
}
@@ -3562,7 +3542,6 @@ module ts {
}
function emitClassDeclaration(node: ClassDeclaration) {
emitLeadingComments(node);
write("var ");
emit(node.name);
write(" = (function (");
@@ -3612,7 +3591,6 @@ module ts {
emitEnd(node);
write(";");
}
emitTrailingComments(node);
function emitConstructorOfClass() {
var saveTempCount = tempCount;
@@ -3691,13 +3669,17 @@ module ts {
emitPinnedOrTripleSlashComments(node);
}
function shouldEmitEnumDeclaration(node: EnumDeclaration) {
var isConstEnum = isConst(node);
return !isConstEnum || compilerOptions.preserveConstEnums;
}
function emitEnumDeclaration(node: EnumDeclaration) {
// const enums are completely erased during compilation.
var isConstEnum = isConst(node);
if (isConstEnum && !compilerOptions.preserveConstEnums) {
if (!shouldEmitEnumDeclaration(node)) {
return;
}
emitLeadingComments(node);
if (!(node.flags & NodeFlags.Export)) {
emitStart(node);
write("var ");
@@ -3714,7 +3696,7 @@ module ts {
write(") {");
increaseIndent();
scopeEmitStart(node);
emitEnumMemberDeclarations(isConstEnum);
emitLines(node.members);
decreaseIndent();
writeLine();
emitToken(SyntaxKind.CloseBraceToken, node.members.end);
@@ -3735,32 +3717,27 @@ module ts {
emitEnd(node);
write(";");
}
emitTrailingComments(node);
}
function emitEnumMemberDeclarations(isConstEnum: boolean) {
forEach(node.members, member => {
writeLine();
emitLeadingComments(member);
emitStart(member);
write(resolver.getLocalNameOfContainer(node));
write("[");
write(resolver.getLocalNameOfContainer(node));
write("[");
emitExpressionForPropertyName(member.name);
write("] = ");
if (member.initializer && !isConstEnum) {
emit(member.initializer);
}
else {
write(resolver.getEnumMemberValue(member).toString());
}
write("] = ");
emitExpressionForPropertyName(member.name);
emitEnd(member);
write(";");
emitTrailingComments(member);
});
function emitEnumMember(node: EnumMember) {
var enumParent = <EnumDeclaration>node.parent;
emitStart(node);
write(resolver.getLocalNameOfContainer(enumParent));
write("[");
write(resolver.getLocalNameOfContainer(enumParent));
write("[");
emitExpressionForPropertyName(node.name);
write("] = ");
if (node.initializer && !isConst(enumParent)) {
emit(node.initializer);
}
else {
write(resolver.getEnumMemberValue(node).toString());
}
write("] = ");
emitExpressionForPropertyName(node.name);
emitEnd(node);
write(";");
}
function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration: ModuleDeclaration): ModuleDeclaration {
@@ -3770,14 +3747,18 @@ module ts {
}
}
function shouldEmitModuleDeclaration(node: ModuleDeclaration) {
return isInstantiatedModule(node, compilerOptions.preserveConstEnums);
}
function emitModuleDeclaration(node: ModuleDeclaration) {
// Emit only if this module is non-ambient.
var shouldEmit = isInstantiatedModule(node, compilerOptions.preserveConstEnums);
var shouldEmit = shouldEmitModuleDeclaration(node);
if (!shouldEmit) {
return emitPinnedOrTripleSlashComments(node);
}
emitLeadingComments(node);
emitStart(node);
write("var ");
emit(node.name);
@@ -3822,7 +3803,6 @@ module ts {
emitModuleMemberName(node);
write(" = {}));");
emitEnd(node);
emitTrailingComments(node);
}
function emitImportDeclaration(node: ImportDeclaration) {
@@ -4012,7 +3992,7 @@ module ts {
emitLeadingComments(node.endOfFileToken);
}
function emitNode(node: Node): void {
function emitNode(node: Node, disableComments?:boolean): void {
if (!node) {
return;
}
@@ -4020,6 +4000,46 @@ module ts {
if (node.flags & NodeFlags.Ambient) {
return emitPinnedOrTripleSlashComments(node);
}
var emitComments = !disableComments && shouldEmitLeadingAndTrailingComments(node);
if (emitComments) {
emitLeadingComments(node);
}
emitJavaScriptWorker(node);
if (emitComments) {
emitTrailingComments(node);
}
}
function shouldEmitLeadingAndTrailingComments(node: Node) {
switch (node.kind) {
// All of these entities are emitted in a specialized fashion. As such, we allow
// the specilized methods for each to handle the comments on the nodes.
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ImportDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ExportAssignment:
return false;
case SyntaxKind.ModuleDeclaration:
// Only emit the leading/trailing comments for a module if we're actually
// emitting the module as well.
return shouldEmitModuleDeclaration(<ModuleDeclaration>node);
case SyntaxKind.EnumDeclaration:
// Only emit the leading/trailing comments for an enum if we're actually
// emitting the module as well.
return shouldEmitEnumDeclaration(<EnumDeclaration>node);
}
// Emit comments for everything else.
return true;
}
function emitJavaScriptWorker(node: Node) {
// Check if the node can be emitted regardless of the ScriptTarget
switch (node.kind) {
case SyntaxKind.Identifier:
@@ -4157,6 +4177,8 @@ module ts {
return emitInterfaceDeclaration(<InterfaceDeclaration>node);
case SyntaxKind.EnumDeclaration:
return emitEnumDeclaration(<EnumDeclaration>node);
case SyntaxKind.EnumMember:
return emitEnumMember(<EnumMember>node);
case SyntaxKind.ModuleDeclaration:
return emitModuleDeclaration(<ModuleDeclaration>node);
case SyntaxKind.ImportDeclaration:
@@ -4186,17 +4208,19 @@ module ts {
function getLeadingCommentsToEmit(node: Node) {
// Emit the leading comments only if the parent's pos doesn't match because parent should take care of emitting these comments
if (node.parent.kind === SyntaxKind.SourceFile || node.pos !== node.parent.pos) {
var leadingComments: CommentRange[];
if (hasDetachedComments(node.pos)) {
// get comments without detached comments
leadingComments = getLeadingCommentsWithoutDetachedComments();
if (node.parent) {
if (node.parent.kind === SyntaxKind.SourceFile || node.pos !== node.parent.pos) {
var leadingComments: CommentRange[];
if (hasDetachedComments(node.pos)) {
// get comments without detached comments
leadingComments = getLeadingCommentsWithoutDetachedComments();
}
else {
// get the leading comments from the node
leadingComments = getLeadingCommentRangesOfNode(node, currentSourceFile);
}
return leadingComments;
}
else {
// get the leading comments from the node
leadingComments = getLeadingCommentRangesOfNode(node, currentSourceFile);
}
return leadingComments;
}
}
@@ -4209,10 +4233,12 @@ module ts {
function emitTrailingDeclarationComments(node: Node) {
// Emit the trailing comments only if the parent's end doesn't match
if (node.parent.kind === SyntaxKind.SourceFile || node.end !== node.parent.end) {
var trailingComments = getTrailingCommentRanges(currentSourceFile.text, node.end);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
if (node.parent) {
if (node.parent.kind === SyntaxKind.SourceFile || node.end !== node.parent.end) {
var trailingComments = getTrailingCommentRanges(currentSourceFile.text, node.end);
// trailing comments are emitted at space/*trailing comment1 */space/*trailing comment*/
emitComments(currentSourceFile, writer, trailingComments, /*trailingSeparator*/ false, newLine, writeComment);
}
}
}
+6
View File
@@ -332,6 +332,12 @@ module ts {
HasAggregatedChildData = 1 << 6
}
export const enum RelationComparisonResult {
Succeeded = 1, // Should be truthy
Failed = 2,
FailedAndReported = 3
}
export interface Node extends TextRange {
kind: SyntaxKind;
flags: NodeFlags;
-27
View File
@@ -1,27 +0,0 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='references.ts' />
module TypeScript {
export interface Logger {
log(s: string): void;
}
export class NullLogger implements Logger {
public log(s: string): void {
}
}
}
File diff suppressed because it is too large. Load diff
-266
View File
@@ -1,266 +0,0 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path="references.ts" />
module TypeScript {
export interface IOptions {
name?: string;
flag?: boolean;
short?: string;
usage?: {
locCode: string; // DiagnosticCode
args: string[]
};
set?: (s: string) => void;
type?: string; // DiagnosticCode
experimental?: boolean;
}
export class OptionsParser {
private DEFAULT_SHORT_FLAG = "-";
private DEFAULT_LONG_FLAG = "--";
private printedVersion: boolean = false;
// Find the option record for the given string. Returns null if not found.
private findOption(arg: string) {
var upperCaseArg = arg && arg.toUpperCase();
for (var i = 0; i < this.options.length; i++) {
var current = this.options[i];
if (upperCaseArg === (current.short && current.short.toUpperCase()) ||
upperCaseArg === (current.name && current.name.toUpperCase())) {
return current;
}
}
return null;
}
public unnamed: string[] = [];
public options: IOptions[] = [];
constructor(public host: IEnvironment, public version: string) {
}
public printUsage() {
this.printVersion();
var optionsWord = getLocalizedText(DiagnosticCode.options, null);
var fileWord = getLocalizedText(DiagnosticCode.file1, null);
var tscSyntax = "tsc [" + optionsWord + "] [" + fileWord + " ..]";
var syntaxHelp = getLocalizedText(DiagnosticCode.Syntax_0, [tscSyntax]);
this.host.standardOut.WriteLine(syntaxHelp);
this.host.standardOut.WriteLine("");
this.host.standardOut.WriteLine(getLocalizedText(DiagnosticCode.Examples, null) + " tsc hello.ts");
this.host.standardOut.WriteLine(" tsc --out foo.js foo.ts");
this.host.standardOut.WriteLine(" tsc @args.txt");
this.host.standardOut.WriteLine("");
this.host.standardOut.WriteLine(getLocalizedText(DiagnosticCode.Options, null));
var output: string[][] = [];
var maxLength = 0;
var i = 0;
this.options = this.options.sort(function (a, b) {
var aName = a.name.toLowerCase();
var bName = b.name.toLowerCase();
if (aName > bName) {
return 1;
} else if (aName < bName) {
return -1;
} else {
return 0;
}
});
// Build up output array
for (i = 0; i < this.options.length; i++) {
var option = this.options[i];
if (option.experimental) {
continue;
}
if (!option.usage) {
break;
}
var usageString = " ";
var type = option.type ? (" " + TypeScript.getLocalizedText(option.type, null)) : "";
if (option.short) {
usageString += this.DEFAULT_SHORT_FLAG + option.short + type + ", ";
}
usageString += this.DEFAULT_LONG_FLAG + option.name + type;
output.push([usageString, TypeScript.getLocalizedText(option.usage.locCode, option.usage.args)]);
if (usageString.length > maxLength) {
maxLength = usageString.length;
}
}
var fileDescription = getLocalizedText(DiagnosticCode.Insert_command_line_options_and_files_from_a_file, null);
output.push([" @<" + fileWord + ">", fileDescription]);
// Print padded output
for (i = 0; i < output.length; i++) {
this.host.standardOut.WriteLine(output[i][0] + (new Array(maxLength - output[i][0].length + 3)).join(" ") + output[i][1]);
}
}
public printVersion() {
if (!this.printedVersion) {
this.host.standardOut.WriteLine(getLocalizedText(DiagnosticCode.Version_0, [this.version]));
this.printedVersion = true;
}
}
public option(name: string, config: IOptions, short?: string) {
if (!config) {
config = <any>short;
short = null;
}
config.name = name;
config.short = short;
config.flag = false;
this.options.push(config);
}
public flag(name: string, config: IOptions, short?: string) {
if (!config) {
config = <any>short;
short = null;
}
config.name = name;
config.short = short;
config.flag = true;
this.options.push(config);
}
// Parse an arguments string
public parseString(argString: string) {
var position = 0;
var tokens = argString.match(/\s+|"|[^\s"]+/g);
function peek() {
return tokens[position];
}
function consume() {
return tokens[position++];
}
function consumeQuotedString() {
var value = '';
consume(); // skip opening quote.
var token = peek();
while (token && token !== '"') {
consume();
value += token;
token = peek();
}
consume(); // skip ending quote;
return value;
}
var args: string[] = [];
var currentArg = '';
while (position < tokens.length) {
var token = peek();
if (token === '"') {
currentArg += consumeQuotedString();
} else if (token.match(/\s/)) {
if (currentArg.length > 0) {
args.push(currentArg);
currentArg = '';
}
consume();
} else {
consume();
currentArg += token;
}
}
if (currentArg.length > 0) {
args.push(currentArg);
}
this.parse(args);
}
// Parse arguments as they come from the platform: split into arguments.
public parse(args: string[]) {
var position = 0;
function consume() {
return args[position++];
}
while (position < args.length) {
var current = consume();
var match = current.match(/^(--?|@)(.*)/);
var value: any = null;
if (match) {
if (match[1] === '@') {
this.parseString(this.host.readFile(match[2], null).contents);
} else {
var arg = match[2];
var option = this.findOption(arg);
if (option === null) {
this.host.standardOut.WriteLine(getDiagnosticMessage(DiagnosticCode.Unknown_compiler_option_0, [arg]));
this.host.standardOut.WriteLine(getLocalizedText(DiagnosticCode.Use_the_0_flag_to_see_options, ["--help"]));
} else {
if (!option.flag) {
value = consume();
if (value === undefined) {
// No value provided
this.host.standardOut.WriteLine(getDiagnosticMessage(DiagnosticCode.Option_0_specified_without_1, [arg, getLocalizedText(option.type, null)]));
this.host.standardOut.WriteLine(getLocalizedText(DiagnosticCode.Use_the_0_flag_to_see_options, ["--help"]));
continue;
}
}
option.set(value);
}
}
} else {
this.unnamed.push(current);
}
}
}
}
}
-736
View File
@@ -1,736 +0,0 @@
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
///<reference path='typescript.ts'/>
///<reference path='io.ts'/>
///<reference path='optionsParser.ts'/>
module TypeScript {
class SourceFile {
constructor(public scriptSnapshot: IScriptSnapshot, public byteOrderMark: ByteOrderMark) {
}
}
class DiagnosticsLogger implements ILogger {
constructor(public ioHost: IEnvironment) {
}
public information(): boolean { return false; }
public debug(): boolean { return false; }
public warning(): boolean { return false; }
public error(): boolean { return false; }
public fatal(): boolean { return false; }
public log(s: string): void {
this.ioHost.standardOut.WriteLine(s);
}
}
export class BatchCompiler implements IReferenceResolverHost {
public compilerVersion = "1.0.1.0";
private inputFiles: string[] = [];
private compilationSettings: ImmutableCompilationSettings;
private resolvedFiles: IResolvedFile[] = [];
private fileNameToSourceFile = new StringHashTable<SourceFile>();
private hasErrors: boolean = false;
private logger: ILogger = null;
constructor(private ioHost: IEnvironment) {
}
// Begin batch compilation
public batchCompile() {
// Parse command line options
if (this.parseOptions()) {
var start = new Date().getTime();
if (this.compilationSettings.gatherDiagnostics()) {
this.logger = new DiagnosticsLogger(this.ioHost);
} else {
this.logger = new NullLogger();
}
if (this.compilationSettings.watch()) {
// Watch will cause the program to stick around as long as the files exist
this.watchFiles();
return;
}
// Resolve the compilation environemnt
this.resolve();
this.compile();
if (this.compilationSettings.gatherDiagnostics()) {
this.logger.log("");
this.logger.log("File resolution time: " + TypeScript.fileResolutionTime);
this.logger.log(" file read: " + TypeScript.fileResolutionIOTime);
this.logger.log(" scan imports: " + TypeScript.fileResolutionScanImportsTime);
this.logger.log(" import search: " + TypeScript.fileResolutionImportFileSearchTime);
this.logger.log(" get lib.d.ts: " + TypeScript.fileResolutionGetDefaultLibraryTime);
this.logger.log("SyntaxTree parse time: " + TypeScript.syntaxTreeParseTime);
this.logger.log("Syntax Diagnostics time: " + TypeScript.syntaxDiagnosticsTime);
this.logger.log("Create declarations time: " + TypeScript.createDeclarationsTime);
this.logger.log("");
this.logger.log("Type check time: " + TypeScript.typeCheckTime);
this.logger.log("");
this.logger.log("Emit time: " + TypeScript.emitTime);
this.logger.log("Declaration emit time: " + TypeScript.declarationEmitTime);
this.logger.log("Total number of symbols created: " + TypeScript.pullSymbolID);
this.logger.log("Specialized types created: " + TypeScript.nSpecializationsCreated);
this.logger.log("Specialized signatures created: " + TypeScript.nSpecializedSignaturesCreated);
this.logger.log(" IsExternallyVisibleTime: " + TypeScript.declarationEmitIsExternallyVisibleTime);
this.logger.log(" TypeSignatureTime: " + TypeScript.declarationEmitTypeSignatureTime);
this.logger.log(" GetBoundDeclTypeTime: " + TypeScript.declarationEmitGetBoundDeclTypeTime);
this.logger.log(" IsOverloadedCallSignatureTime: " + TypeScript.declarationEmitIsOverloadedCallSignatureTime);
this.logger.log(" FunctionDeclarationGetSymbolTime: " + TypeScript.declarationEmitFunctionDeclarationGetSymbolTime);
this.logger.log(" GetBaseTypeTime: " + TypeScript.declarationEmitGetBaseTypeTime);
this.logger.log(" GetAccessorFunctionTime: " + TypeScript.declarationEmitGetAccessorFunctionTime);
this.logger.log(" GetTypeParameterSymbolTime: " + TypeScript.declarationEmitGetTypeParameterSymbolTime);
this.logger.log(" GetImportDeclarationSymbolTime: " + TypeScript.declarationEmitGetImportDeclarationSymbolTime);
this.logger.log("Emit write file time: " + TypeScript.emitWriteFileTime);
this.logger.log("Compiler resolve path time: " + TypeScript.compilerResolvePathTime);
this.logger.log("Compiler directory name time: " + TypeScript.compilerDirectoryNameTime);
this.logger.log("Compiler directory exists time: " + TypeScript.compilerDirectoryExistsTime);
this.logger.log("Compiler file exists time: " + TypeScript.compilerFileExistsTime);
this.logger.log("IO host resolve path time: " + TypeScript.ioHostResolvePathTime);
this.logger.log("IO host directory name time: " + TypeScript.ioHostDirectoryNameTime);
this.logger.log("IO host create directory structure time: " + TypeScript.ioHostCreateDirectoryStructureTime);
this.logger.log("IO host write file time: " + TypeScript.ioHostWriteFileTime);
this.logger.log("Node make directory time: " + TypeScript.nodeMakeDirectoryTime);
this.logger.log("Node writeFileSync time: " + TypeScript.nodeWriteFileSyncTime);
this.logger.log("Node createBuffer time: " + TypeScript.nodeCreateBufferTime);
this.logger.log("Total time: " + (new Date().getTime() - start));
}
}
// Exit with the appropriate error code
this.ioHost.quit(this.hasErrors ? 1 : 0);
}
private resolve() {
// Resolve file dependencies, if requested
var includeDefaultLibrary = !this.compilationSettings.noLib();
var resolvedFiles: IResolvedFile[] = [];
var start = new Date().getTime();
if (!this.compilationSettings.noResolve()) {
// Resolve references
var resolutionResults = ReferenceResolver.resolve(this.inputFiles, this, this.compilationSettings.useCaseSensitiveFileResolution());
resolvedFiles = resolutionResults.resolvedFiles;
// Only include the library if useDefaultLib is set to true and did not see any 'no-default-lib' comments
includeDefaultLibrary = !this.compilationSettings.noLib() && !resolutionResults.seenNoDefaultLibTag;
// Populate any diagnostic messages generated during resolution
resolutionResults.diagnostics.forEach(d => this.addDiagnostic(d));
}
else {
for (var i = 0, n = this.inputFiles.length; i < n; i++) {
var inputFile = this.inputFiles[i];
var referencedFiles: string[] = [];
var importedFiles: string[] = [];
// If declaration files are going to be emitted, preprocess the file contents and add in referenced files as well
if (this.compilationSettings.generateDeclarationFiles()) {
var references = getReferencedFiles(inputFile, this.getScriptSnapshot(inputFile));
for (var j = 0; j < references.length; j++) {
referencedFiles.push(references[j].path);
}
inputFile = this.resolvePath(inputFile);
}
resolvedFiles.push({
path: inputFile,
referencedFiles: referencedFiles,
importedFiles: importedFiles
});
}
}
var defaultLibStart = new Date().getTime();
if (includeDefaultLibrary) {
var libraryResolvedFile: IResolvedFile = {
path: this.getDefaultLibraryFilePath(),
referencedFiles: [],
importedFiles: []
};
// Prepend the library to the resolved list
resolvedFiles = [libraryResolvedFile].concat(resolvedFiles);
}
TypeScript.fileResolutionGetDefaultLibraryTime += new Date().getTime() - defaultLibStart;
this.resolvedFiles = resolvedFiles;
TypeScript.fileResolutionTime = new Date().getTime() - start;
}
// Returns true if compilation failed from some reason.
private compile(): void {
var compiler = new TypeScriptCompiler(this.logger, this.compilationSettings);
this.resolvedFiles.forEach(resolvedFile => {
var sourceFile = this.getSourceFile(resolvedFile.path);
compiler.addFile(resolvedFile.path, sourceFile.scriptSnapshot, sourceFile.byteOrderMark, /*version:*/ 0, /*isOpen:*/ false, resolvedFile.referencedFiles);
});
for (var it = compiler.compile((path: string) => this.resolvePath(path)); it.moveNext();) {
var result = it.current();
result.diagnostics.forEach(d => this.addDiagnostic(d));
if (!this.tryWriteOutputFiles(result.outputFiles)) {
return;
}
}
}
// Parse command line options
private parseOptions() {
var opts = new OptionsParser(this.ioHost, this.compilerVersion);
var mutableSettings = new CompilationSettings();
opts.option('out', {
usage: {
locCode: DiagnosticCode.Concatenate_and_emit_output_to_single_file,
args: null
},
type: DiagnosticCode.file2,
set: (str) => {
mutableSettings.outFileOption = str;
}
});
opts.option('outDir', {
usage: {
locCode: DiagnosticCode.Redirect_output_structure_to_the_directory,
args: null
},
type: DiagnosticCode.DIRECTORY,
set: (str) => {
mutableSettings.outDirOption = str;
}
});
opts.flag('sourcemap', {
usage: {
locCode: DiagnosticCode.Generates_corresponding_0_file,
args: ['.map']
},
set: () => {
mutableSettings.mapSourceFiles = true;
}
});
opts.option('mapRoot', {
usage: {
locCode: DiagnosticCode.Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
args: null
},
type: DiagnosticCode.LOCATION,
set: (str) => {
mutableSettings.mapRoot = str;
}
});
opts.option('sourceRoot', {
usage: {
locCode: DiagnosticCode.Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
args: null
},
type: DiagnosticCode.LOCATION,
set: (str) => {
mutableSettings.sourceRoot = str;
}
});
opts.flag('declaration', {
usage: {
locCode: DiagnosticCode.Generates_corresponding_0_file,
args: ['.d.ts']
},
set: () => {
mutableSettings.generateDeclarationFiles = true;
}
}, 'd');
if (this.ioHost.watchFile) {
opts.flag('watch', {
usage: {
locCode: DiagnosticCode.Watch_input_files,
args: null
},
set: () => {
mutableSettings.watch = true;
}
}, 'w');
}
opts.flag('propagateEnumConstants', {
experimental: true,
set: () => { mutableSettings.propagateEnumConstants = true; }
});
opts.flag('removeComments', {
usage: {
locCode: DiagnosticCode.Do_not_emit_comments_to_output,
args: null
},
set: () => {
mutableSettings.removeComments = true;
}
});
opts.flag('noResolve', {
experimental: true,
usage: {
locCode: DiagnosticCode.Skip_resolution_and_preprocessing,
args: null
},
set: () => {
mutableSettings.noResolve = true;
}
});
opts.flag('noLib', {
experimental: true,
set: () => {
mutableSettings.noLib = true;
}
});
opts.flag('diagnostics', {
experimental: true,
set: () => {
mutableSettings.gatherDiagnostics = true;
}
});
opts.option('target', {
usage: {
locCode: DiagnosticCode.Specify_ECMAScript_target_version_0_default_or_1,
args: ['ES3', 'ES5']
},
type: DiagnosticCode.VERSION,
set: (type) => {
type = type.toLowerCase();
if (type === 'es3') {
mutableSettings.codeGenTarget = LanguageVersion.EcmaScript3;
}
else if (type === 'es5') {
mutableSettings.codeGenTarget = LanguageVersion.EcmaScript5;
}
else {
this.addDiagnostic(
new Diagnostic(null, null, 0, 0, DiagnosticCode.Argument_for_0_option_must_be_1_or_2, ["target", "ES3", "ES5"]));
}
}
}, 't');
opts.option('module', {
usage: {
locCode: DiagnosticCode.Specify_module_code_generation_0_or_1,
args: ['commonjs', 'amd']
},
type: DiagnosticCode.KIND,
set: (type) => {
type = type.toLowerCase();
if (type === 'commonjs') {
mutableSettings.moduleGenTarget = ModuleGenTarget.Synchronous;
}
else if (type === 'amd') {
mutableSettings.moduleGenTarget = ModuleGenTarget.Asynchronous;
}
else {
this.addDiagnostic(
new Diagnostic(null, null, 0, 0, DiagnosticCode.Argument_for_0_option_must_be_1_or_2, ["module", "commonjs", "amd"]));
}
}
}, 'm');
var needsHelp = false;
opts.flag('help', {
usage: {
locCode: DiagnosticCode.Print_this_message,
args: null
},
set: () => {
needsHelp = true;
}
}, 'h');
opts.flag('useCaseSensitiveFileResolution', {
experimental: true,
set: () => {
mutableSettings.useCaseSensitiveFileResolution = true;
}
});
var shouldPrintVersionOnly = false;
opts.flag('version', {
usage: {
locCode: DiagnosticCode.Print_the_compiler_s_version_0,
args: [this.compilerVersion]
},
set: () => {
shouldPrintVersionOnly = true;
}
}, 'v');
var locale: string = null;
opts.option('locale', {
experimental: true,
usage: {
locCode: DiagnosticCode.Specify_locale_for_errors_and_messages_For_example_0_or_1,
args: ['en', 'ja-jp']
},
type: DiagnosticCode.STRING,
set: (value) => {
locale = value;
}
});
opts.flag('noImplicitAny', {
usage: {
locCode: DiagnosticCode.Raise_error_on_expressions_and_declarations_with_an_implied_any_type,
args: null
},
set: () => {
mutableSettings.noImplicitAny = true;
}
});
if (Environment.supportsCodePage()) {
opts.option('codepage', {
usage: {
locCode: DiagnosticCode.Specify_the_codepage_to_use_when_opening_source_files,
args: null
},
type: DiagnosticCode.NUMBER,
set: (arg) => {
mutableSettings.codepage = parseInt(arg, 10);
}
});
}
opts.parse(this.ioHost.arguments);
this.compilationSettings = ImmutableCompilationSettings.fromCompilationSettings(mutableSettings);
if (locale) {
if (!this.setLocale(locale)) {
return false;
}
}
this.inputFiles.push.apply(this.inputFiles, opts.unnamed);
if (shouldPrintVersionOnly) {
opts.printVersion();
return false;
}
// If no source files provided to compiler - print usage information
else if (this.inputFiles.length === 0 || needsHelp) {
opts.printUsage();
return false;
}
return !this.hasErrors;
}
private setLocale(locale: string): boolean {
var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
if (!matchResult) {
this.addDiagnostic(new Diagnostic(null, null, 0, 0, DiagnosticCode.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, ['en', 'ja-jp']));
return false;
}
var language = matchResult[1];
var territory = matchResult[3];
// First try the entire locale, then fall back to just language if that's all we have.
if (!this.setLanguageAndTerritory(language, territory) &&
!this.setLanguageAndTerritory(language, null)) {
this.addDiagnostic(new Diagnostic(null, null, 0, 0, DiagnosticCode.Unsupported_locale_0, [locale]));
return false;
}
return true;
}
private setLanguageAndTerritory(language: string, territory: string): boolean {
var compilerFilePath = this.ioHost.executingFilePath();
var containingDirectoryPath = this.ioHost.directoryName(compilerFilePath);
var filePath = IOUtils.combine(containingDirectoryPath, language);
if (territory) {
filePath = filePath + "-" + territory;
}
filePath = this.resolvePath(IOUtils.combine(filePath, "diagnosticMessages.generated.json"));
if (!this.fileExists(filePath)) {
return false;
}
var fileContents = this.ioHost.readFile(filePath, this.compilationSettings.codepage());
TypeScript.LocalizedDiagnosticMessages = JSON.parse(fileContents.contents);
return true;
}
// Handle -watch switch
private watchFiles() {
if (!this.ioHost.watchFile) {
this.addDiagnostic(
new Diagnostic(null, null, 0, 0, DiagnosticCode.Current_host_does_not_support_0_option, ['-w[atch]']));
return;
}
var lastResolvedFileSet: string[] = []
var watchers: { [x: string]: IFileWatcher; } = {};
var firstTime = true;
var addWatcher = (fileName: string) => {
if (!watchers[fileName]) {
var watcher = this.ioHost.watchFile(fileName, onWatchedFileChange);
watchers[fileName] = watcher;
}
};
var removeWatcher = (fileName: string) => {
if (watchers[fileName]) {
watchers[fileName].close();
delete watchers[fileName];
}
};
var onWatchedFileChange = () => {
// Clean errors for previous compilation
this.hasErrors = false;
// Clear out any source file data we've cached.
this.fileNameToSourceFile = new StringHashTable<SourceFile>();
// Resolve file dependencies, if requested
this.resolve();
// Check if any new files were added to the environment as a result of the file change
var oldFiles = lastResolvedFileSet;
var newFiles = this.resolvedFiles.map(resolvedFile => resolvedFile.path).sort();
var i = 0, j = 0;
while (i < oldFiles.length && j < newFiles.length) {
var compareResult = oldFiles[i].localeCompare(newFiles[j]);
if (compareResult === 0) {
// No change here
i++;
j++;
}
else if (compareResult < 0) {
// Entry in old list does not exist in the new one, it was removed
removeWatcher(oldFiles[i]);
i++;
}
else {
// Entry in new list does exist in the new one, it was added
addWatcher(newFiles[j]);
j++;
}
}
// All remaining unmatched items in the old list have been removed
for (var k = i; k < oldFiles.length; k++) {
removeWatcher(oldFiles[k]);
}
// All remaing unmatched items in the new list have been added
for (k = j; k < newFiles.length; k++) {
addWatcher(newFiles[k]);
}
// Update the state
lastResolvedFileSet = newFiles;
// Print header
if (!firstTime) {
var fileNames = "";
for (var k = 0; k < lastResolvedFileSet.length; k++) {
fileNames += Environment.newLine + " " + lastResolvedFileSet[k];
}
this.ioHost.standardError.WriteLine(getLocalizedText(DiagnosticCode.NL_Recompiling_0, [fileNames]));
}
else {
firstTime = false;
}
// Trigger a new compilation
this.compile();
};
// Switch to using stdout for all error messages
this.ioHost.standardOut = this.ioHost.standardOut;
onWatchedFileChange();
}
private getSourceFile(fileName: string): SourceFile {
var sourceFile: SourceFile = this.fileNameToSourceFile.lookup(fileName);
if (!sourceFile) {
// Attempt to read the file
var fileInformation: FileInformation;
try {
fileInformation = this.ioHost.readFile(fileName, this.compilationSettings.codepage());
}
catch (e) {
this.addDiagnostic(new Diagnostic(null, null, 0, 0, DiagnosticCode.Cannot_read_file_0_1, [fileName, e.message]));
fileInformation = new FileInformation("", ByteOrderMark.None);
}
var snapshot = ScriptSnapshot.fromString(fileInformation.contents);
var sourceFile = new SourceFile(snapshot, fileInformation.byteOrderMark);
this.fileNameToSourceFile.add(fileName, sourceFile);
}
return sourceFile;
}
private getDefaultLibraryFilePath(): string {
var compilerFilePath = this.ioHost.executingFilePath();
var containingDirectoryPath = this.ioHost.directoryName(compilerFilePath);
var libraryFilePath = this.resolvePath(IOUtils.combine(containingDirectoryPath, "lib.d.ts"));
return libraryFilePath;
}
/// IReferenceResolverHost methods
getScriptSnapshot(fileName: string): IScriptSnapshot {
return this.getSourceFile(fileName).scriptSnapshot;
}
resolveRelativePath(path: string, directory: string): string {
var unQuotedPath = stripStartAndEndQuotes(path);
var normalizedPath: string;
if (isRooted(unQuotedPath) || !directory) {
normalizedPath = unQuotedPath;
} else {
normalizedPath = IOUtils.combine(directory, unQuotedPath);
}
// get the absolute path
normalizedPath = this.resolvePath(normalizedPath);
// Switch to forward slashes
normalizedPath = switchToForwardSlashes(normalizedPath);
return normalizedPath;
}
private fileExistsCache = createIntrinsicsObject<boolean>();
fileExists(path: string): boolean {
var exists = this.fileExistsCache[path];
if (exists === undefined) {
var start = new Date().getTime();
exists = this.ioHost.fileExists(path);
this.fileExistsCache[path] = exists;
TypeScript.compilerFileExistsTime += new Date().getTime() - start;
}
return exists;
}
getParentDirectory(path: string): string {
var start = new Date().getTime();
var result = this.ioHost.directoryName(path);
TypeScript.compilerDirectoryNameTime += new Date().getTime() - start;
return result;
}
private addDiagnostic(diagnostic: Diagnostic): void {
var diagnosticInfo = diagnostic.info();
if (diagnosticInfo.category === DiagnosticCategory.Error) {
this.hasErrors = true;
}
this.ioHost.standardError.Write(TypeScriptCompiler.getFullDiagnosticText(diagnostic, path => this.resolvePath(path)));
}
private tryWriteOutputFiles(outputFiles: OutputFile[]): boolean {
for (var i = 0, n = outputFiles.length; i < n; i++) {
var outputFile = outputFiles[i];
try {
this.writeFile(outputFile.name, outputFile.text, outputFile.writeByteOrderMark);
}
catch (e) {
this.addDiagnostic(
new Diagnostic(outputFile.name, null, 0, 0, DiagnosticCode.Emit_Error_0, [e.message]));
return false;
}
}
return true;
}
writeFile(fileName: string, contents: string, writeByteOrderMark: boolean): void {
var start = new Date().getTime();
IOUtils.writeFileAndFolderStructure(this.ioHost, fileName, contents, writeByteOrderMark);
TypeScript.emitWriteFileTime += new Date().getTime() - start;
}
directoryExists(path: string): boolean {
var start = new Date().getTime();
var result = this.ioHost.directoryExists(path);
TypeScript.compilerDirectoryExistsTime += new Date().getTime() - start;
return result;
}
// For performance reasons we cache the results of resolvePath. This avoids costly lookup
// on the disk once we've already resolved a path once.
private resolvePathCache = createIntrinsicsObject<string>();
resolvePath(path: string): string {
var cachedValue = this.resolvePathCache[path];
if (!cachedValue) {
var start = new Date().getTime();
cachedValue = this.ioHost.absolutePath(path);
this.resolvePathCache[path] = cachedValue;
TypeScript.compilerResolvePathTime += new Date().getTime() - start;
}
return cachedValue;
}
}
// Start the batch compilation using the current hosts IO
var batch = new TypeScript.BatchCompiler(Environment);
batch.batchCompile();
}
@@ -402,19 +402,13 @@ module TypeScript {
Option_0_specified_without_1: "Option '{0}' specified without '{1}'",
codepage_option_not_supported_on_current_platform: "'codepage' option not supported on current platform.",
Concatenate_and_emit_output_to_single_file: "Concatenate and emit output to single file.",
Generates_corresponding_0_file: "Generates corresponding {0} file.",
Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: "Specifies the location where debugger should locate map files instead of generated locations.",
Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: "Specifies the location where debugger should locate TypeScript files instead of source locations.",
Watch_input_files: "Watch input files.",
Redirect_output_structure_to_the_directory: "Redirect output structure to the directory.",
Do_not_emit_comments_to_output: "Do not emit comments to output.",
Skip_resolution_and_preprocessing: "Skip resolution and preprocessing.",
Specify_ECMAScript_target_version_0_default_or_1: "Specify ECMAScript target version: '{0}' (default), or '{1}'",
Specify_module_code_generation_0_or_1: "Specify module code generation: '{0}' or '{1}'",
Print_this_message: "Print this message.",
Print_the_compiler_s_version_0: "Print the compiler's version: {0}",
Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: "Allow use of deprecated '{0}' keyword when referencing an external module.",
Specify_locale_for_errors_and_messages_For_example_0_or_1: "Specify locale for errors and messages. For example '{0}' or '{1}'",
Syntax_0: "Syntax: {0}",
options: "options",
file1: "file",
@@ -431,7 +425,6 @@ module TypeScript {
LOCATION: "LOCATION",
DIRECTORY: "DIRECTORY",
NUMBER: "NUMBER",
Specify_the_codepage_to_use_when_opening_source_files: "Specify the codepage to use when opening source files.",
Additional_locations: "Additional locations:",
This_version_of_the_Javascript_runtime_does_not_support_the_0_function: "This version of the Javascript runtime does not support the '{0}' function.",
Unknown_rule: "Unknown rule.",
+37 -29
View File
@@ -335,36 +335,44 @@ module ts {
var paramTag = "@param";
var jsDocCommentParts: SymbolDisplayPart[] = [];
ts.forEach(declarations, declaration => {
var sourceFileOfDeclaration = getSourceFileOfNode(declaration);
// If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments
if (canUseParsedParamTagComments && declaration.kind === SyntaxKind.Parameter) {
ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), jsDocCommentTextRange => {
var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedParamJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedParamJsDocComment);
}
});
ts.forEach(declarations, (declaration, indexOfDeclaration) => {
// Make sure we are collecting doc comment from declaration once,
// In case of union property there might be same declaration multiple times
// which only varies in type parameter
// Eg. var a: Array<string> | Array<number>; a.length
// The property length will have two declarations of property length coming
// from Array<T> - Array<string> and Array<number>
if (indexOf(declarations, declaration) === indexOfDeclaration) {
var sourceFileOfDeclaration = getSourceFileOfNode(declaration);
// If it is parameter - try and get the jsDoc comment with @param tag from function declaration's jsDoc comments
if (canUseParsedParamTagComments && declaration.kind === SyntaxKind.Parameter) {
ts.forEach(getJsDocCommentTextRange(declaration.parent, sourceFileOfDeclaration), jsDocCommentTextRange => {
var cleanedParamJsDocComment = getCleanedParamJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedParamJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedParamJsDocComment);
}
});
}
// If this is left side of dotted module declaration, there is no doc comments associated with this node
if (declaration.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>declaration).body.kind === SyntaxKind.ModuleDeclaration) {
return;
}
// If this is dotted module name, get the doc comments from the parent
while (declaration.kind === SyntaxKind.ModuleDeclaration && declaration.parent.kind === SyntaxKind.ModuleDeclaration) {
declaration = <ModuleDeclaration>declaration.parent;
}
// Get the cleaned js doc comment text from the declaration
ts.forEach(getJsDocCommentTextRange(
declaration.kind === SyntaxKind.VariableDeclaration ? declaration.parent.parent : declaration, sourceFileOfDeclaration), jsDocCommentTextRange => {
var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment);
}
});
}
// If this is left side of dotted module declaration, there is no doc comments associated with this node
if (declaration.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>declaration).body.kind === SyntaxKind.ModuleDeclaration) {
return;
}
// If this is dotted module name, get the doc comments from the parent
while (declaration.kind === SyntaxKind.ModuleDeclaration && declaration.parent.kind === SyntaxKind.ModuleDeclaration) {
declaration = <ModuleDeclaration>declaration.parent;
}
// Get the cleaned js doc comment text from the declaration
ts.forEach(getJsDocCommentTextRange(
declaration.kind === SyntaxKind.VariableDeclaration ? declaration.parent.parent : declaration, sourceFileOfDeclaration), jsDocCommentTextRange => {
var cleanedJsDocComment = getCleanedJsDocComment(jsDocCommentTextRange.pos, jsDocCommentTextRange.end, sourceFileOfDeclaration);
if (cleanedJsDocComment) {
jsDocCommentParts.push.apply(jsDocCommentParts, cleanedJsDocComment);
}
});
});
return jsDocCommentParts;
-7
View File
@@ -383,19 +383,13 @@ declare module TypeScript {
Option_0_specified_without_1: string;
codepage_option_not_supported_on_current_platform: string;
Concatenate_and_emit_output_to_single_file: string;
Generates_corresponding_0_file: string;
Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: string;
Specifies_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations: string;
Watch_input_files: string;
Redirect_output_structure_to_the_directory: string;
Do_not_emit_comments_to_output: string;
Skip_resolution_and_preprocessing: string;
Specify_ECMAScript_target_version_0_default_or_1: string;
Specify_module_code_generation_0_or_1: string;
Print_this_message: string;
Print_the_compiler_s_version_0: string;
Allow_use_of_deprecated_0_keyword_when_referencing_an_external_module: string;
Specify_locale_for_errors_and_messages_For_example_0_or_1: string;
Syntax_0: string;
options: string;
file1: string;
@@ -412,7 +406,6 @@ declare module TypeScript {
LOCATION: string;
DIRECTORY: string;
NUMBER: string;
Specify_the_codepage_to_use_when_opening_source_files: string;
Additional_locations: string;
This_version_of_the_Javascript_runtime_does_not_support_the_0_function: string;
Unknown_rule: string;