merge with master

This commit is contained in:
Vladimir Matveev 2015-01-08 15:16:01 -08:00
commit 9934c5c124
203 changed files with 18798 additions and 11523 deletions

View file

@ -1,5 +1,7 @@
built
doc
scripts
src
tests
Jakefile
.travis.yml

View file

@ -39,6 +39,7 @@ var compilerSources = [
"binder.ts",
"checker.ts",
"emitter.ts",
"program.ts",
"commandLineParser.ts",
"tsc.ts",
"diagnosticInformationMap.generated.ts"
@ -56,6 +57,7 @@ var servicesSources = [
"binder.ts",
"checker.ts",
"emitter.ts",
"program.ts",
"diagnosticInformationMap.generated.ts"
].map(function (f) {
return path.join(compilerDirectory, f);
@ -92,6 +94,7 @@ var definitionsRoots = [
"compiler/scanner.d.ts",
"compiler/parser.d.ts",
"compiler/checker.d.ts",
"compiler/program.d.ts",
"services/services.d.ts",
];
@ -189,8 +192,7 @@ var compilerFilename = "tsc.js";
* @param keepComments: false to compile using --removeComments
* @param callback: a function to execute after the compilation process ends
*/
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, keepComments, noResolve, callback) {
function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOutFile, generateDeclarations, outDir, preserveConstEnums, keepComments, noResolve, callback) {
file(outFile, prereqs, function() {
var dir = useBuiltCompiler ? builtLocalDirectory : LKGDirectory;
var options = "--module commonjs -noImplicitAny";
@ -203,7 +205,7 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, noOu
options += " --declaration";
}
if (useDebugMode) {
if (useDebugMode || preserveConstEnums) {
options += " --preserveConstEnums";
}
@ -319,7 +321,15 @@ var tscFile = path.join(builtLocalDirectory, compilerFilename);
compileFile(tscFile, compilerSources, [builtLocalDirectory, copyright].concat(compilerSources), [copyright], /*useBuiltCompiler:*/ false);
var servicesFile = path.join(builtLocalDirectory, "typescriptServices.js");
compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources), [copyright], /*useBuiltCompiler*/ true);
compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].concat(servicesSources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ false,
/*outDir*/ undefined,
/*preserveConstEnums*/ true,
/*keepComments*/ false,
/*noResolve*/ false);
var nodeDefinitionsFile = path.join(builtLocalDirectory, "typescript.d.ts");
var standaloneDefinitionsFile = path.join(builtLocalDirectory, "typescriptServices.d.ts");
@ -332,6 +342,7 @@ compileFile(nodeDefinitionsFile, servicesSources,[builtLocalDirectory, copyright
/*noOutFile*/ true,
/*generateDeclarations*/ true,
/*outDir*/ tempDirPath,
/*preserveConstEnums*/ true,
/*keepComments*/ true,
/*noResolve*/ true,
/*callback*/ function () {
@ -380,7 +391,7 @@ task("clean", function() {
var analyzerFile = path.join(builtLocalDirectory, "analyzer.js");
var analyserSourceFile = "src/services/analyzer.ts";
compileFile(analyzerFile, [analyserSourceFile], [builtLocalDirectory, analyserSourceFile].concat(servicesSources), [], true, false, true);
compileFile(analyzerFile, [analyserSourceFile], [builtLocalDirectory, analyserSourceFile].concat(servicesSources), [], false, false, true);
desc("Builds analyzer");
task("analyzer", [analyzerFile]);

9373
bin/tsc.js

File diff suppressed because it is too large Load diff

214
bin/typescript.d.ts vendored
View file

@ -189,29 +189,29 @@ declare module "typescript" {
ConditionalExpression = 164,
TemplateExpression = 165,
YieldExpression = 166,
OmittedExpression = 167,
TemplateSpan = 168,
Block = 169,
VariableStatement = 170,
EmptyStatement = 171,
ExpressionStatement = 172,
IfStatement = 173,
DoStatement = 174,
WhileStatement = 175,
ForStatement = 176,
ForInStatement = 177,
ContinueStatement = 178,
BreakStatement = 179,
ReturnStatement = 180,
WithStatement = 181,
SwitchStatement = 182,
LabeledStatement = 183,
ThrowStatement = 184,
TryStatement = 185,
TryBlock = 186,
FinallyBlock = 187,
DebuggerStatement = 188,
VariableDeclaration = 189,
SpreadElementExpression = 167,
OmittedExpression = 168,
TemplateSpan = 169,
Block = 170,
VariableStatement = 171,
EmptyStatement = 172,
ExpressionStatement = 173,
IfStatement = 174,
DoStatement = 175,
WhileStatement = 176,
ForStatement = 177,
ForInStatement = 178,
ContinueStatement = 179,
BreakStatement = 180,
ReturnStatement = 181,
WithStatement = 182,
SwitchStatement = 183,
LabeledStatement = 184,
ThrowStatement = 185,
TryStatement = 186,
DebuggerStatement = 187,
VariableDeclaration = 188,
VariableDeclarationList = 189,
FunctionDeclaration = 190,
ClassDeclaration = 191,
InterfaceDeclaration = 192,
@ -230,9 +230,8 @@ declare module "typescript" {
ShorthandPropertyAssignment = 205,
EnumMember = 206,
SourceFile = 207,
Program = 208,
SyntaxList = 209,
Count = 210,
SyntaxList = 208,
Count = 209,
FirstAssignment = 52,
LastAssignment = 63,
FirstReservedWord = 65,
@ -253,8 +252,6 @@ declare module "typescript" {
LastLiteralToken = 10,
FirstTemplateToken = 10,
LastTemplateToken = 13,
FirstOperator = 22,
LastOperator = 63,
FirstBinaryOperator = 24,
LastBinaryOperator = 63,
FirstNode = 121,
@ -331,10 +328,14 @@ declare module "typescript" {
type?: TypeNode;
}
interface VariableDeclaration extends Declaration {
parent?: VariableDeclarationList;
name: Identifier | BindingPattern;
type?: TypeNode;
initializer?: Expression;
}
interface VariableDeclarationList extends Node {
declarations: NodeArray<VariableDeclaration>;
}
interface ParameterDeclaration extends Declaration {
dotDotDotToken?: Node;
name: Identifier | BindingPattern;
@ -514,6 +515,9 @@ declare module "typescript" {
interface ArrayLiteralExpression extends PrimaryExpression {
elements: NodeArray<Expression>;
}
interface SpreadElementExpression extends Expression {
expression: Expression;
}
interface ObjectLiteralExpression extends PrimaryExpression, Declaration {
properties: NodeArray<ObjectLiteralElement>;
}
@ -548,7 +552,7 @@ declare module "typescript" {
statements: NodeArray<Statement>;
}
interface VariableStatement extends Statement {
declarations: NodeArray<VariableDeclaration>;
declarationList: VariableDeclarationList;
}
interface ExpressionStatement extends Statement {
expression: Expression;
@ -568,14 +572,12 @@ declare module "typescript" {
expression: Expression;
}
interface ForStatement extends IterationStatement {
declarations?: NodeArray<VariableDeclaration>;
initializer?: Expression;
initializer?: VariableDeclarationList | Expression;
condition?: Expression;
iterator?: Expression;
}
interface ForInStatement extends IterationStatement {
declarations?: NodeArray<VariableDeclaration>;
variable?: Expression;
initializer: VariableDeclarationList | Expression;
expression: Expression;
}
interface BreakOrContinueStatement extends Statement {
@ -682,12 +684,12 @@ declare module "typescript" {
getLineAndCharacterFromPosition(position: number): LineAndCharacter;
getPositionFromLineAndCharacter(line: number, character: number): number;
getLineStarts(): number[];
update(newText: string, textChangeRange: TextChangeRange): SourceFile;
amdDependencies: string[];
amdModuleName: string;
referencedFiles: FileReference[];
referenceDiagnostics: Diagnostic[];
parseDiagnostics: Diagnostic[];
grammarDiagnostics: Diagnostic[];
getSyntacticDiagnostics(): Diagnostic[];
semanticDiagnostics: Diagnostic[];
hasNoDefaultLib: boolean;
@ -698,15 +700,21 @@ declare module "typescript" {
languageVersion: ScriptTarget;
identifiers: Map<string>;
}
interface Program {
getSourceFile(filename: string): SourceFile;
getSourceFiles(): SourceFile[];
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(filename: string): SourceFile;
getCurrentDirectory(): string;
}
interface Program extends ScriptReferenceHost {
getSourceFiles(): SourceFile[];
getCompilerHost(): CompilerHost;
getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getTypeChecker(fullTypeCheckMode: boolean): TypeChecker;
getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[];
getTypeChecker(produceDiagnostics: boolean): TypeChecker;
getCommonSourceDirectory(): string;
emitFiles(targetSourceFile?: SourceFile): EmitResult;
isEmitBlocked(sourceFile?: SourceFile): boolean;
}
interface SourceMapSpan {
emittedLine: number;
@ -740,16 +748,20 @@ declare module "typescript" {
diagnostics: Diagnostic[];
sourceMaps: SourceMapData[];
}
interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
getCompilerHost(): CompilerHost;
getSourceFiles(): SourceFile[];
getSourceFile(filename: string): SourceFile;
}
interface TypeChecker {
getProgram(): Program;
getEmitResolver(): EmitResolver;
getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getNodeCount(): number;
getIdentifierCount(): number;
getSymbolCount(): number;
getTypeCount(): number;
emitFiles(targetSourceFile?: SourceFile): EmitResult;
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
@ -773,7 +785,6 @@ declare module "typescript" {
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isEmitBlocked(sourceFile?: SourceFile): boolean;
getEnumMemberValue(node: EnumMember): number;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
@ -833,7 +844,6 @@ declare module "typescript" {
errorModuleName?: string;
}
interface EmitResolver {
getProgram(): Program;
getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string;
getExpressionNamePrefix(node: Identifier): string;
getExportAssignmentName(node: SourceFile): string;
@ -849,7 +859,6 @@ declare module "typescript" {
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult;
getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number;
isEmitBlocked(sourceFile?: SourceFile): boolean;
isUnknownIdentifier(location: Node, name: string): boolean;
}
const enum SymbolFlags {
@ -1119,6 +1128,7 @@ declare module "typescript" {
locale?: string;
mapRoot?: string;
module?: ModuleKind;
noEmit?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
@ -1303,13 +1313,18 @@ declare module "typescript" {
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
}
interface TextSpan {
start: number;
length: number;
}
interface TextChangeRange {
span: TextSpan;
newLength: number;
}
}
declare module "typescript" {
interface ErrorCallback {
(message: DiagnosticMessage): void;
}
interface CommentCallback {
(pos: number, end: number): void;
(message: DiagnosticMessage, length: number): void;
}
interface Scanner {
getStartPos(): number;
@ -1356,16 +1371,18 @@ declare module "typescript" {
function getNodeConstructor(kind: SyntaxKind): new () => Node;
function createNode(kind: SyntaxKind): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodes?: (nodes: Node[]) => T): T;
function createCompilerHost(options: CompilerOptions): CompilerHost;
function modifierToFlag(token: SyntaxKind): NodeFlags;
function isEvalOrArgumentsIdentifier(node: Node): boolean;
function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
function isLeftHandSideExpression(expr: Expression): boolean;
function isAssignmentOperator(token: SyntaxKind): boolean;
function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program;
}
declare module "typescript" {
function createTypeChecker(program: Program, fullTypeCheck: boolean): TypeChecker;
function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker;
}
declare module "typescript" {
function createCompilerHost(options: CompilerOptions): CompilerHost;
function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program;
}
declare module "typescript" {
var servicesVersion: string;
@ -1412,9 +1429,8 @@ declare module "typescript" {
interface SourceFile {
isOpen: boolean;
version: string;
getScriptSnapshot(): IScriptSnapshot;
scriptSnapshot: IScriptSnapshot;
getNamedDeclarations(): Declaration[];
update(scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile;
}
/**
* Represents an immutable snapshot of a script at a specified time.Once acquired, the
@ -1496,96 +1512,6 @@ declare module "typescript" {
getSourceFile(filename: string): SourceFile;
dispose(): void;
}
class TextSpan {
private _start;
private _length;
/**
* Creates a TextSpan instance beginning with the position Start and having the Length
* specified with length.
*/
constructor(start: number, length: number);
toJSON(key: any): any;
start(): number;
length(): number;
end(): number;
isEmpty(): boolean;
/**
* Determines whether the position lies within the span. Returns true if the position is greater than or equal to Start and strictly less
* than End, otherwise false.
* @param position The position to check.
*/
containsPosition(position: number): boolean;
/**
* Determines whether span falls completely within this span. Returns true if the specified span falls completely within this span, otherwise false.
* @param span The span to check.
*/
containsTextSpan(span: TextSpan): boolean;
/**
* Determines whether the given span overlaps this span. Two spans are considered to overlap
* if they have positions in common and neither is empty. Empty spans do not overlap with any
* other span. Returns true if the spans overlap, false otherwise.
* @param span The span to check.
*/
overlapsWith(span: TextSpan): boolean;
/**
* Returns the overlap with the given span, or undefined if there is no overlap.
* @param span The span to check.
*/
overlap(span: TextSpan): TextSpan;
/**
* Determines whether span intersects this span. Two spans are considered to
* intersect if they have positions in common or the end of one span
* coincides with the start of the other span. Returns true if the spans intersect, false otherwise.
* @param The span to check.
*/
intersectsWithTextSpan(span: TextSpan): boolean;
intersectsWith(start: number, length: number): boolean;
/**
* Determines whether the given position intersects this span.
* A position is considered to intersect if it is between the start and
* end positions (inclusive) of this span. Returns true if the position intersects, false otherwise.
* @param position The position to check.
*/
intersectsWithPosition(position: number): boolean;
/**
* Returns the intersection with the given span, or undefined if there is no intersection.
* @param span The span to check.
*/
intersection(span: TextSpan): TextSpan;
/**
* Creates a new TextSpan from the given start and end positions
* as opposed to a position and length.
*/
static fromBounds(start: number, end: number): TextSpan;
}
class TextChangeRange {
static unchanged: TextChangeRange;
private _span;
private _newLength;
/**
* Initializes a new instance of TextChangeRange.
*/
constructor(span: TextSpan, newLength: number);
/**
* The span of text before the edit which is being changed
*/
span(): TextSpan;
/**
* Width of the span after the edit. A 0 here would represent a delete
*/
newLength(): number;
newSpan(): TextSpan;
isUnchanged(): boolean;
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
static collapseChangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
}
interface ClassifiedSpan {
textSpan: TextSpan;
classificationType: string;
@ -1877,6 +1803,8 @@ declare module "typescript" {
throwIfCancellationRequested(): void;
}
function createLanguageServiceSourceFile(filename: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, isOpen: boolean, setNodeParents: boolean): SourceFile;
var disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile;
function createDocumentRegistry(): DocumentRegistry;
function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry: DocumentRegistry): LanguageService;

View file

@ -189,29 +189,29 @@ declare module ts {
ConditionalExpression = 164,
TemplateExpression = 165,
YieldExpression = 166,
OmittedExpression = 167,
TemplateSpan = 168,
Block = 169,
VariableStatement = 170,
EmptyStatement = 171,
ExpressionStatement = 172,
IfStatement = 173,
DoStatement = 174,
WhileStatement = 175,
ForStatement = 176,
ForInStatement = 177,
ContinueStatement = 178,
BreakStatement = 179,
ReturnStatement = 180,
WithStatement = 181,
SwitchStatement = 182,
LabeledStatement = 183,
ThrowStatement = 184,
TryStatement = 185,
TryBlock = 186,
FinallyBlock = 187,
DebuggerStatement = 188,
VariableDeclaration = 189,
SpreadElementExpression = 167,
OmittedExpression = 168,
TemplateSpan = 169,
Block = 170,
VariableStatement = 171,
EmptyStatement = 172,
ExpressionStatement = 173,
IfStatement = 174,
DoStatement = 175,
WhileStatement = 176,
ForStatement = 177,
ForInStatement = 178,
ContinueStatement = 179,
BreakStatement = 180,
ReturnStatement = 181,
WithStatement = 182,
SwitchStatement = 183,
LabeledStatement = 184,
ThrowStatement = 185,
TryStatement = 186,
DebuggerStatement = 187,
VariableDeclaration = 188,
VariableDeclarationList = 189,
FunctionDeclaration = 190,
ClassDeclaration = 191,
InterfaceDeclaration = 192,
@ -230,9 +230,8 @@ declare module ts {
ShorthandPropertyAssignment = 205,
EnumMember = 206,
SourceFile = 207,
Program = 208,
SyntaxList = 209,
Count = 210,
SyntaxList = 208,
Count = 209,
FirstAssignment = 52,
LastAssignment = 63,
FirstReservedWord = 65,
@ -253,8 +252,6 @@ declare module ts {
LastLiteralToken = 10,
FirstTemplateToken = 10,
LastTemplateToken = 13,
FirstOperator = 22,
LastOperator = 63,
FirstBinaryOperator = 24,
LastBinaryOperator = 63,
FirstNode = 121,
@ -331,10 +328,14 @@ declare module ts {
type?: TypeNode;
}
interface VariableDeclaration extends Declaration {
parent?: VariableDeclarationList;
name: Identifier | BindingPattern;
type?: TypeNode;
initializer?: Expression;
}
interface VariableDeclarationList extends Node {
declarations: NodeArray<VariableDeclaration>;
}
interface ParameterDeclaration extends Declaration {
dotDotDotToken?: Node;
name: Identifier | BindingPattern;
@ -514,6 +515,9 @@ declare module ts {
interface ArrayLiteralExpression extends PrimaryExpression {
elements: NodeArray<Expression>;
}
interface SpreadElementExpression extends Expression {
expression: Expression;
}
interface ObjectLiteralExpression extends PrimaryExpression, Declaration {
properties: NodeArray<ObjectLiteralElement>;
}
@ -548,7 +552,7 @@ declare module ts {
statements: NodeArray<Statement>;
}
interface VariableStatement extends Statement {
declarations: NodeArray<VariableDeclaration>;
declarationList: VariableDeclarationList;
}
interface ExpressionStatement extends Statement {
expression: Expression;
@ -568,14 +572,12 @@ declare module ts {
expression: Expression;
}
interface ForStatement extends IterationStatement {
declarations?: NodeArray<VariableDeclaration>;
initializer?: Expression;
initializer?: VariableDeclarationList | Expression;
condition?: Expression;
iterator?: Expression;
}
interface ForInStatement extends IterationStatement {
declarations?: NodeArray<VariableDeclaration>;
variable?: Expression;
initializer: VariableDeclarationList | Expression;
expression: Expression;
}
interface BreakOrContinueStatement extends Statement {
@ -682,12 +684,12 @@ declare module ts {
getLineAndCharacterFromPosition(position: number): LineAndCharacter;
getPositionFromLineAndCharacter(line: number, character: number): number;
getLineStarts(): number[];
update(newText: string, textChangeRange: TextChangeRange): SourceFile;
amdDependencies: string[];
amdModuleName: string;
referencedFiles: FileReference[];
referenceDiagnostics: Diagnostic[];
parseDiagnostics: Diagnostic[];
grammarDiagnostics: Diagnostic[];
getSyntacticDiagnostics(): Diagnostic[];
semanticDiagnostics: Diagnostic[];
hasNoDefaultLib: boolean;
@ -698,15 +700,21 @@ declare module ts {
languageVersion: ScriptTarget;
identifiers: Map<string>;
}
interface Program {
getSourceFile(filename: string): SourceFile;
getSourceFiles(): SourceFile[];
interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(filename: string): SourceFile;
getCurrentDirectory(): string;
}
interface Program extends ScriptReferenceHost {
getSourceFiles(): SourceFile[];
getCompilerHost(): CompilerHost;
getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getTypeChecker(fullTypeCheckMode: boolean): TypeChecker;
getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[];
getTypeChecker(produceDiagnostics: boolean): TypeChecker;
getCommonSourceDirectory(): string;
emitFiles(targetSourceFile?: SourceFile): EmitResult;
isEmitBlocked(sourceFile?: SourceFile): boolean;
}
interface SourceMapSpan {
emittedLine: number;
@ -740,16 +748,20 @@ declare module ts {
diagnostics: Diagnostic[];
sourceMaps: SourceMapData[];
}
interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
getCompilerHost(): CompilerHost;
getSourceFiles(): SourceFile[];
getSourceFile(filename: string): SourceFile;
}
interface TypeChecker {
getProgram(): Program;
getEmitResolver(): EmitResolver;
getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getNodeCount(): number;
getIdentifierCount(): number;
getSymbolCount(): number;
getTypeCount(): number;
emitFiles(targetSourceFile?: SourceFile): EmitResult;
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
@ -773,7 +785,6 @@ declare module ts {
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isEmitBlocked(sourceFile?: SourceFile): boolean;
getEnumMemberValue(node: EnumMember): number;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
getAliasedSymbol(symbol: Symbol): Symbol;
@ -833,7 +844,6 @@ declare module ts {
errorModuleName?: string;
}
interface EmitResolver {
getProgram(): Program;
getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string;
getExpressionNamePrefix(node: Identifier): string;
getExportAssignmentName(node: SourceFile): string;
@ -849,7 +859,6 @@ declare module ts {
isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessiblityResult;
isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult;
getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number;
isEmitBlocked(sourceFile?: SourceFile): boolean;
isUnknownIdentifier(location: Node, name: string): boolean;
}
const enum SymbolFlags {
@ -1119,6 +1128,7 @@ declare module ts {
locale?: string;
mapRoot?: string;
module?: ModuleKind;
noEmit?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
@ -1303,13 +1313,18 @@ declare module ts {
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
}
interface TextSpan {
start: number;
length: number;
}
interface TextChangeRange {
span: TextSpan;
newLength: number;
}
}
declare module ts {
interface ErrorCallback {
(message: DiagnosticMessage): void;
}
interface CommentCallback {
(pos: number, end: number): void;
(message: DiagnosticMessage, length: number): void;
}
interface Scanner {
getStartPos(): number;
@ -1356,16 +1371,18 @@ declare module ts {
function getNodeConstructor(kind: SyntaxKind): new () => Node;
function createNode(kind: SyntaxKind): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodes?: (nodes: Node[]) => T): T;
function createCompilerHost(options: CompilerOptions): CompilerHost;
function modifierToFlag(token: SyntaxKind): NodeFlags;
function isEvalOrArgumentsIdentifier(node: Node): boolean;
function createSourceFile(filename: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
function isLeftHandSideExpression(expr: Expression): boolean;
function isAssignmentOperator(token: SyntaxKind): boolean;
function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program;
}
declare module ts {
function createTypeChecker(program: Program, fullTypeCheck: boolean): TypeChecker;
function createTypeChecker(host: TypeCheckerHost, produceDiagnostics: boolean): TypeChecker;
}
declare module ts {
function createCompilerHost(options: CompilerOptions): CompilerHost;
function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program;
}
declare module ts {
var servicesVersion: string;
@ -1412,9 +1429,8 @@ declare module ts {
interface SourceFile {
isOpen: boolean;
version: string;
getScriptSnapshot(): IScriptSnapshot;
scriptSnapshot: IScriptSnapshot;
getNamedDeclarations(): Declaration[];
update(scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile;
}
/**
* Represents an immutable snapshot of a script at a specified time.Once acquired, the
@ -1496,96 +1512,6 @@ declare module ts {
getSourceFile(filename: string): SourceFile;
dispose(): void;
}
class TextSpan {
private _start;
private _length;
/**
* Creates a TextSpan instance beginning with the position Start and having the Length
* specified with length.
*/
constructor(start: number, length: number);
toJSON(key: any): any;
start(): number;
length(): number;
end(): number;
isEmpty(): boolean;
/**
* Determines whether the position lies within the span. Returns true if the position is greater than or equal to Start and strictly less
* than End, otherwise false.
* @param position The position to check.
*/
containsPosition(position: number): boolean;
/**
* Determines whether span falls completely within this span. Returns true if the specified span falls completely within this span, otherwise false.
* @param span The span to check.
*/
containsTextSpan(span: TextSpan): boolean;
/**
* Determines whether the given span overlaps this span. Two spans are considered to overlap
* if they have positions in common and neither is empty. Empty spans do not overlap with any
* other span. Returns true if the spans overlap, false otherwise.
* @param span The span to check.
*/
overlapsWith(span: TextSpan): boolean;
/**
* Returns the overlap with the given span, or undefined if there is no overlap.
* @param span The span to check.
*/
overlap(span: TextSpan): TextSpan;
/**
* Determines whether span intersects this span. Two spans are considered to
* intersect if they have positions in common or the end of one span
* coincides with the start of the other span. Returns true if the spans intersect, false otherwise.
* @param The span to check.
*/
intersectsWithTextSpan(span: TextSpan): boolean;
intersectsWith(start: number, length: number): boolean;
/**
* Determines whether the given position intersects this span.
* A position is considered to intersect if it is between the start and
* end positions (inclusive) of this span. Returns true if the position intersects, false otherwise.
* @param position The position to check.
*/
intersectsWithPosition(position: number): boolean;
/**
* Returns the intersection with the given span, or undefined if there is no intersection.
* @param span The span to check.
*/
intersection(span: TextSpan): TextSpan;
/**
* Creates a new TextSpan from the given start and end positions
* as opposed to a position and length.
*/
static fromBounds(start: number, end: number): TextSpan;
}
class TextChangeRange {
static unchanged: TextChangeRange;
private _span;
private _newLength;
/**
* Initializes a new instance of TextChangeRange.
*/
constructor(span: TextSpan, newLength: number);
/**
* The span of text before the edit which is being changed
*/
span(): TextSpan;
/**
* Width of the span after the edit. A 0 here would represent a delete
*/
newLength(): number;
newSpan(): TextSpan;
isUnchanged(): boolean;
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
static collapseChangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
}
interface ClassifiedSpan {
textSpan: TextSpan;
classificationType: string;
@ -1877,6 +1803,8 @@ declare module ts {
throwIfCancellationRequested(): void;
}
function createLanguageServiceSourceFile(filename: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, isOpen: boolean, setNodeParents: boolean): SourceFile;
var disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, isOpen: boolean, textChangeRange: TextChangeRange): SourceFile;
function createDocumentRegistry(): DocumentRegistry;
function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry: DocumentRegistry): LanguageService;

File diff suppressed because it is too large Load diff

View file

@ -26,7 +26,7 @@ declare module ts {
}
interface StringSet extends Map<any> {
}
function forEach<T, U>(array: T[], callback: (element: T) => U): U;
function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U;
function contains<T>(array: T[], value: T): boolean;
function indexOf<T>(array: T[], value: T): number;
function countWhere<T>(array: T[], predicate: (x: T) => boolean): number;
@ -149,7 +149,8 @@ declare module ts {
function getSourceFileOfNode(node: Node): SourceFile;
function nodePosToString(node: Node): string;
function getStartPosOfNode(node: Node): number;
function isMissingNode(node: Node): boolean;
function nodeIsMissing(node: Node): boolean;
function nodeIsPresent(node: Node): boolean;
function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number;
function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string;
function getTextOfNodeFromSourceText(sourceText: string, node: Node): string;
@ -163,6 +164,7 @@ declare module ts {
function isExternalModule(file: SourceFile): boolean;
function isDeclarationFile(file: SourceFile): boolean;
function isConstEnumDeclaration(node: Node): boolean;
function getCombinedNodeFlags(node: Node): NodeFlags;
function isConst(node: Node): boolean;
function isLet(node: Node): boolean;
function isPrologueDirective(node: Node): boolean;
@ -196,12 +198,38 @@ declare module ts {
function getClassImplementedTypeNodes(node: ClassDeclaration): NodeArray<TypeReferenceNode>;
function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray<TypeReferenceNode>;
function getHeritageClause(clauses: NodeArray<HeritageClause>, kind: SyntaxKind): HeritageClause;
function tryResolveScriptReference(program: Program, sourceFile: SourceFile, reference: FileReference): SourceFile;
function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile;
function getAncestor(node: Node, kind: SyntaxKind): Node;
function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult;
function isKeyword(token: SyntaxKind): boolean;
function isTrivia(token: SyntaxKind): boolean;
function isModifier(token: SyntaxKind): boolean;
function createEmitHostFromProgram(program: Program): EmitHost;
function textSpanEnd(span: TextSpan): number;
function textSpanIsEmpty(span: TextSpan): boolean;
function textSpanContainsPosition(span: TextSpan, position: number): boolean;
function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan;
function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean;
function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean;
function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan;
function createTextSpan(start: number, length: number): TextSpan;
function createTextSpanFromBounds(start: number, end: number): TextSpan;
function textChangeRangeNewSpan(range: TextChangeRange): TextSpan;
function textChangeRangeIsUnchanged(range: TextChangeRange): boolean;
function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange;
var unchangedTextChangeRange: TextChangeRange;
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
}
declare module ts {
interface ListItemInfo {

View file

@ -26,7 +26,7 @@ declare module "typescript" {
}
interface StringSet extends Map<any> {
}
function forEach<T, U>(array: T[], callback: (element: T) => U): U;
function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U;
function contains<T>(array: T[], value: T): boolean;
function indexOf<T>(array: T[], value: T): number;
function countWhere<T>(array: T[], predicate: (x: T) => boolean): number;
@ -149,7 +149,8 @@ declare module "typescript" {
function getSourceFileOfNode(node: Node): SourceFile;
function nodePosToString(node: Node): string;
function getStartPosOfNode(node: Node): number;
function isMissingNode(node: Node): boolean;
function nodeIsMissing(node: Node): boolean;
function nodeIsPresent(node: Node): boolean;
function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number;
function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string;
function getTextOfNodeFromSourceText(sourceText: string, node: Node): string;
@ -163,6 +164,7 @@ declare module "typescript" {
function isExternalModule(file: SourceFile): boolean;
function isDeclarationFile(file: SourceFile): boolean;
function isConstEnumDeclaration(node: Node): boolean;
function getCombinedNodeFlags(node: Node): NodeFlags;
function isConst(node: Node): boolean;
function isLet(node: Node): boolean;
function isPrologueDirective(node: Node): boolean;
@ -196,12 +198,38 @@ declare module "typescript" {
function getClassImplementedTypeNodes(node: ClassDeclaration): NodeArray<TypeReferenceNode>;
function getInterfaceBaseTypeNodes(node: InterfaceDeclaration): NodeArray<TypeReferenceNode>;
function getHeritageClause(clauses: NodeArray<HeritageClause>, kind: SyntaxKind): HeritageClause;
function tryResolveScriptReference(program: Program, sourceFile: SourceFile, reference: FileReference): SourceFile;
function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference): SourceFile;
function getAncestor(node: Node, kind: SyntaxKind): Node;
function getFileReferenceFromReferencePath(comment: string, commentRange: CommentRange): ReferencePathMatchResult;
function isKeyword(token: SyntaxKind): boolean;
function isTrivia(token: SyntaxKind): boolean;
function isModifier(token: SyntaxKind): boolean;
function createEmitHostFromProgram(program: Program): EmitHost;
function textSpanEnd(span: TextSpan): number;
function textSpanIsEmpty(span: TextSpan): boolean;
function textSpanContainsPosition(span: TextSpan, position: number): boolean;
function textSpanContainsTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlapsWith(span: TextSpan, other: TextSpan): boolean;
function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan;
function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean;
function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean;
function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan;
function createTextSpan(start: number, length: number): TextSpan;
function createTextSpanFromBounds(start: number, end: number): TextSpan;
function textChangeRangeNewSpan(range: TextChangeRange): TextSpan;
function textChangeRangeIsUnchanged(range: TextChangeRange): boolean;
function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange;
var unchangedTextChangeRange: TextChangeRange;
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
}
declare module "typescript" {
interface ListItemInfo {

View file

@ -1,10 +1,6 @@
/// <reference path="types.ts"/>
/// <reference path="core.ts"/>
/// <reference path="scanner.ts"/>
/// <reference path="parser.ts"/>
module ts {
export const enum ModuleInstanceState {
NonInstantiated = 0,
Instantiated = 1,
@ -206,7 +202,8 @@ module ts {
if (symbolKind & SymbolFlags.Namespace) {
exportKind |= SymbolFlags.ExportNamespace;
}
if (node.flags & NodeFlags.Export || (node.kind !== SyntaxKind.ImportDeclaration && isAmbientContext(container))) {
if (getCombinedNodeFlags(node) & NodeFlags.Export || (node.kind !== SyntaxKind.ImportDeclaration && isAmbientContext(container))) {
if (exportKind) {
var local = declareSymbol(container.locals, undefined, node, exportKind, symbolExcludes);
local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolKind, symbolExcludes);
@ -234,10 +231,8 @@ module ts {
parent = node;
if (symbolKind & SymbolFlags.IsContainer) {
container = node;
Debug.assert(container.nextContainer === undefined);
if (lastContainer) {
Debug.assert(lastContainer.nextContainer === undefined);
lastContainer.nextContainer = container;
}
@ -391,7 +386,7 @@ module ts {
if (isBindingPattern((<Declaration>node).name)) {
bindChildren(node, 0, /*isBlockScopeContainer*/ false);
}
else if (node.flags & NodeFlags.BlockScoped) {
else if (getCombinedNodeFlags(node) & NodeFlags.BlockScoped) {
bindBlockScopedVariableDeclaration(<Declaration>node);
}
else {
@ -483,9 +478,7 @@ module ts {
break;
}
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.SwitchStatement:

File diff suppressed because it is too large Load diff

View file

@ -54,6 +54,11 @@ module ts {
paramType: Diagnostics.KIND,
error: Diagnostics.Argument_for_module_option_must_be_commonjs_or_amd
},
{
name: "noEmit",
type: "boolean",
description: Diagnostics.Do_not_emit_outputs,
},
{
name: "noEmitOnError",
type: "boolean",

View file

@ -23,10 +23,10 @@ module ts {
export interface StringSet extends Map<any> { }
export function forEach<T, U>(array: T[], callback: (element: T) => U): U {
export function forEach<T, U>(array: T[], callback: (element: T, index: number) => U): U {
if (array) {
for (var i = 0, len = array.length; i < len; i++) {
var result = callback(array[i]);
var result = callback(array[i], i);
if (result) {
return result;
}
@ -208,6 +208,12 @@ module ts {
return result;
}
export function copyMap<T>(source: Map<T>, target: Map<T>): void {
for (var p in source) {
target[p] = source[p];
}
}
/**
* Creates a map from the elements of an array.
*

View file

@ -143,8 +143,9 @@ module ts {
A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer.", isEarly: true },
Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: DiagnosticCategory.Error, key: "Destructuring declarations are not allowed in ambient contexts.", isEarly: true },
An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts.", isEarly: true },
Merge_conflict_marker_encountered: { code: 1184, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." },
A_rest_element_cannot_have_an_initializer: { code: 1185, category: DiagnosticCategory.Error, key: "A rest element cannot have an initializer." },
Modifiers_cannot_appear_here: { code: 1184, category: DiagnosticCategory.Error, key: "Modifiers cannot appear here." },
Merge_conflict_marker_encountered: { code: 1185, category: DiagnosticCategory.Error, key: "Merge conflict marker encountered." },
A_rest_element_cannot_have_an_initializer: { code: 1186, category: DiagnosticCategory.Error, key: "A rest element cannot have an initializer." },
Duplicate_identifier_0: { code: 2300, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'." },
Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: { code: 2301, category: DiagnosticCategory.Error, key: "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor." },
Static_members_cannot_reference_class_type_parameters: { code: 2302, category: DiagnosticCategory.Error, key: "Static members cannot reference class type parameters." },
@ -379,6 +380,8 @@ module ts {
Could_not_write_file_0_Colon_1: { code: 5033, category: DiagnosticCategory.Error, key: "Could not write file '{0}': {1}" },
Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5038, category: DiagnosticCategory.Error, key: "Option mapRoot cannot be specified without specifying sourcemap option." },
Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option: { code: 5039, category: DiagnosticCategory.Error, key: "Option sourceRoot cannot be specified without specifying sourcemap option." },
Option_noEmit_cannot_be_specified_with_option_out_or_outDir: { code: 5040, category: DiagnosticCategory.Error, key: "Option noEmit cannot be specified with option out or outDir." },
Option_noEmit_cannot_be_specified_with_option_declaration: { code: 5041, category: DiagnosticCategory.Error, key: "Option noEmit cannot be specified with option declaration." },
Concatenate_and_emit_output_to_single_file: { code: 6001, category: DiagnosticCategory.Message, key: "Concatenate and emit output to single file." },
Generates_corresponding_d_ts_file: { code: 6002, category: DiagnosticCategory.Message, key: "Generates corresponding '.d.ts' file." },
Specifies_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations: { code: 6003, category: DiagnosticCategory.Message, key: "Specifies the location where debugger should locate map files instead of generated locations." },
@ -388,6 +391,7 @@ module ts {
Do_not_erase_const_enum_declarations_in_generated_code: { code: 6007, category: DiagnosticCategory.Message, key: "Do not erase const enum declarations in generated code." },
Do_not_emit_outputs_if_any_type_checking_errors_were_reported: { code: 6008, category: DiagnosticCategory.Message, key: "Do not emit outputs if any type checking errors were reported." },
Do_not_emit_comments_to_output: { code: 6009, category: DiagnosticCategory.Message, key: "Do not emit comments to output." },
Do_not_emit_outputs: { code: 6010, category: DiagnosticCategory.Message, key: "Do not emit outputs." },
Specify_ECMAScript_target_version_Colon_ES3_default_ES5_or_ES6_experimental: { code: 6015, category: DiagnosticCategory.Message, key: "Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)" },
Specify_module_code_generation_Colon_commonjs_or_amd: { code: 6016, category: DiagnosticCategory.Message, key: "Specify module code generation: 'commonjs' or 'amd'" },
Print_this_message: { code: 6017, category: DiagnosticCategory.Message, key: "Print this message." },

View file

@ -661,14 +661,18 @@
"code": 1184,
"isEarly": true
},
"Merge conflict marker encountered.": {
"Modifiers cannot appear here.": {
"category": "Error",
"code": 1184
},
"A rest element cannot have an initializer.": {
"Merge conflict marker encountered.": {
"category": "Error",
"code": 1185
},
"A rest element cannot have an initializer.": {
"category": "Error",
"code": 1186
},
"Duplicate identifier '{0}'.": {
"category": "Error",
@ -1612,6 +1616,14 @@
"category": "Error",
"code": 5039
},
"Option noEmit cannot be specified with option out or outDir.": {
"category": "Error",
"code": 5040
},
"Option noEmit cannot be specified with option declaration.": {
"category": "Error",
"code": 5041
},
"Concatenate and emit output to single file.": {
"category": "Message",
"code": 6001
@ -1648,6 +1660,10 @@
"category": "Message",
"code": 6009
},
"Do not emit outputs.": {
"category": "Message",
"code": 6010
},
"Specify ECMAScript target version: 'ES3' (default), 'ES5', or 'ES6' (experimental)": {
"category": "Message",
"code": 6015

View file

@ -1,8 +1,4 @@
/// <reference path="types.ts"/>
/// <reference path="core.ts"/>
/// <reference path="scanner.ts"/>
/// <reference path="parser.ts"/>
/// <reference path="binder.ts"/>
/// <reference path="checker.ts"/>
module ts {
interface EmitTextWriter {
@ -268,7 +264,7 @@ module ts {
function getFirstConstructorWithBody(node: ClassDeclaration): ConstructorDeclaration {
return forEach(node.members, member => {
if (member.kind === SyntaxKind.Constructor && (<ConstructorDeclaration>member).body) {
if (member.kind === SyntaxKind.Constructor && nodeIsPresent((<ConstructorDeclaration>member).body)) {
return <ConstructorDeclaration>member;
}
});
@ -316,17 +312,16 @@ module ts {
};
}
function getSourceFilePathInNewDir(sourceFile: SourceFile, program: Program, newDirPath: string) {
var compilerHost = program.getCompilerHost();
var sourceFilePath = getNormalizedAbsolutePath(sourceFile.filename, compilerHost.getCurrentDirectory());
sourceFilePath = sourceFilePath.replace(program.getCommonSourceDirectory(), "");
function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string) {
var sourceFilePath = getNormalizedAbsolutePath(sourceFile.filename, host.getCurrentDirectory());
sourceFilePath = sourceFilePath.replace(host.getCommonSourceDirectory(), "");
return combinePaths(newDirPath, sourceFilePath);
}
function getOwnEmitOutputFilePath(sourceFile: SourceFile, program: Program, extension: string){
var compilerOptions = program.getCompilerOptions();
function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string){
var compilerOptions = host.getCompilerOptions();
if (compilerOptions.outDir) {
var emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, program, compilerOptions.outDir));
var emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(sourceFile, host, compilerOptions.outDir));
}
else {
var emitOutputFilePathWithoutExtension = removeFileExtension(sourceFile.filename);
@ -335,16 +330,15 @@ module ts {
return emitOutputFilePathWithoutExtension + extension;
}
function writeFile(compilerHost: CompilerHost, diagnostics: Diagnostic[], filename: string, data: string, writeByteOrderMark: boolean) {
compilerHost.writeFile(filename, data, writeByteOrderMark, hostErrorMessage => {
function writeFile(host: EmitHost, diagnostics: Diagnostic[], filename: string, data: string, writeByteOrderMark: boolean) {
host.writeFile(filename, data, writeByteOrderMark, hostErrorMessage => {
diagnostics.push(createCompilerDiagnostic(Diagnostics.Could_not_write_file_0_Colon_1, filename, hostErrorMessage));
});
}
function emitDeclarations(program: Program, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit {
var newLine = program.getCompilerHost().getNewLine();
var compilerOptions = program.getCompilerOptions();
var compilerHost = program.getCompilerHost();
function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit {
var newLine = host.getNewLine();
var compilerOptions = host.getCompilerOptions();
var write: (s: string) => void;
var writeLine: () => void;
@ -1014,20 +1008,20 @@ module ts {
}
function emitVariableStatement(node: VariableStatement) {
var hasDeclarationWithEmit = forEach(node.declarations, varDeclaration => resolver.isDeclarationVisible(varDeclaration));
var hasDeclarationWithEmit = forEach(node.declarationList.declarations, varDeclaration => resolver.isDeclarationVisible(varDeclaration));
if (hasDeclarationWithEmit) {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
if (isLet(node)) {
if (isLet(node.declarationList)) {
write("let ");
}
else if (isConst(node)) {
else if (isConst(node.declarationList)) {
write("const ");
}
else {
write("var ");
}
emitCommaList(node.declarations, emitVariableDeclaration);
emitCommaList(node.declarationList.declarations, emitVariableDeclaration);
write(";");
writeLine();
}
@ -1400,14 +1394,14 @@ module ts {
var declFileName = referencedFile.flags & NodeFlags.DeclarationFile
? referencedFile.filename // Declaration file, use declaration file name
: shouldEmitToOwnFile(referencedFile, compilerOptions)
? getOwnEmitOutputFilePath(referencedFile, program, ".d.ts") // Own output file so get the .d.ts file
: removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file
? getOwnEmitOutputFilePath(referencedFile, host, ".d.ts") // Own output file so get the .d.ts file
: removeFileExtension(compilerOptions.out) + ".d.ts";// Global out file
declFileName = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizeSlashes(jsFilePath)),
declFileName,
compilerHost.getCurrentDirectory(),
compilerHost.getCanonicalFileName,
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ false);
referencePathsOutput += "/// <reference path=\"" + declFileName + "\" />" + newLine;
@ -1418,7 +1412,7 @@ module ts {
if (!compilerOptions.noResolve) {
var addedGlobalFileReference = false;
forEach(root.referencedFiles, fileReference => {
var referencedFile = tryResolveScriptReference(program, root, fileReference);
var referencedFile = tryResolveScriptReference(host, root, fileReference);
// All the references that are not going to be part of same file
if (referencedFile && ((referencedFile.flags & NodeFlags.DeclarationFile) || // This is a declare file reference
@ -1438,12 +1432,12 @@ module ts {
else {
// Emit references corresponding to this file
var emittedReferencedFiles: SourceFile[] = [];
forEach(program.getSourceFiles(), sourceFile => {
forEach(host.getSourceFiles(), sourceFile => {
if (!isExternalModuleOrDeclarationFile(sourceFile)) {
// Check what references need to be added
if (!compilerOptions.noResolve) {
forEach(sourceFile.referencedFiles, fileReference => {
var referencedFile = tryResolveScriptReference(program, sourceFile, fileReference);
var referencedFile = tryResolveScriptReference(host, sourceFile, fileReference);
// If the reference file is a declaration file or an external module, emit that reference
if (referencedFile && (isExternalModuleOrDeclarationFile(referencedFile) &&
@ -1467,22 +1461,21 @@ module ts {
referencePathsOutput,
}
}
export function getDeclarationDiagnostics(program: Program, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {
export function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[] {
var diagnostics: Diagnostic[] = [];
var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js");
emitDeclarations(program, resolver, diagnostics, jsFilePath, targetSourceFile);
var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js");
emitDeclarations(host, resolver, diagnostics, jsFilePath, targetSourceFile);
return diagnostics;
}
// targetSourceFile is when users only want one file in entire project to be emitted. This is used in compilerOnSave feature
export function emitFiles(resolver: EmitResolver, targetSourceFile?: SourceFile): EmitResult {
var program = resolver.getProgram();
var compilerHost = program.getCompilerHost();
var compilerOptions = program.getCompilerOptions();
export function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile?: SourceFile): EmitResult {
// var program = resolver.getProgram();
var compilerOptions = host.getCompilerOptions();
var sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap ? [] : undefined;
var diagnostics: Diagnostic[] = [];
var newLine = program.getCompilerHost().getNewLine();
var newLine = host.getNewLine();
function emitJavaScript(jsFilePath: string, root?: SourceFile) {
var writer = createTextWriter(newLine);
@ -1704,12 +1697,12 @@ module ts {
// Add the file to tsFilePaths
// If sourceroot option: Use the relative path corresponding to the common directory path
// otherwise source locations relative to map file location
var sourcesDirectoryPath = compilerOptions.sourceRoot ? program.getCommonSourceDirectory() : sourceMapDir;
var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir;
sourceMapData.sourceMapSources.push(getRelativePathToDirectoryOrUrl(sourcesDirectoryPath,
node.filename,
compilerHost.getCurrentDirectory(),
compilerHost.getCanonicalFileName,
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true));
sourceMapSourceIndex = sourceMapData.sourceMapSources.length - 1;
@ -1805,7 +1798,7 @@ module ts {
function writeJavaScriptAndSourceMapFile(emitOutput: string, writeByteOrderMark: boolean) {
// Write source map file
encodeLastRecordedSourceMapSpan();
writeFile(compilerHost, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents(
writeFile(host, diagnostics, sourceMapData.sourceMapFilePath, serializeSourceMapContents(
3,
sourceMapData.sourceMapFile,
sourceMapData.sourceMapSourceRoot,
@ -1844,17 +1837,17 @@ module ts {
if (root) { // emitting single module file
// For modules or multiple emit files the mapRoot will have directory structure like the sources
// So if src\a.ts and src\lib\b.ts are compiled together user would be moving the maps into mapRoot\a.js.map and mapRoot\lib\b.js.map
sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(root, program, sourceMapDir));
sourceMapDir = getDirectoryPath(getSourceFilePathInNewDir(root, host, sourceMapDir));
}
if (!isRootedDiskPath(sourceMapDir) && !isUrl(sourceMapDir)) {
// The relative paths are relative to the common directory
sourceMapDir = combinePaths(program.getCommonSourceDirectory(), sourceMapDir);
sourceMapDir = combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
sourceMapData.jsSourceMappingURL = getRelativePathToDirectoryOrUrl(
getDirectoryPath(normalizePath(jsFilePath)), // get the relative sourceMapDir path based on jsFilePath
combinePaths(sourceMapDir, sourceMapData.jsSourceMappingURL), // this is where user expects to see sourceMap
compilerHost.getCurrentDirectory(),
compilerHost.getCanonicalFileName,
host.getCurrentDirectory(),
host.getCanonicalFileName,
/*isAbsolutePathAnUrl*/ true);
}
else {
@ -1890,7 +1883,7 @@ module ts {
}
function writeJavaScriptFile(emitOutput: string, writeByteOrderMark: boolean) {
writeFile(compilerHost, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
writeFile(host, diagnostics, jsFilePath, emitOutput, writeByteOrderMark);
}
// Create a temporary variable with a unique unused name. The forLoopVariable parameter signals that the
@ -2064,9 +2057,15 @@ module ts {
write("(");
}
emitLiteral(node.head);
var headEmitted = false;
if (shouldEmitTemplateHead()) {
emitLiteral(node.head);
headEmitted = true;
}
for (var i = 0; i < node.templateSpans.length; i++) {
var templateSpan = node.templateSpans[i];
forEach(node.templateSpans, templateSpan => {
// Check if the expression has operands and binds its operands less closely than binary '+'.
// If it does, we need to wrap the expression in parentheses. Otherwise, something like
// `abc${ 1 << 2 }`
@ -2078,7 +2077,14 @@ module ts {
// "abc" + (1 << 2) + ""
var needsParens = templateSpan.expression.kind !== SyntaxKind.ParenthesizedExpression
&& comparePrecedenceToBinaryPlus(templateSpan.expression) !== Comparison.GreaterThan;
write(" + ");
if (i > 0 || headEmitted) {
// If this is the first span and the head was not emitted, then this templateSpan's
// expression will be the first to be emitted. Don't emit the preceding ' + ' in that
// case.
write(" + ");
}
emitParenthesized(templateSpan.expression, needsParens);
// Only emit if the literal is non-empty.
// The binary '+' operator is left-associative, so the first string concatenation
@ -2088,12 +2094,34 @@ module ts {
write(" + ")
emitLiteral(templateSpan.literal);
}
});
}
if (emitOuterParens) {
write(")");
}
function shouldEmitTemplateHead() {
// If this expression has an empty head literal and the first template span has a non-empty
// literal, then emitting the empty head literal is not necessary.
// `${ foo } and ${ bar }`
// can be emitted as
// foo + " and " + bar
// This is because it is only required that one of the first two operands in the emit
// output must be a string literal, so that the other operand and all following operands
// are forced into strings.
//
// If the first template span has an empty literal, then the head must still be emitted.
// `${ foo }${ bar }`
// must still be emitted as
// "" + foo + bar
// There is always atleast one templateSpan in this code path, since
// NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
Debug.assert(node.templateSpans.length !== 0);
return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
}
function templateNeedsParens(template: TemplateExpression, parent: Expression) {
switch (parent.kind) {
case SyntaxKind.CallExpression:
@ -2113,7 +2141,8 @@ module ts {
* or equal precedence to the binary '+' operator
*/
function comparePrecedenceToBinaryPlus(expression: Expression): Comparison {
// All binary expressions have lower precedence than '+' apart from '*', '/', and '%'.
// All binary expressions have lower precedence than '+' apart from '*', '/', and '%'
// which have greater precedence and '-' which has equal precedence.
// All unary operators have a higher precedence apart from yield.
// Arrow functions and conditionals have a lower precedence,
// although we convert the former into regular function expressions in ES5 mode,
@ -2130,6 +2159,7 @@ module ts {
case SyntaxKind.PercentToken:
return Comparison.GreaterThan;
case SyntaxKind.PlusToken:
case SyntaxKind.MinusToken:
return Comparison.EqualTo;
default:
return Comparison.LessThan;
@ -2681,20 +2711,22 @@ module ts {
var endPos = emitToken(SyntaxKind.ForKeyword, node.pos);
write(" ");
endPos = emitToken(SyntaxKind.OpenParenToken, endPos);
if (node.declarations) {
if (node.declarations[0] && isLet(node.declarations[0])) {
if (node.initializer && node.initializer.kind === SyntaxKind.VariableDeclarationList) {
var variableDeclarationList = <VariableDeclarationList>node.initializer;
var declarations = variableDeclarationList.declarations;
if (declarations[0] && isLet(declarations[0])) {
emitToken(SyntaxKind.LetKeyword, endPos);
}
else if (node.declarations[0] && isConst(node.declarations[0])) {
else if (declarations[0] && isConst(declarations[0])) {
emitToken(SyntaxKind.ConstKeyword, endPos);
}
else {
emitToken(SyntaxKind.VarKeyword, endPos);
}
write(" ");
emitCommaList(node.declarations);
emitCommaList(variableDeclarationList.declarations);
}
if (node.initializer) {
else if (node.initializer) {
emit(node.initializer);
}
write(";");
@ -2709,9 +2741,10 @@ module ts {
var endPos = emitToken(SyntaxKind.ForKeyword, node.pos);
write(" ");
endPos = emitToken(SyntaxKind.OpenParenToken, endPos);
if (node.declarations) {
if (node.declarations.length >= 1) {
var decl = node.declarations[0];
if (node.initializer.kind === SyntaxKind.VariableDeclarationList) {
var variableDeclarationList = <VariableDeclarationList>node.initializer;
if (variableDeclarationList.declarations.length >= 1) {
var decl = variableDeclarationList.declarations[0];
if (isLet(decl)) {
emitToken(SyntaxKind.LetKeyword, endPos);
}
@ -2723,7 +2756,7 @@ module ts {
}
}
else {
emit(node.variable);
emit(node.initializer);
}
write(" in ");
emit(node.expression);
@ -2840,7 +2873,7 @@ module ts {
function emitModuleMemberName(node: Declaration) {
emitStart(node.name);
if (node.flags & NodeFlags.Export) {
if (getCombinedNodeFlags(node) & NodeFlags.Export) {
var container = getContainingModule(node);
write(container ? resolver.getLocalNameOfContainer(container) : "exports");
write(".");
@ -2853,7 +2886,7 @@ module ts {
var emitCount = 0;
// An exported declaration is actually emitted as an assignment (to a property on the module object), so
// temporary variables in an exported declaration need to have real declarations elsewhere
var isDeclaration = (root.kind === SyntaxKind.VariableDeclaration && !(root.flags & NodeFlags.Export)) || root.kind === SyntaxKind.Parameter;
var isDeclaration = (root.kind === SyntaxKind.VariableDeclaration && !(getCombinedNodeFlags(root) & NodeFlags.Export)) || root.kind === SyntaxKind.Parameter;
if (root.kind === SyntaxKind.BinaryExpression) {
emitAssignmentExpression(<BinaryExpression>root);
}
@ -3086,17 +3119,17 @@ module ts {
function emitVariableStatement(node: VariableStatement) {
emitLeadingComments(node);
if (!(node.flags & NodeFlags.Export)) {
if (isLet(node)) {
if (isLet(node.declarationList)) {
write("let ");
}
else if (isConst(node)) {
else if (isConst(node.declarationList)) {
write("const ");
}
else {
write("var ");
}
}
emitCommaList(node.declarations);
emitCommaList(node.declarationList.declarations);
write(";");
emitTrailingComments(node);
}
@ -3204,7 +3237,7 @@ module ts {
}
function emitFunctionDeclaration(node: FunctionLikeDeclaration) {
if (!node.body) {
if (nodeIsMissing(node.body)) {
return emitPinnedOrTripleSlashComments(node);
}
@ -3677,8 +3710,8 @@ module ts {
}
function emitModuleDeclaration(node: ModuleDeclaration) {
var shouldEmit = getModuleInstanceState(node) === ModuleInstanceState.Instantiated ||
(getModuleInstanceState(node) === ModuleInstanceState.ConstEnumOnly && compilerOptions.preserveConstEnums);
// Emit only if this module is non-ambient.
var shouldEmit = isInstantiatedModule(node, compilerOptions.preserveConstEnums);
if (!shouldEmit) {
return emitPinnedOrTripleSlashComments(node);
@ -3922,6 +3955,7 @@ module ts {
if (!node) {
return;
}
if (node.flags & NodeFlags.Ambient) {
return emitPinnedOrTripleSlashComments(node);
}
@ -4014,8 +4048,6 @@ module ts {
case SyntaxKind.OmittedExpression:
return;
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
return emitBlock(<Block>node);
case SyntaxKind.VariableStatement:
@ -4213,7 +4245,7 @@ module ts {
emit(root);
}
else {
forEach(program.getSourceFiles(), sourceFile => {
forEach(host.getSourceFiles(), sourceFile => {
if (!isExternalModuleOrDeclarationFile(sourceFile)) {
emit(sourceFile);
}
@ -4225,7 +4257,7 @@ module ts {
}
function writeDeclarationFile(jsFilePath: string, sourceFile: SourceFile) {
var emitDeclarationResult = emitDeclarations(program, resolver, diagnostics, jsFilePath, sourceFile);
var emitDeclarationResult = emitDeclarations(host, resolver, diagnostics, jsFilePath, sourceFile);
// TODO(shkamat): Should we not write any declaration file if any of them can produce error,
// or should we just not write this file like we are doing now
if (!emitDeclarationResult.reportedDeclarationError) {
@ -4240,7 +4272,7 @@ module ts {
}
});
declarationOutput += emitDeclarationResult.synchronousDeclarationOutput.substring(appliedSyncOutputPos);
writeFile(compilerHost, diagnostics, removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM);
writeFile(host, diagnostics, removeFileExtension(jsFilePath) + ".d.ts", declarationOutput, compilerOptions.emitBOM);
}
}
@ -4250,11 +4282,11 @@ module ts {
if (targetSourceFile === undefined) {
// No targetSourceFile is specified (e.g. calling emitter from batch compiler)
hasSemanticErrors = resolver.hasSemanticErrors();
isEmitBlocked = resolver.isEmitBlocked();
isEmitBlocked = host.isEmitBlocked();
forEach(program.getSourceFiles(), sourceFile => {
forEach(host.getSourceFiles(), sourceFile => {
if (shouldEmitToOwnFile(sourceFile, compilerOptions)) {
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, program, ".js");
var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js");
emitFile(jsFilePath, sourceFile);
}
});
@ -4268,18 +4300,18 @@ module ts {
if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) {
// If shouldEmitToOwnFile returns true or targetSourceFile is an external module file, then emit targetSourceFile in its own output file
hasSemanticErrors = resolver.hasSemanticErrors(targetSourceFile);
isEmitBlocked = resolver.isEmitBlocked(targetSourceFile);
isEmitBlocked = host.isEmitBlocked(targetSourceFile);
var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, program, ".js");
var jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js");
emitFile(jsFilePath, targetSourceFile);
}
else if (!isDeclarationFile(targetSourceFile) && compilerOptions.out) {
// Otherwise, if --out is specified and targetSourceFile is not a declaration file,
// Emit all, non-external-module file, into one single output file
forEach(program.getSourceFiles(), sourceFile => {
forEach(host.getSourceFiles(), sourceFile => {
if (!shouldEmitToOwnFile(sourceFile, compilerOptions)) {
hasSemanticErrors = hasSemanticErrors || resolver.hasSemanticErrors(sourceFile);
isEmitBlocked = isEmitBlocked || resolver.isEmitBlocked(sourceFile);
isEmitBlocked = isEmitBlocked || host.isEmitBlocked(sourceFile);
}
});

File diff suppressed because it is too large Load diff

408
src/compiler/program.ts Normal file
View file

@ -0,0 +1,408 @@
/// <reference path="sys.ts" />
/// <reference path="emitter.ts" />
module ts {
export function createCompilerHost(options: CompilerOptions): CompilerHost {
var currentDirectory: string;
var existingDirectories: Map<boolean> = {};
function getCanonicalFileName(fileName: string): string {
// if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form.
// otherwise use toLowerCase as a canonical form.
return sys.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase();
}
// returned by CScript sys environment
var unsupportedFileEncodingErrorCode = -2147024809;
function getSourceFile(filename: string, languageVersion: ScriptTarget, onError?: (message: string) => void): SourceFile {
try {
var text = sys.readFile(filename, options.charset);
}
catch (e) {
if (onError) {
onError(e.number === unsupportedFileEncodingErrorCode ?
createCompilerDiagnostic(Diagnostics.Unsupported_file_encoding).messageText :
e.message);
}
text = "";
}
return text !== undefined ? createSourceFile(filename, text, languageVersion) : undefined;
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void) {
function directoryExists(directoryPath: string): boolean {
if (hasProperty(existingDirectories, directoryPath)) {
return true;
}
if (sys.directoryExists(directoryPath)) {
existingDirectories[directoryPath] = true;
return true;
}
return false;
}
function ensureDirectoriesExist(directoryPath: string) {
if (directoryPath.length > getRootLength(directoryPath) && !directoryExists(directoryPath)) {
var parentDirectory = getDirectoryPath(directoryPath);
ensureDirectoriesExist(parentDirectory);
sys.createDirectory(directoryPath);
}
}
try {
ensureDirectoriesExist(getDirectoryPath(normalizePath(fileName)));
sys.writeFile(fileName, data, writeByteOrderMark);
}
catch (e) {
if (onError) {
onError(e.message);
}
}
}
return {
getSourceFile,
getDefaultLibFilename: options => combinePaths(getDirectoryPath(normalizePath(sys.getExecutingFilePath())), options.target === ScriptTarget.ES6 ? "lib.es6.d.ts" : "lib.d.ts"),
writeFile,
getCurrentDirectory: () => currentDirectory || (currentDirectory = sys.getCurrentDirectory()),
useCaseSensitiveFileNames: () => sys.useCaseSensitiveFileNames,
getCanonicalFileName,
getNewLine: () => sys.newLine
};
}
export function createProgram(rootNames: string[], options: CompilerOptions, host: CompilerHost): Program {
var program: Program;
var files: SourceFile[] = [];
var filesByName: Map<SourceFile> = {};
var errors: Diagnostic[] = [];
var seenNoDefaultLib = options.noLib;
var commonSourceDirectory: string;
forEach(rootNames, name => processRootFile(name, false));
if (!seenNoDefaultLib) {
processRootFile(host.getDefaultLibFilename(options), true);
}
verifyCompilerOptions();
errors.sort(compareDiagnostics);
var diagnosticsProducingTypeChecker: TypeChecker;
var noDiagnosticsTypeChecker: TypeChecker;
var emitHost: EmitHost;
program = {
getSourceFile: getSourceFile,
getSourceFiles: () => files,
getCompilerOptions: () => options,
getCompilerHost: () => host,
getDiagnostics: getDiagnostics,
getGlobalDiagnostics: getGlobalDiagnostics,
getDeclarationDiagnostics: getDeclarationDiagnostics,
getTypeChecker,
getCommonSourceDirectory: () => commonSourceDirectory,
emitFiles: invokeEmitter,
isEmitBlocked,
getCurrentDirectory: host.getCurrentDirectory,
};
return program;
function getEmitHost() {
return emitHost || (emitHost = createEmitHostFromProgram(program));
}
function hasEarlyErrors(sourceFile?: SourceFile): boolean {
return forEach(getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile), d => d.isEarly);
}
function isEmitBlocked(sourceFile?: SourceFile): boolean {
return getDiagnostics(sourceFile).length !== 0 ||
hasEarlyErrors(sourceFile) ||
(options.noEmitOnError && getDiagnosticsProducingTypeChecker().getDiagnostics(sourceFile).length !== 0);
}
function getDiagnosticsProducingTypeChecker() {
return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = createTypeChecker(program, /*produceDiagnostics:*/ true));
}
function getTypeChecker(produceDiagnostics: boolean) {
if (produceDiagnostics) {
return getDiagnosticsProducingTypeChecker();
}
else {
return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = createTypeChecker(program, produceDiagnostics));
}
}
function getDeclarationDiagnostics(targetSourceFile: SourceFile): Diagnostic[]{
var typeChecker = getDiagnosticsProducingTypeChecker();
typeChecker.getDiagnostics(targetSourceFile);
var resolver = typeChecker.getEmitResolver();
return ts.getDeclarationDiagnostics(getEmitHost(), resolver, targetSourceFile);
}
function invokeEmitter(targetSourceFile?: SourceFile) {
var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver();
return emitFiles(resolver, getEmitHost(), targetSourceFile);
} function getSourceFile(filename: string) {
filename = host.getCanonicalFileName(filename);
return hasProperty(filesByName, filename) ? filesByName[filename] : undefined;
}
function getDiagnostics(sourceFile?: SourceFile): Diagnostic[] {
return sourceFile ? filter(errors, e => e.file === sourceFile) : errors;
}
function getGlobalDiagnostics(): Diagnostic[] {
return filter(errors, e => !e.file);
}
function hasExtension(filename: string): boolean {
return getBaseFilename(filename).indexOf(".") >= 0;
}
function processRootFile(filename: string, isDefaultLib: boolean) {
processSourceFile(normalizePath(filename), isDefaultLib);
}
function processSourceFile(filename: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
if (refEnd !== undefined && refPos !== undefined) {
var start = refPos;
var length = refEnd - refPos;
}
var diagnostic: DiagnosticMessage;
if (hasExtension(filename)) {
if (!options.allowNonTsExtensions && !fileExtensionIs(filename, ".ts")) {
diagnostic = Diagnostics.File_0_must_have_extension_ts_or_d_ts;
}
else if (!findSourceFile(filename, isDefaultLib, refFile, refPos, refEnd)) {
diagnostic = Diagnostics.File_0_not_found;
}
else if (refFile && host.getCanonicalFileName(filename) === host.getCanonicalFileName(refFile.filename)) {
diagnostic = Diagnostics.A_file_cannot_have_a_reference_to_itself;
}
}
else {
if (!(findSourceFile(filename + ".ts", isDefaultLib, refFile, refPos, refEnd) || findSourceFile(filename + ".d.ts", isDefaultLib, refFile, refPos, refEnd))) {
diagnostic = Diagnostics.File_0_not_found;
filename += ".ts";
}
}
if (diagnostic) {
if (refFile) {
errors.push(createFileDiagnostic(refFile, start, length, diagnostic, filename));
}
else {
errors.push(createCompilerDiagnostic(diagnostic, filename));
}
}
}
// Get source file from normalized filename
function findSourceFile(filename: string, isDefaultLib: boolean, refFile?: SourceFile, refStart?: number, refLength?: number): SourceFile {
var canonicalName = host.getCanonicalFileName(filename);
if (hasProperty(filesByName, canonicalName)) {
// We've already looked for this file, use cached result
return getSourceFileFromCache(filename, canonicalName, /*useAbsolutePath*/ false);
}
else {
var normalizedAbsolutePath = getNormalizedAbsolutePath(filename, host.getCurrentDirectory());
var canonicalAbsolutePath = host.getCanonicalFileName(normalizedAbsolutePath);
if (hasProperty(filesByName, canonicalAbsolutePath)) {
return getSourceFileFromCache(normalizedAbsolutePath, canonicalAbsolutePath, /*useAbsolutePath*/ true);
}
// We haven't looked for this file, do so now and cache result
var file = filesByName[canonicalName] = host.getSourceFile(filename, options.target, hostErrorMessage => {
if (refFile) {
errors.push(createFileDiagnostic(refFile, refStart, refLength,
Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage));
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, filename, hostErrorMessage));
}
});
if (file) {
seenNoDefaultLib = seenNoDefaultLib || file.hasNoDefaultLib;
// Set the source file for normalized absolute path
filesByName[canonicalAbsolutePath] = file;
if (!options.noResolve) {
var basePath = getDirectoryPath(filename);
processReferencedFiles(file, basePath);
processImportedModules(file, basePath);
}
if (isDefaultLib) {
files.unshift(file);
}
else {
files.push(file);
}
forEach(file.getSyntacticDiagnostics(), e => {
errors.push(e);
});
}
}
return file;
function getSourceFileFromCache(filename: string, canonicalName: string, useAbsolutePath: boolean): SourceFile {
var file = filesByName[canonicalName];
if (file && host.useCaseSensitiveFileNames()) {
var sourceFileName = useAbsolutePath ? getNormalizedAbsolutePath(file.filename, host.getCurrentDirectory()) : file.filename;
if (canonicalName !== sourceFileName) {
errors.push(createFileDiagnostic(refFile, refStart, refLength,
Diagnostics.Filename_0_differs_from_already_included_filename_1_only_in_casing, filename, sourceFileName));
}
}
return file;
}
}
function processReferencedFiles(file: SourceFile, basePath: string) {
forEach(file.referencedFiles, ref => {
var referencedFilename = isRootedDiskPath(ref.filename) ? ref.filename : combinePaths(basePath, ref.filename);
processSourceFile(normalizePath(referencedFilename), /* isDefaultLib */ false, file, ref.pos, ref.end);
});
}
function processImportedModules(file: SourceFile, basePath: string) {
forEach(file.statements, node => {
if (isExternalModuleImportDeclaration(node) &&
getExternalModuleImportDeclarationExpression(node).kind === SyntaxKind.StringLiteral) {
var nameLiteral = <LiteralExpression>getExternalModuleImportDeclarationExpression(node);
var moduleName = nameLiteral.text;
if (moduleName) {
var searchPath = basePath;
while (true) {
var searchName = normalizePath(combinePaths(searchPath, moduleName));
if (findModuleSourceFile(searchName + ".ts", nameLiteral) || findModuleSourceFile(searchName + ".d.ts", nameLiteral)) {
break;
}
var parentPath = getDirectoryPath(searchPath);
if (parentPath === searchPath) {
break;
}
searchPath = parentPath;
}
}
}
else if (node.kind === SyntaxKind.ModuleDeclaration && (<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral && (node.flags & NodeFlags.Ambient || isDeclarationFile(file))) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An AmbientExternalModuleDeclaration declares an external module.
// This type of declaration is permitted only in the global module.
// The StringLiteral must specify a top - level external module name.
// Relative external module names are not permitted
forEachChild((<ModuleDeclaration>node).body, node => {
if (isExternalModuleImportDeclaration(node) &&
getExternalModuleImportDeclarationExpression(node).kind === SyntaxKind.StringLiteral) {
var nameLiteral = <LiteralExpression>getExternalModuleImportDeclarationExpression(node);
var moduleName = nameLiteral.text;
if (moduleName) {
// TypeScript 1.0 spec (April 2014): 12.1.6
// An ExternalImportDeclaration in anAmbientExternalModuleDeclaration may reference other external modules
// only through top - level external module names. Relative external module names are not permitted.
var searchName = normalizePath(combinePaths(basePath, moduleName));
var tsFile = findModuleSourceFile(searchName + ".ts", nameLiteral);
if (!tsFile) {
findModuleSourceFile(searchName + ".d.ts", nameLiteral);
}
}
}
});
}
});
function findModuleSourceFile(filename: string, nameLiteral: LiteralExpression) {
return findSourceFile(filename, /* isDefaultLib */ false, file, nameLiteral.pos, nameLiteral.end - nameLiteral.pos);
}
}
function verifyCompilerOptions() {
if (!options.sourceMap && (options.mapRoot || options.sourceRoot)) {
// Error to specify --mapRoot or --sourceRoot without mapSourceFiles
if (options.mapRoot) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_mapRoot_cannot_be_specified_without_specifying_sourcemap_option));
}
if (options.sourceRoot) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_sourceRoot_cannot_be_specified_without_specifying_sourcemap_option));
}
return;
}
var firstExternalModule = forEach(files, f => isExternalModule(f) ? f : undefined);
if (firstExternalModule && options.module === ModuleKind.None) {
// We cannot use createDiagnosticFromNode because nodes do not have parents yet
var externalModuleErrorSpan = getErrorSpanForNode(firstExternalModule.externalModuleIndicator);
var errorStart = skipTrivia(firstExternalModule.text, externalModuleErrorSpan.pos);
var errorLength = externalModuleErrorSpan.end - errorStart;
errors.push(createFileDiagnostic(firstExternalModule, errorStart, errorLength, Diagnostics.Cannot_compile_external_modules_unless_the_module_flag_is_provided));
}
// there has to be common source directory if user specified --outdir || --sourcRoot
// 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
(!options.out || firstExternalModule !== undefined))) {
var commonPathComponents: string[];
forEach(files, sourceFile => {
// Each file contributes into common source file path
if (!(sourceFile.flags & NodeFlags.DeclarationFile)
&& !fileExtensionIs(sourceFile.filename, ".js")) {
var sourcePathComponents = getNormalizedPathComponents(sourceFile.filename, host.getCurrentDirectory());
sourcePathComponents.pop(); // FileName is not part of directory
if (commonPathComponents) {
for (var i = 0; i < Math.min(commonPathComponents.length, sourcePathComponents.length); i++) {
if (commonPathComponents[i] !== sourcePathComponents[i]) {
if (i === 0) {
errors.push(createCompilerDiagnostic(Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files));
return;
}
// New common path found that is 0 -> i-1
commonPathComponents.length = i;
break;
}
}
// If the fileComponent path completely matched and less than already found update the length
if (sourcePathComponents.length < commonPathComponents.length) {
commonPathComponents.length = sourcePathComponents.length;
}
}
else {
// first file
commonPathComponents = sourcePathComponents;
}
}
});
commonSourceDirectory = getNormalizedPathFromPathComponents(commonPathComponents);
if (commonSourceDirectory) {
// Make sure directory path ends with directory separator so this string can directly
// used to replace with "" to get the relative path of the source file and the relative path doesn't
// start with / making it rooted path
commonSourceDirectory += directorySeparator;
}
}
if (options.noEmit) {
if (options.out || options.outDir) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_out_or_outDir));
}
if (options.declaration) {
errors.push(createCompilerDiagnostic(Diagnostics.Option_noEmit_cannot_be_specified_with_option_declaration));
}
}
}
}
}

View file

@ -1,15 +1,10 @@
/// <reference path="types.ts"/>
/// <reference path="core.ts"/>
/// <reference path="diagnosticInformationMap.generated.ts"/>
module ts {
export interface ErrorCallback {
(message: DiagnosticMessage): void;
}
export interface CommentCallback {
(pos: number, end: number): void;
(message: DiagnosticMessage, length: number): void;
}
export interface Scanner {
@ -392,34 +387,57 @@ module ts {
}
}
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
var mergeConflictMarkerLength = "<<<<<<<".length;
function isConflictMarkerTrivia(text: string, pos: number) {
Debug.assert(pos >= 0);
// Conflict markers must be at the start of a line.
if (pos > 0 && isLineBreak(text.charCodeAt(pos - 1))) {
if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
var ch = text.charCodeAt(pos);
// All conflict markers consist of the same character repeated seven times. If it is
// a <<<<<<< or >>>>>>> marker then it is also followd by a space.
var markerLength = "<<<<<<<".length;
if ((pos + markerLength) < text.length) {
for (var i = 0, n = markerLength; i < n; i++) {
if ((pos + mergeConflictMarkerLength) < text.length) {
for (var i = 0, n = mergeConflictMarkerLength; i < n; i++) {
if (text.charCodeAt(pos + i) !== ch) {
return false;
}
}
return ch === CharacterCodes.equals ||
text.charCodeAt(pos + markerLength) === CharacterCodes.space;
text.charCodeAt(pos + mergeConflictMarkerLength) === CharacterCodes.space;
}
}
return false;
}
function scanConflictMarkerTrivia(text: string, pos: number) {
function scanConflictMarkerTrivia(text: string, pos: number, error?: ErrorCallback) {
if (error) {
error(Diagnostics.Merge_conflict_marker_encountered, mergeConflictMarkerLength);
}
var ch = text.charCodeAt(pos);
var len = text.length;
while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
pos++;
if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) {
while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
pos++;
}
}
else {
Debug.assert(ch === CharacterCodes.equals);
// Consume everything from the start of the mid-conlict marker to the start of the next
// end-conflict marker.
while (pos < len) {
var ch = text.charCodeAt(pos);
if (ch === CharacterCodes.greaterThan && isConflictMarkerTrivia(text, pos)) {
break;
}
pos++;
}
}
return pos;
@ -529,9 +547,9 @@ module ts {
var precedingLineBreak: boolean;
var tokenIsUnterminated: boolean;
function error(message: DiagnosticMessage): void {
function error(message: DiagnosticMessage, length?: number): void {
if (onError) {
onError(message);
onError(message, length || 0);
}
}
@ -1058,8 +1076,7 @@ module ts {
return pos++, token = SyntaxKind.SemicolonToken;
case CharacterCodes.lessThan:
if (isConflictMarkerTrivia(text, pos)) {
error(Diagnostics.Merge_conflict_marker_encountered);
pos = scanConflictMarkerTrivia(text, pos);
pos = scanConflictMarkerTrivia(text, pos, error);
if (skipTrivia) {
continue;
}
@ -1080,8 +1097,7 @@ module ts {
return pos++, token = SyntaxKind.LessThanToken;
case CharacterCodes.equals:
if (isConflictMarkerTrivia(text, pos)) {
error(Diagnostics.Merge_conflict_marker_encountered);
pos = scanConflictMarkerTrivia(text, pos);
pos = scanConflictMarkerTrivia(text, pos, error);
if (skipTrivia) {
continue;
}
@ -1102,8 +1118,7 @@ module ts {
return pos++, token = SyntaxKind.EqualsToken;
case CharacterCodes.greaterThan:
if (isConflictMarkerTrivia(text, pos)) {
error(Diagnostics.Merge_conflict_marker_encountered);
pos = scanConflictMarkerTrivia(text, pos);
pos = scanConflictMarkerTrivia(text, pos, error);
if (skipTrivia) {
continue;
}

View file

@ -1,11 +1,4 @@
/// <reference path="core.ts"/>
/// <reference path="sys.ts"/>
/// <reference path="types.ts"/>
/// <reference path="scanner.ts"/>
/// <reference path="parser.ts"/>
/// <reference path="binder.ts"/>
/// <reference path="checker.ts"/>
/// <reference path="emitter.ts"/>
/// <reference path="program.ts"/>
/// <reference path="commandLineParser.ts"/>
module ts {
@ -293,12 +286,15 @@ module ts {
var checker = program.getTypeChecker(/*fullTypeCheckMode*/ true);
var checkStart = new Date().getTime();
errors = checker.getDiagnostics();
if (checker.isEmitBlocked()) {
if (program.isEmitBlocked()) {
exitStatus = EmitReturnStatus.AllOutputGenerationSkipped;
}
else if (compilerOptions.noEmit) {
exitStatus = EmitReturnStatus.Succeeded;
}
else {
var emitStart = new Date().getTime();
var emitOutput = checker.emitFiles();
var emitOutput = program.emitFiles();
var emitErrors = emitOutput.diagnostics;
exitStatus = emitOutput.emitResultStatus;
var reportStart = new Date().getTime();

View file

@ -1,5 +1,3 @@
/// <reference path="core.ts"/>
module ts {
export interface Map<T> {
[index: string]: T;
@ -18,6 +16,8 @@ module ts {
MultiLineCommentTrivia,
NewLineTrivia,
WhitespaceTrivia,
// We detect and provide better error recovery when we encounter a git merge marker. This
// allows us to edit files with git-conflict markers in them in a much more pleasant manner.
ConflictMarkerTrivia,
// Literals
NumericLiteral,
@ -218,10 +218,9 @@ module ts {
LabeledStatement,
ThrowStatement,
TryStatement,
TryBlock,
FinallyBlock,
DebuggerStatement,
VariableDeclaration,
VariableDeclarationList,
FunctionDeclaration,
ClassDeclaration,
InterfaceDeclaration,
@ -249,7 +248,6 @@ module ts {
EnumMember,
// Top-level nodes
SourceFile,
Program,
// Synthesized list
SyntaxList,
@ -276,26 +274,24 @@ module ts {
LastLiteralToken = NoSubstitutionTemplateLiteral,
FirstTemplateToken = NoSubstitutionTemplateLiteral,
LastTemplateToken = TemplateTail,
FirstOperator = SemicolonToken,
LastOperator = CaretEqualsToken,
FirstBinaryOperator = LessThanToken,
LastBinaryOperator = CaretEqualsToken,
FirstNode = QualifiedName,
}
export const enum NodeFlags {
Export = 0x00000001, // Declarations
Ambient = 0x00000002, // Declarations
Public = 0x00000010, // Property/Method
Private = 0x00000020, // Property/Method
Protected = 0x00000040, // Property/Method
Static = 0x00000080, // Property/Method
MultiLine = 0x00000100, // Multi-line array or object literal
Synthetic = 0x00000200, // Synthetic node (for full fidelity)
DeclarationFile = 0x00000400, // Node is a .d.ts file
Let = 0x00000800, // Variable declaration
Const = 0x00001000, // Variable declaration
OctalLiteral = 0x00002000,
Export = 0x00000001, // Declarations
Ambient = 0x00000002, // Declarations
Public = 0x00000010, // Property/Method
Private = 0x00000020, // Property/Method
Protected = 0x00000040, // Property/Method
Static = 0x00000080, // Property/Method
MultiLine = 0x00000100, // Multi-line array or object literal
Synthetic = 0x00000200, // Synthetic node (for full fidelity)
DeclarationFile = 0x00000400, // Node is a .d.ts file
Let = 0x00000800, // Variable declaration
Const = 0x00001000, // Variable declaration
OctalLiteral = 0x00002000,
Modifier = Export | Ambient | Public | Private | Protected | Static,
AccessibilityModifier = Public | Private | Protected,
@ -396,11 +392,16 @@ module ts {
// SyntaxKind.VariableDeclaration
export interface VariableDeclaration extends Declaration {
parent?: VariableDeclarationList;
name: Identifier | BindingPattern; // Declared variable name
type?: TypeNode; // Optional type annotation
initializer?: Expression; // Optional initializer
}
export interface VariableDeclarationList extends Node {
declarations: NodeArray<VariableDeclaration>;
}
// SyntaxKind.Parameter
export interface ParameterDeclaration extends Declaration {
dotDotDotToken?: Node; // Present on rest parameter
@ -606,7 +607,7 @@ module ts {
export interface VoidExpression extends UnaryExpression {
expression: UnaryExpression;
}
export interface YieldExpression extends Expression {
asteriskToken?: Node;
expression: Expression;
@ -709,7 +710,7 @@ module ts {
}
export interface VariableStatement extends Statement {
declarations: NodeArray<VariableDeclaration>;
declarationList: VariableDeclarationList;
}
export interface ExpressionStatement extends Statement {
@ -735,15 +736,13 @@ module ts {
}
export interface ForStatement extends IterationStatement {
declarations?: NodeArray<VariableDeclaration>;
initializer?: Expression;
initializer?: VariableDeclarationList | Expression;
condition?: Expression;
iterator?: Expression;
}
export interface ForInStatement extends IterationStatement {
declarations?: NodeArray<VariableDeclaration>;
variable?: Expression;
initializer: VariableDeclarationList | Expression;
expression: Expression;
}
@ -881,9 +880,22 @@ module ts {
filename: string;
text: string;
getLineAndCharacterFromPosition(position: number): LineAndCharacter;
getPositionFromLineAndCharacter(line: number, character: number): number;
getLineStarts(): number[];
// Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
// indicates what changed between the 'text' that this SourceFile has and the 'newText'.
// The SourceFile will be created with the compiler attempting to reuse as many nodes from
// this file as possible.
//
// Note: this function mutates nodes from this SourceFile. That means any existing nodes
// from this SourceFile that are being held onto may change as a result (including
// becoming detached from any SourceFile). It is recommended that this SourceFile not
// be used once 'update' is called on it.
update(newText: string, textChangeRange: TextChangeRange): SourceFile;
amdDependencies: string[];
amdModuleName: string;
referencedFiles: FileReference[];
@ -910,15 +922,33 @@ module ts {
identifiers: Map<string>;
}
export interface Program {
getSourceFile(filename: string): SourceFile;
getSourceFiles(): SourceFile[];
export interface ScriptReferenceHost {
getCompilerOptions(): CompilerOptions;
getSourceFile(filename: string): SourceFile;
getCurrentDirectory(): string;
}
export interface Program extends ScriptReferenceHost {
getSourceFiles(): SourceFile[];
getCompilerHost(): CompilerHost;
getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getTypeChecker(fullTypeCheckMode: boolean): TypeChecker;
getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[];
// Gets a type checker that can be used to semantically analyze source fils in the program.
// The 'produceDiagnostics' flag determines if the checker will produce diagnostics while
// analyzing the code. It can be set to 'false' to make many type checking operaitons
// faster. With this flag set, the checker can avoid codepaths only necessary to produce
// diagnostics, but not necessary to answer semantic questions about the code.
//
// If 'produceDiagnostics' is false, then any calls to get diagnostics from the TypeChecker
// will throw an invalid operation exception.
getTypeChecker(produceDiagnostics: boolean): TypeChecker;
getCommonSourceDirectory(): string;
emitFiles(targetSourceFile?: SourceFile): EmitResult;
isEmitBlocked(sourceFile?: SourceFile): boolean;
}
export interface SourceMapSpan {
@ -944,7 +974,7 @@ module ts {
// Return code used by getEmitOutput function to indicate status of the function
export enum EmitReturnStatus {
Succeeded = 0, // All outputs generated as requested (.js, .map, .d.ts), no errors reported
Succeeded = 0, // All outputs generated if requested (.js, .map, .d.ts), no errors reported
AllOutputGenerationSkipped = 1, // No .js generated because of syntax errors, nothing generated
JSGeneratedWithSemanticErrors = 2, // .js and .map generated with semantic errors
DeclarationGenerationSkipped = 3, // .d.ts generation skipped because of semantic errors or declaration emitter specific errors; Output .js with semantic errors
@ -958,16 +988,22 @@ module ts {
sourceMaps: SourceMapData[]; // Array of sourceMapData if compiler emitted sourcemaps
}
export interface TypeCheckerHost {
getCompilerOptions(): CompilerOptions;
getCompilerHost(): CompilerHost;
getSourceFiles(): SourceFile[];
getSourceFile(filename: string): SourceFile;
}
export interface TypeChecker {
getProgram(): Program;
getEmitResolver(): EmitResolver;
getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile: SourceFile): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getNodeCount(): number;
getIdentifierCount(): number;
getSymbolCount(): number;
getTypeCount(): number;
emitFiles(targetSourceFile?: SourceFile): EmitResult;
getTypeOfSymbolAtLocation(symbol: Symbol, node: Node): Type;
getDeclaredTypeOfSymbol(symbol: Symbol): Type;
getPropertiesOfType(type: Type): Symbol[];
@ -991,7 +1027,7 @@ module ts {
isImplementationOfOverload(node: FunctionLikeDeclaration): boolean;
isUndefinedSymbol(symbol: Symbol): boolean;
isArgumentsSymbol(symbol: Symbol): boolean;
isEmitBlocked(sourceFile?: SourceFile): boolean;
// Returns the constant value of this enum member, or 'undefined' if the enum member has a computed value.
getEnumMemberValue(node: EnumMember): number;
isValidPropertyAccess(node: PropertyAccessExpression | QualifiedName, propertyName: string): boolean;
@ -1030,7 +1066,7 @@ module ts {
}
export const enum TypeFormatFlags {
None = 0x00000000,
None = 0x00000000,
WriteArrayAsGenericType = 0x00000001, // Write Array<T> instead T[]
UseTypeOfFunction = 0x00000002, // Write typeof instead of function type literal
NoTruncation = 0x00000004, // Don't truncate typeToString result
@ -1041,14 +1077,18 @@ module ts {
}
export const enum SymbolFormatFlags {
None = 0x00000000,
WriteTypeParametersOrArguments = 0x00000001, // Write symbols's type argument if it is instantiated symbol
// eg. class C<T> { p: T } <-- Show p as C<T>.p here
// var a: C<number>;
// var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
UseOnlyExternalAliasing = 0x00000002, // Use only external alias information to get the symbol name in the given context
// eg. module m { export class c { } } import x = m.c;
// When this flag is specified m.c will be used to refer to the class instead of alias symbol x
None = 0x00000000,
// Write symbols's type argument if it is instantiated symbol
// eg. class C<T> { p: T } <-- Show p as C<T>.p here
// var a: C<number>;
// var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
WriteTypeParametersOrArguments = 0x00000001,
// Use only external alias information to get the symbol name in the given context
// eg. module m { export class c { } } import x = m.c;
// When this flag is specified m.c will be used to refer to the class instead of alias symbol x
UseOnlyExternalAliasing = 0x00000002,
}
export const enum SymbolAccessibility {
@ -1069,7 +1109,6 @@ module ts {
}
export interface EmitResolver {
getProgram(): Program;
getLocalNameOfContainer(container: ModuleDeclaration | EnumDeclaration): string;
getExpressionNamePrefix(node: Identifier): string;
getExportAssignmentName(node: SourceFile): string;
@ -1086,51 +1125,50 @@ module ts {
isEntityNameVisible(entityName: EntityName, enclosingDeclaration: Node): SymbolVisibilityResult;
// Returns the constant value this property access resolves to, or 'undefined' for a non-constant
getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number;
isEmitBlocked(sourceFile?: SourceFile): boolean;
isUnknownIdentifier(location: Node, name: string): boolean;
}
export const enum SymbolFlags {
FunctionScopedVariable = 0x00000001, // Variable (var) or parameter
BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const)
Property = 0x00000004, // Property or enum member
EnumMember = 0x00000008, // Enum member
Function = 0x00000010, // Function
Class = 0x00000020, // Class
Interface = 0x00000040, // Interface
ConstEnum = 0x00000080, // Const enum
RegularEnum = 0x00000100, // Enum
ValueModule = 0x00000200, // Instantiated module
NamespaceModule = 0x00000400, // Uninstantiated module
TypeLiteral = 0x00000800, // Type Literal
ObjectLiteral = 0x00001000, // Object Literal
Method = 0x00002000, // Method
Constructor = 0x00004000, // Constructor
GetAccessor = 0x00008000, // Get accessor
SetAccessor = 0x00010000, // Set accessor
Signature = 0x00020000, // Call, construct, or index signature
TypeParameter = 0x00040000, // Type parameter
TypeAlias = 0x00080000, // Type alias
FunctionScopedVariable = 0x00000001, // Variable (var) or parameter
BlockScopedVariable = 0x00000002, // A block-scoped variable (let or const)
Property = 0x00000004, // Property or enum member
EnumMember = 0x00000008, // Enum member
Function = 0x00000010, // Function
Class = 0x00000020, // Class
Interface = 0x00000040, // Interface
ConstEnum = 0x00000080, // Const enum
RegularEnum = 0x00000100, // Enum
ValueModule = 0x00000200, // Instantiated module
NamespaceModule = 0x00000400, // Uninstantiated module
TypeLiteral = 0x00000800, // Type Literal
ObjectLiteral = 0x00001000, // Object Literal
Method = 0x00002000, // Method
Constructor = 0x00004000, // Constructor
GetAccessor = 0x00008000, // Get accessor
SetAccessor = 0x00010000, // Set accessor
Signature = 0x00020000, // Call, construct, or index signature
TypeParameter = 0x00040000, // Type parameter
TypeAlias = 0x00080000, // Type alias
// Export markers (see comment in declareModuleMember in binder)
ExportValue = 0x00100000, // Exported value marker
ExportType = 0x00200000, // Exported type marker
ExportNamespace = 0x00400000, // Exported namespace marker
Import = 0x00800000, // Import
Instantiated = 0x01000000, // Instantiated symbol
Merged = 0x02000000, // Merged symbol (created during program binding)
Transient = 0x04000000, // Transient symbol (created during type check)
Prototype = 0x08000000, // Prototype property (no source representation)
UnionProperty = 0x10000000, // Property in union type
Optional = 0x20000000, // Optional property
ExportValue = 0x00100000, // Exported value marker
ExportType = 0x00200000, // Exported type marker
ExportNamespace = 0x00400000, // Exported namespace marker
Import = 0x00800000, // Import
Instantiated = 0x01000000, // Instantiated symbol
Merged = 0x02000000, // Merged symbol (created during program binding)
Transient = 0x04000000, // Transient symbol (created during type check)
Prototype = 0x08000000, // Prototype property (no source representation)
UnionProperty = 0x10000000, // Property in union type
Optional = 0x20000000, // Optional property
Enum = RegularEnum | ConstEnum,
Variable = FunctionScopedVariable | BlockScopedVariable,
Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,
Enum = RegularEnum | ConstEnum,
Variable = FunctionScopedVariable | BlockScopedVariable,
Value = Variable | Property | EnumMember | Function | Class | Enum | ValueModule | Method | GetAccessor | SetAccessor,
Type = Class | Interface | Enum | TypeLiteral | ObjectLiteral | TypeParameter | TypeAlias,
Namespace = ValueModule | NamespaceModule,
Module = ValueModule | NamespaceModule,
Accessor = GetAccessor | SetAccessor,
Module = ValueModule | NamespaceModule,
Accessor = GetAccessor | SetAccessor,
// Variables can be redeclared, but can not redeclare a block-scoped declaration with the
// same name, or any other value that is not a variable, e.g. ValueModule or Class
@ -1140,34 +1178,34 @@ module ts {
// they can not merge with anything in the value space
BlockScopedVariableExcludes = Value,
ParameterExcludes = Value,
PropertyExcludes = Value,
EnumMemberExcludes = Value,
FunctionExcludes = Value & ~(Function | ValueModule),
ClassExcludes = (Value | Type) & ~ValueModule,
InterfaceExcludes = Type & ~Interface,
RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules
ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums
ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule),
ParameterExcludes = Value,
PropertyExcludes = Value,
EnumMemberExcludes = Value,
FunctionExcludes = Value & ~(Function | ValueModule),
ClassExcludes = (Value | Type) & ~ValueModule,
InterfaceExcludes = Type & ~Interface,
RegularEnumExcludes = (Value | Type) & ~(RegularEnum | ValueModule), // regular enums merge only with regular enums and modules
ConstEnumExcludes = (Value | Type) & ~ConstEnum, // const enums merge only with const enums
ValueModuleExcludes = Value & ~(Function | Class | RegularEnum | ValueModule),
NamespaceModuleExcludes = 0,
MethodExcludes = Value & ~Method,
GetAccessorExcludes = Value & ~SetAccessor,
SetAccessorExcludes = Value & ~GetAccessor,
TypeParameterExcludes = Type & ~TypeParameter,
TypeAliasExcludes = Type,
ImportExcludes = Import, // Imports collide with all other imports with the same name
MethodExcludes = Value & ~Method,
GetAccessorExcludes = Value & ~SetAccessor,
SetAccessorExcludes = Value & ~GetAccessor,
TypeParameterExcludes = Type & ~TypeParameter,
TypeAliasExcludes = Type,
ImportExcludes = Import, // Imports collide with all other imports with the same name
ModuleMember = Variable | Function | Class | Interface | Enum | Module | TypeAlias | Import,
ExportHasLocal = Function | Class | Enum | ValueModule,
HasLocals = Function | Module | Method | Constructor | Accessor | Signature,
HasLocals = Function | Module | Method | Constructor | Accessor | Signature,
HasExports = Class | Enum | Module,
HasMembers = Class | Interface | TypeLiteral | ObjectLiteral,
IsContainer = HasLocals | HasExports | HasMembers,
IsContainer = HasLocals | HasExports | HasMembers,
PropertyOrAccessor = Property | Accessor,
Export = ExportNamespace | ExportType | ExportValue,
Export = ExportNamespace | ExportType | ExportValue,
}
export interface Symbol {
@ -1201,16 +1239,16 @@ module ts {
}
export const enum NodeCheckFlags {
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
EmitExtends = 0x00000008, // Emit __extends
SuperInstance = 0x00000010, // Instance 'super' reference
SuperStatic = 0x00000020, // Static 'super' reference
ContextChecked = 0x00000040, // Contextual types have been assigned
TypeChecked = 0x00000001, // Node has been type checked
LexicalThis = 0x00000002, // Lexical 'this' reference
CaptureThis = 0x00000004, // Lexical 'this' used in body
EmitExtends = 0x00000008, // Emit __extends
SuperInstance = 0x00000010, // Instance 'super' reference
SuperStatic = 0x00000020, // Static 'super' reference
ContextChecked = 0x00000040, // Contextual types have been assigned
// Values for enum members have been computed, and any errors have been reported for them.
EnumValuesComputed = 0x00000080,
EnumValuesComputed = 0x00000080,
}
export interface NodeLinks {
@ -1228,26 +1266,26 @@ module ts {
}
export const enum TypeFlags {
Any = 0x00000001,
String = 0x00000002,
Number = 0x00000004,
Boolean = 0x00000008,
Void = 0x00000010,
Undefined = 0x00000020,
Null = 0x00000040,
Enum = 0x00000080, // Enum type
StringLiteral = 0x00000100, // String literal type
TypeParameter = 0x00000200, // Type parameter
Class = 0x00000400, // Class
Interface = 0x00000800, // Interface
Reference = 0x00001000, // Generic type reference
Tuple = 0x00002000, // Tuple
Union = 0x00004000, // Union
Anonymous = 0x00008000, // Anonymous
FromSignature = 0x00010000, // Created for signature assignment check
Unwidened = 0x00020000, // Unwidened type (is or contains Undefined or Null type)
Any = 0x00000001,
String = 0x00000002,
Number = 0x00000004,
Boolean = 0x00000008,
Void = 0x00000010,
Undefined = 0x00000020,
Null = 0x00000040,
Enum = 0x00000080, // Enum type
StringLiteral = 0x00000100, // String literal type
TypeParameter = 0x00000200, // Type parameter
Class = 0x00000400, // Class
Interface = 0x00000800, // Interface
Reference = 0x00001000, // Generic type reference
Tuple = 0x00002000, // Tuple
Union = 0x00004000, // Union
Anonymous = 0x00008000, // Anonymous
FromSignature = 0x00010000, // Created for signature assignment check
Unwidened = 0x00020000, // Unwidened type (is or contains Undefined or Null type)
Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null,
Intrinsic = Any | String | Number | Boolean | Void | Undefined | Null,
StringLike = String | StringLiteral,
NumberLike = Number | Enum,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
@ -1364,7 +1402,7 @@ module ts {
inferences: TypeInferences[]; // Inferences made for each type parameter
inferredTypes: Type[]; // Inferred type for each type parameter
failedTypeParameterIndex?: number; // Index of type parameter for which inference failed
// It is optional because in contextual signature instantiation, nothing fails
// It is optional because in contextual signature instantiation, nothing fails
}
export interface DiagnosticMessage {
@ -1415,6 +1453,7 @@ module ts {
locale?: string;
mapRoot?: string;
module?: ModuleKind;
noEmit?: boolean;
noEmitOnError?: boolean;
noErrorTruncation?: boolean;
noImplicitAny?: boolean;
@ -1448,7 +1487,6 @@ module ts {
character: number;
}
export const enum ScriptTarget {
ES3 = 0,
ES5 = 1,
@ -1499,7 +1537,7 @@ module ts {
narrowNoBreakSpace = 0x202F,
ideographicSpace = 0x3000,
mathematicalSpace = 0x205F,
ogham = 0x1680,
ogham = 0x1680,
_ = 0x5F,
$ = 0x24,
@ -1620,4 +1658,14 @@ module ts {
useCaseSensitiveFileNames(): boolean;
getNewLine(): string;
}
export interface TextSpan {
start: number;
length: number;
}
export interface TextChangeRange {
span: TextSpan;
newLength: number;
}
}

View file

@ -23,6 +23,17 @@ module ts {
string(): string;
}
export interface EmitHost extends ScriptReferenceHost {
getSourceFiles(): SourceFile[];
isEmitBlocked(sourceFile?: SourceFile): boolean;
getCommonSourceDirectory(): string;
getCanonicalFileName(fileName: string): string;
getNewLine(): string;
writeFile(filename: string, data: string, writeByteOrderMark: boolean, onError?: (message: string) => void): void;
}
// Pool writers to avoid needing to allocate them for every symbol we write.
var stringWriters: StringSymbolWriter[] = [];
export function getSingleLineStringWriter(): StringSymbolWriter {
@ -62,22 +73,18 @@ module ts {
return node.end - node.pos;
}
function hasFlag(val: number, flag: number): boolean {
return (val & flag) !== 0;
}
// Returns true if this node contains a parse error anywhere underneath it.
export function containsParseError(node: Node): boolean {
aggregateChildData(node);
return hasFlag(node.parserContextFlags, ParserContextFlags.ThisNodeOrAnySubNodesHasError);
return (node.parserContextFlags & ParserContextFlags.ThisNodeOrAnySubNodesHasError) !== 0
}
function aggregateChildData(node: Node): void {
if (!hasFlag(node.parserContextFlags, ParserContextFlags.HasAggregatedChildData)) {
if (!(node.parserContextFlags & ParserContextFlags.HasAggregatedChildData)) {
// A node is considered to contain a parse error if:
// a) the parser explicitly marked that it had an error
// b) any of it's children reported that it had an error.
var thisNodeOrAnySubNodesHasError = hasFlag(node.parserContextFlags, ParserContextFlags.ThisNodeHasError) ||
var thisNodeOrAnySubNodesHasError = ((node.parserContextFlags & ParserContextFlags.ThisNodeHasError) !== 0) ||
forEachChild(node, containsParseError);
// If so, mark ourselves accordingly.
@ -110,14 +117,34 @@ module ts {
return node.pos;
}
export function isMissingNode(node: Node) {
// Returns true if this node is missing from the actual source code. 'missing' is different
// from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
// in the tree), it is definitel missing. HOwever, a node may be defined, but still be
// missing. This happens whenever the parser knows it needs to parse something, but can't
// get anything in the source code that it expects at that location. For example:
//
// var a: ;
//
// Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
// code). So the parser will attempt to parse out a type, and will create an actual node.
// However, this node will be 'missing' in the sense that no actual source-code/tokens are
// contained within it.
export function nodeIsMissing(node: Node) {
if (!node) {
return true;
}
return node.pos === node.end && node.kind !== SyntaxKind.EndOfFileToken;
}
export function nodeIsPresent(node: Node) {
return !nodeIsMissing(node);
}
export function getTokenPosOfNode(node: Node, sourceFile?: SourceFile): number {
// With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
// want to skip trivia because this will launch us forward to the next token.
if (isMissingNode(node)) {
if (nodeIsMissing(node)) {
return node.pos;
}
@ -125,7 +152,7 @@ module ts {
}
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string {
if (isMissingNode(node)) {
if (nodeIsMissing(node)) {
return "";
}
@ -134,7 +161,7 @@ module ts {
}
export function getTextOfNodeFromSourceText(sourceText: string, node: Node): string {
if (isMissingNode(node)) {
if (nodeIsMissing(node)) {
return "";
}
@ -216,12 +243,47 @@ module ts {
return node.kind === SyntaxKind.EnumDeclaration && isConst(node);
}
function walkUpBindingElementsAndPatterns(node: Node): Node {
while (node && (node.kind === SyntaxKind.BindingElement || isBindingPattern(node))) {
node = node.parent;
}
return node;
}
// Returns the node flags for this node and all relevant parent nodes. This is done so that
// nodes like variable declarations and binding elements can returned a view of their flags
// that includes the modifiers from their container. i.e. flags like export/declare aren't
// stored on the variable declaration directly, but on the containing variable statement
// (if it has one). Similarly, flags for let/const are store on the variable declaration
// list. By calling this function, all those flags are combined so that the client can treat
// the node as if it actually had those flags.
export function getCombinedNodeFlags(node: Node): NodeFlags {
node = walkUpBindingElementsAndPatterns(node);
var flags = node.flags;
if (node.kind === SyntaxKind.VariableDeclaration) {
node = node.parent;
}
if (node && node.kind === SyntaxKind.VariableDeclarationList) {
flags |= node.flags;
node = node.parent;
}
if (node && node.kind === SyntaxKind.VariableStatement) {
flags |= node.flags;
}
return flags;
}
export function isConst(node: Node): boolean {
return !!(node.flags & NodeFlags.Const);
return !!(getCombinedNodeFlags(node) & NodeFlags.Const);
}
export function isLet(node: Node): boolean {
return !!(node.flags & NodeFlags.Let);
return !!(getCombinedNodeFlags(node) & NodeFlags.Let);
}
export function isPrologueDirective(node: Node): boolean {
@ -281,9 +343,7 @@ module ts {
case SyntaxKind.DefaultClause:
case SyntaxKind.LabeledStatement:
case SyntaxKind.TryStatement:
case SyntaxKind.TryBlock:
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyBlock:
return forEachChild(node, traverse);
}
}
@ -455,12 +515,14 @@ module ts {
case SyntaxKind.SwitchStatement:
return (<ExpressionStatement>parent).expression === node;
case SyntaxKind.ForStatement:
return (<ForStatement>parent).initializer === node ||
(<ForStatement>parent).condition === node ||
(<ForStatement>parent).iterator === node;
var forStatement = <ForStatement>parent;
return (forStatement.initializer === node && forStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) ||
forStatement.condition === node ||
forStatement.iterator === node;
case SyntaxKind.ForInStatement:
return (<ForInStatement>parent).variable === node ||
(<ForInStatement>parent).expression === node;
var forInStatement = <ForInStatement>parent;
return (forInStatement.initializer === node && forInStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) ||
forInStatement.expression === node;
case SyntaxKind.TypeAssertionExpression:
return node === (<TypeAssertion>parent).expression;
case SyntaxKind.TemplateSpan:
@ -474,6 +536,12 @@ module ts {
return false;
}
export function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean) {
var moduleState = getModuleInstanceState(node)
return moduleState === ModuleInstanceState.Instantiated ||
(preserveConstEnums && moduleState === ModuleInstanceState.ConstEnumOnly);
}
export function isExternalModuleImportDeclaration(node: Node) {
return node.kind === SyntaxKind.ImportDeclaration && (<ImportDeclaration>node).moduleReference.kind === SyntaxKind.ExternalModuleReference;
}
@ -532,7 +600,10 @@ module ts {
export function isInAmbientContext(node: Node): boolean {
while (node) {
if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) return true;
if (node.flags & (NodeFlags.Ambient | NodeFlags.DeclarationFile)) {
return true;
}
node = node.parent;
}
return false;
@ -637,11 +708,11 @@ module ts {
return undefined;
}
export function tryResolveScriptReference(program: Program, sourceFile: SourceFile, reference: FileReference) {
if (!program.getCompilerOptions().noResolve) {
export function tryResolveScriptReference(host: ScriptReferenceHost, sourceFile: SourceFile, reference: FileReference) {
if (!host.getCompilerOptions().noResolve) {
var referenceFileName = isRootedDiskPath(reference.filename) ? reference.filename : combinePaths(getDirectoryPath(sourceFile.filename), reference.filename);
referenceFileName = getNormalizedAbsolutePath(referenceFileName, program.getCompilerHost().getCurrentDirectory());
return program.getSourceFile(referenceFileName);
referenceFileName = getNormalizedAbsolutePath(referenceFileName, host.getCurrentDirectory());
return host.getSourceFile(referenceFileName);
}
}
@ -710,6 +781,7 @@ module ts {
}
}
}
return undefined;
}
@ -735,4 +807,229 @@ module ts {
return false;
}
export function createEmitHostFromProgram(program: Program): EmitHost {
var compilerHost = program.getCompilerHost();
return {
getCanonicalFileName: compilerHost.getCanonicalFileName,
getCommonSourceDirectory: program.getCommonSourceDirectory,
getCompilerOptions: program.getCompilerOptions,
getCurrentDirectory: compilerHost.getCurrentDirectory,
getNewLine: compilerHost.getNewLine,
getSourceFile: program.getSourceFile,
getSourceFiles: program.getSourceFiles,
isEmitBlocked: program.isEmitBlocked,
writeFile: compilerHost.writeFile,
};
}
export function textSpanEnd(span: TextSpan) {
return span.start + span.length
}
export function textSpanIsEmpty(span: TextSpan) {
return span.length === 0
}
export function textSpanContainsPosition(span: TextSpan, position: number) {
return position >= span.start && position < textSpanEnd(span);
}
// Returns true if 'span' contains 'other'.
export function textSpanContainsTextSpan(span: TextSpan, other: TextSpan) {
return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
}
export function textSpanOverlapsWith(span: TextSpan, other: TextSpan) {
var overlapStart = Math.max(span.start, other.start);
var overlapEnd = Math.min(textSpanEnd(span), textSpanEnd(other));
return overlapStart < overlapEnd;
}
export function textSpanOverlap(span1: TextSpan, span2: TextSpan) {
var overlapStart = Math.max(span1.start, span2.start);
var overlapEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
if (overlapStart < overlapEnd) {
return createTextSpanFromBounds(overlapStart, overlapEnd);
}
return undefined;
}
export function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan) {
return other.start <= textSpanEnd(span) && textSpanEnd(other) >= span.start
}
export function textSpanIntersectsWith(span: TextSpan, start: number, length: number) {
var end = start + length;
return start <= textSpanEnd(span) && end >= span.start;
}
export function textSpanIntersectsWithPosition(span: TextSpan, position: number) {
return position <= textSpanEnd(span) && position >= span.start;
}
export function textSpanIntersection(span1: TextSpan, span2: TextSpan) {
var intersectStart = Math.max(span1.start, span2.start);
var intersectEnd = Math.min(textSpanEnd(span1), textSpanEnd(span2));
if (intersectStart <= intersectEnd) {
return createTextSpanFromBounds(intersectStart, intersectEnd);
}
return undefined;
}
export function createTextSpan(start: number, length: number): TextSpan {
if (start < 0) {
throw new Error("start < 0");
}
if (length < 0) {
throw new Error("length < 0");
}
return { start, length };
}
export function createTextSpanFromBounds(start: number, end: number) {
return createTextSpan(start, end - start);
}
export function textChangeRangeNewSpan(range: TextChangeRange) {
return createTextSpan(range.span.start, range.newLength);
}
export function textChangeRangeIsUnchanged(range: TextChangeRange) {
return textSpanIsEmpty(range.span) && range.newLength === 0;
}
export function createTextChangeRange(span: TextSpan, newLength: number): TextChangeRange {
if (newLength < 0) {
throw new Error("newLength < 0");
}
return { span, newLength };
}
export var unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0);
/**
* Called to merge all the changes that occurred across several versions of a script snapshot
* into a single change. i.e. if a user keeps making successive edits to a script we will
* have a text change from V1 to V2, V2 to V3, ..., Vn.
*
* This function will then merge those changes into a single change range valid between V1 and
* Vn.
*/
export function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange {
if (changes.length === 0) {
return unchangedTextChangeRange;
}
if (changes.length === 1) {
return changes[0];
}
// We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
// as it makes things much easier to reason about.
var change0 = changes[0];
var oldStartN = change0.span.start;
var oldEndN = textSpanEnd(change0.span);
var newEndN = oldStartN + change0.newLength;
for (var i = 1; i < changes.length; i++) {
var nextChange = changes[i];
// Consider the following case:
// i.e. two edits. The first represents the text change range { { 10, 50 }, 30 }. i.e. The span starting
// at 10, with length 50 is reduced to length 30. The second represents the text change range { { 30, 30 }, 40 }.
// i.e. the span starting at 30 with length 30 is increased to length 40.
//
// 0 10 20 30 40 50 60 70 80 90 100
// -------------------------------------------------------------------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// -------------------------------------------------------------------------------------------------------
// | \
// | \
// T2 | \
// | \
// | \
// -------------------------------------------------------------------------------------------------------
//
// Merging these turns out to not be too difficult. First, determining the new start of the change is trivial
// it's just the min of the old and new starts. i.e.:
//
// 0 10 20 30 40 50 60 70 80 90 100
// ------------------------------------------------------------*------------------------------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ----------------------------------------$-------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// (Note the dots represent the newly inferrred start.
// Determining the new and old end is also pretty simple. Basically it boils down to paying attention to the
// absolute positions at the asterixes, and the relative change between the dollar signs. Basically, we see
// which if the two $'s precedes the other, and we move that one forward until they line up. in this case that
// means:
//
// 0 10 20 30 40 50 60 70 80 90 100
// --------------------------------------------------------------------------------*----------------------
// | /
// | /----
// T1 | /----
// | /----
// | /----
// ------------------------------------------------------------$------------------------------------------
// . | \
// . | \
// T2 . | \
// . | \
// . | \
// ----------------------------------------------------------------------*--------------------------------
//
// In other words (in this case), we're recognizing that the second edit happened after where the first edit
// ended with a delta of 20 characters (60 - 40). Thus, if we go back in time to where the first edit started
// that's the same as if we started at char 80 instead of 60.
//
// As it so happens, the same logic applies if the second edit precedes the first edit. In that case rahter
// than pusing the first edit forward to match the second, we'll push the second edit forward to match the
// first.
//
// In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
// semantics: { { start: 10, length: 70 }, newLength: 60 }
//
// The math then works out as follows.
// If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
// final result like so:
//
// {
// oldStart3: Min(oldStart1, oldStart2),
// oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
// newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
// }
var oldStart1 = oldStartN;
var oldEnd1 = oldEndN;
var newEnd1 = newEndN;
var oldStart2 = nextChange.span.start;
var oldEnd2 = textSpanEnd(nextChange.span);
var newEnd2 = oldStart2 + nextChange.newLength;
oldStartN = Math.min(oldStart1, oldStart2);
oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
}
return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength: */newEndN - oldStartN);
}
}

View file

@ -53,7 +53,7 @@ class CompilerBaselineRunner extends RunnerBase {
var rootDir: string;
var result: Harness.Compiler.CompilerResult;
var checker: ts.TypeChecker;
var program: ts.Program;
var options: ts.CompilerOptions;
// equivalent to the files that will be passed on the command line
var toBeCompiled: { unitName: string; content: string }[];
@ -61,12 +61,6 @@ class CompilerBaselineRunner extends RunnerBase {
var otherFiles: { unitName: string; content: string }[];
var harnessCompiler: Harness.Compiler.HarnessCompiler;
var declFileCompilationResult: {
declInputFiles: { unitName: string; content: string }[];
declOtherFiles: { unitName: string; content: string }[];
declResult: Harness.Compiler.CompilerResult;
};
var createNewInstance = false;
before(() => {
@ -97,10 +91,10 @@ class CompilerBaselineRunner extends RunnerBase {
});
}
options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult, _checker) {
options = harnessCompiler.compileFiles(toBeCompiled, otherFiles, function (compileResult, _program) {
result = compileResult;
// The checker will be used by typeWriter
checker = _checker;
// The program will be used by typeWriter
program = _program;
}, function (settings) {
harnessCompiler.setCompilerSettings(tcSettings);
});
@ -138,12 +132,11 @@ class CompilerBaselineRunner extends RunnerBase {
lastUnit = undefined;
rootDir = undefined;
result = undefined;
checker = undefined;
program = undefined;
options = undefined;
toBeCompiled = undefined;
otherFiles = undefined;
harnessCompiler = undefined;
declFileCompilationResult = undefined;
});
function getByteOrderMarkText(file: Harness.Compiler.GeneratedFile): string {
@ -179,13 +172,6 @@ class CompilerBaselineRunner extends RunnerBase {
}
});
// Compile .d.ts files
it('Correct compiler generated.d.ts for ' + fileName, () => {
declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) {
harnessCompiler.setCompilerSettings(tcSettings);
}, options);
});
it('Correct JS output for ' + fileName, () => {
if (!ts.fileExtensionIs(lastUnit.name, '.d.ts') && this.emit) {
@ -223,6 +209,10 @@ class CompilerBaselineRunner extends RunnerBase {
}
}
var declFileCompilationResult = harnessCompiler.compileDeclarationFiles(toBeCompiled, otherFiles, result, function (settings) {
harnessCompiler.setCompilerSettings(tcSettings);
}, options);
if (declFileCompilationResult && declFileCompilationResult.declResult.errors.length) {
jsCode += '\r\n\r\n//// [DtsFileErrors]\r\n';
jsCode += '\r\n\r\n';
@ -267,10 +257,10 @@ class CompilerBaselineRunner extends RunnerBase {
// NEWTODO: Type baselines
if (result.errors.length === 0) {
Harness.Baseline.runBaseline('Correct expression types for ' + fileName, justName.replace(/\.ts/, '.types'), () => {
var allFiles = toBeCompiled.concat(otherFiles).filter(file => !!checker.getProgram().getSourceFile(file.unitName));
var allFiles = toBeCompiled.concat(otherFiles).filter(file => !!program.getSourceFile(file.unitName));
var typeLines: string[] = [];
var typeMap: { [fileName: string]: { [lineNum: number]: string[]; } } = {};
var walker = new TypeWriterWalker(checker);
var walker = new TypeWriterWalker(program);
allFiles.forEach(file => {
var codeLines = file.content.split('\n');
walker.getTypes(file.unitName).forEach(result => {

View file

@ -18,6 +18,8 @@
/// <reference path='harness.ts' />
module FourSlash {
ts.disableIncrementalParsing = false;
// Represents a parsed source file with metadata
export interface FourSlashFile {
// The contents of the file (with markers, etc stripped out)
@ -697,7 +699,7 @@ module FourSlash {
for (var i = 0; i < references.length; i++) {
var reference = references[i];
if (reference && reference.fileName === fileName && reference.textSpan.start() === start && reference.textSpan.end() === end) {
if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) {
if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) {
this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.');
}
@ -828,17 +830,17 @@ module FourSlash {
}
ranges = ranges.sort((r1, r2) => r1.start - r2.start);
references = references.sort((r1, r2) => r1.textSpan.start() - r2.textSpan.start());
references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start);
for (var i = 0, n = ranges.length; i < n; i++) {
var reference = references[i];
var range = ranges[i];
if (reference.textSpan.start() !== range.start ||
reference.textSpan.end() !== range.end) {
if (reference.textSpan.start !== range.start ||
ts.textSpanEnd(reference.textSpan) !== range.end) {
this.raiseError(this.assertionMessage("Rename location",
"[" + reference.textSpan.start() + "," + reference.textSpan.end() + ")",
"[" + reference.textSpan.start + "," + ts.textSpanEnd(reference.textSpan) + ")",
"[" + range.start + "," + range.end + ")"));
}
}
@ -978,10 +980,10 @@ module FourSlash {
}
var expectedRange = this.getRanges()[0];
if (renameInfo.triggerSpan.start() !== expectedRange.start ||
renameInfo.triggerSpan.end() !== expectedRange.end) {
if (renameInfo.triggerSpan.start !== expectedRange.start ||
ts.textSpanEnd(renameInfo.triggerSpan) !== expectedRange.end) {
this.raiseError("Expected triggerSpan [" + expectedRange.start + "," + expectedRange.end + "). Got [" +
renameInfo.triggerSpan.start() + "," + renameInfo.triggerSpan.end() + ") instead.");
renameInfo.triggerSpan.start + "," + ts.textSpanEnd(renameInfo.triggerSpan) + ") instead.");
}
}
@ -1012,7 +1014,7 @@ module FourSlash {
private spanInfoToString(pos: number, spanInfo: ts.TextSpan, prefixString: string) {
var resultString = "SpanInfo: " + JSON.stringify(spanInfo);
if (spanInfo) {
var spanString = this.activeFile.content.substr(spanInfo.start(), spanInfo.length());
var spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length);
var spanLineMap = ts.computeLineStarts(spanString);
for (var i = 0; i < spanLineMap.length; i++) {
if (!i) {
@ -1020,7 +1022,7 @@ module FourSlash {
}
resultString += prefixString + spanString.substring(spanLineMap[i], spanLineMap[i + 1]);
}
resultString += "\n" + prefixString + ":=> (" + this.getLineColStringAtPosition(spanInfo.start()) + ") to (" + this.getLineColStringAtPosition(spanInfo.end()) + ")";
resultString += "\n" + prefixString + ":=> (" + this.getLineColStringAtPosition(spanInfo.start) + ") to (" + this.getLineColStringAtPosition(ts.textSpanEnd(spanInfo)) + ")";
}
return resultString;
@ -1223,16 +1225,24 @@ module FourSlash {
var offset = this.currentCaretPosition;
var ch = "";
var checkCadence = (count >> 2) + 1
for (var i = 0; i < count; i++) {
// Make the edit
this.languageServiceShimHost.editScript(this.activeFile.fileName, offset, offset + 1, ch);
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch);
this.checkPostEditInvariants();
if (i % checkCadence === 0) {
this.checkPostEditInvariants();
}
// Handle post-keystroke formatting
if (this.enableFormatting) {
var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
offset += this.applyEdits(this.activeFile.fileName, edits, true);
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, true);
//this.checkPostEditInvariants();
}
}
}
@ -1249,8 +1259,6 @@ module FourSlash {
this.languageServiceShimHost.editScript(this.activeFile.fileName, start, start + length, text);
this.updateMarkersForEdit(this.activeFile.fileName, start, start + length, text);
this.checkPostEditInvariants();
this.checkPostEditInvariants();
}
public deleteCharBehindMarker(count = 1) {
@ -1258,19 +1266,24 @@ module FourSlash {
var offset = this.currentCaretPosition;
var ch = "";
var checkCadence = (count >> 2) + 1
for (var i = 0; i < count; i++) {
offset--;
// Make the edit
this.languageServiceShimHost.editScript(this.activeFile.fileName, offset, offset + 1, ch);
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset + 1, ch);
this.checkPostEditInvariants();
if (i % checkCadence === 0) {
this.checkPostEditInvariants();
}
// Handle post-keystroke formatting
if (this.enableFormatting) {
var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
offset += this.applyEdits(this.activeFile.fileName, edits, true);
this.checkPostEditInvariants();
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, true);
}
}
}
@ -1295,9 +1308,11 @@ module FourSlash {
// Enters lines of text at the current caret position, invoking
// language service APIs to mimic Visual Studio's behavior
// as much as possible
private typeHighFidelity(text: string, errorCadence = 5) {
private typeHighFidelity(text: string) {
var offset = this.currentCaretPosition;
var prevChar = ' ';
var checkCadence = (text.length >> 2) + 1;
for (var i = 0; i < text.length; i++) {
// Make the edit
var ch = text.charAt(i);
@ -1305,7 +1320,6 @@ module FourSlash {
this.languageService.getBraceMatchingAtPosition(this.activeFile.fileName, offset);
this.updateMarkersForEdit(this.activeFile.fileName, offset, offset, ch);
this.checkPostEditInvariants();
offset++;
if (ch === '(' || ch === ',') {
@ -1316,16 +1330,19 @@ module FourSlash {
this.languageService.getCompletionsAtPosition(this.activeFile.fileName, offset);
}
if (i % errorCadence === 0) {
this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
if (i % checkCadence === 0) {
this.checkPostEditInvariants();
// this.languageService.getSyntacticDiagnostics(this.activeFile.fileName);
// this.languageService.getSemanticDiagnostics(this.activeFile.fileName);
}
// Handle post-keystroke formatting
if (this.enableFormatting) {
var edits = this.languageService.getFormattingEditsAfterKeystroke(this.activeFile.fileName, offset, ch, this.formatCodeOptions);
offset += this.applyEdits(this.activeFile.fileName, edits, true);
this.checkPostEditInvariants();
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, true);
// this.checkPostEditInvariants();
}
}
}
@ -1350,8 +1367,10 @@ module FourSlash {
// Handle formatting
if (this.enableFormatting) {
var edits = this.languageService.getFormattingEditsForRange(this.activeFile.fileName, start, offset, this.formatCodeOptions);
offset += this.applyEdits(this.activeFile.fileName, edits, true);
this.checkPostEditInvariants();
if (edits.length) {
offset += this.applyEdits(this.activeFile.fileName, edits, true);
this.checkPostEditInvariants();
}
}
// Move the caret to wherever we ended up
@ -1365,7 +1384,7 @@ module FourSlash {
var incrementalSourceFile = this.languageService.getSourceFile(this.activeFile.fileName);
Utils.assertInvariants(incrementalSourceFile, /*parent:*/ undefined);
var incrementalSyntaxDiagnostics = JSON.stringify(Utils.convertDiagnostics(incrementalSourceFile.getSyntacticDiagnostics()));
var incrementalSyntaxDiagnostics = incrementalSourceFile.getSyntacticDiagnostics();
// Check syntactic structure
var snapshot = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName);
@ -1373,32 +1392,10 @@ module FourSlash {
var referenceSourceFile = ts.createLanguageServiceSourceFile(
this.activeFile.fileName, createScriptSnapShot(content), ts.ScriptTarget.Latest, /*version:*/ "0", /*isOpen:*/ false, /*setNodeParents:*/ false);
var referenceSyntaxDiagnostics = JSON.stringify(Utils.convertDiagnostics(referenceSourceFile.getSyntacticDiagnostics()));
if (incrementalSyntaxDiagnostics !== referenceSyntaxDiagnostics) {
this.raiseError('Mismatched incremental/reference syntactic diagnostics for file ' + this.activeFile.fileName + '.\n=== Incremental diagnostics ===\n' + incrementalSyntaxDiagnostics + '\n=== Reference Diagnostics ===\n' + referenceSyntaxDiagnostics);
}
var referenceSyntaxDiagnostics = referenceSourceFile.getSyntacticDiagnostics();
Utils.assertDiagnosticsEquals(incrementalSyntaxDiagnostics, referenceSyntaxDiagnostics);
Utils.assertStructuralEquals(incrementalSourceFile, referenceSourceFile);
//if (this.editValidation !== IncrementalEditValidation.SyntacticOnly) {
// var compiler = new TypeScript.TypeScriptCompiler();
// for (var i = 0; i < this.testData.files.length; i++) {
// snapshot = this.languageServiceShimHost.getScriptSnapshot(this.testData.files[i].fileName);
// compiler.addFile(this.testData.files[i].fileName, TypeScript.ScriptSnapshot.fromString(snapshot.getText(0, snapshot.getLength())), ts.ByteOrderMark.None, 0, true);
// }
// compiler.addFile('lib.d.ts', TypeScript.ScriptSnapshot.fromString(Harness.Compiler.libTextMinimal), ts.ByteOrderMark.None, 0, true);
// for (var i = 0; i < this.testData.files.length; i++) {
// var refSemanticErrs = JSON.stringify(compiler.getSemanticDiagnostics(this.testData.files[i].fileName));
// var incrSemanticErrs = JSON.stringify(this.languageService.getSemanticDiagnostics(this.testData.files[i].fileName));
// if (incrSemanticErrs !== refSemanticErrs) {
// this.raiseError('Mismatched incremental/full semantic errors for file ' + this.testData.files[i].fileName + '\n=== Incremental errors ===\n' + incrSemanticErrs + '\n=== Full Errors ===\n' + refSemanticErrs);
// }
// }
//}
}
private fixCaretPosition() {
@ -1416,14 +1413,14 @@ module FourSlash {
// We get back a set of edits, but langSvc.editScript only accepts one at a time. Use this to keep track
// of the incremental offset from each edit to the next. Assumption is that these edit ranges don't overlap
var runningOffset = 0;
edits = edits.sort((a, b) => a.span.start() - b.span.start());
edits = edits.sort((a, b) => a.span.start - b.span.start);
// Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters
var snapshot = this.languageServiceShimHost.getScriptSnapshot(fileName);
var oldContent = snapshot.getText(0, snapshot.getLength());
for (var j = 0; j < edits.length; j++) {
this.languageServiceShimHost.editScript(fileName, edits[j].span.start() + runningOffset, edits[j].span.end() + runningOffset, edits[j].newText);
this.updateMarkersForEdit(fileName, edits[j].span.start() + runningOffset, edits[j].span.end() + runningOffset, edits[j].newText);
var change = (edits[j].span.start() - edits[j].span.end()) + edits[j].newText.length;
this.languageServiceShimHost.editScript(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText);
this.updateMarkersForEdit(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText);
var change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length;
runningOffset += change;
// TODO: Consider doing this at least some of the time for higher fidelity. Currently causes a failure (bug 707150)
// this.languageService.getScriptLexicalStructure(fileName);
@ -1500,7 +1497,7 @@ module FourSlash {
var definition = definitions[definitionIndex];
this.openFile(definition.fileName);
this.currentCaretPosition = definition.textSpan.start();
this.currentCaretPosition = definition.textSpan.start;
}
public verifyDefinitionLocationExists(negative: boolean) {
@ -1518,6 +1515,14 @@ module FourSlash {
}
}
public verifyDefinitionsCount(negative: boolean, expectedCount: number) {
var assertFn = negative ? assert.notEqual : assert.equal;
var definitions = this.languageService.getDefinitionAtPosition(this.activeFile.fileName, this.currentCaretPosition);
assertFn(definitions.length, expectedCount, this.messageAtLastKnownMarker("Definitions Count"));
}
public verifyDefinitionsName(negative: boolean, expectedName: string, expectedContainerName: string) {
this.taoInvalidReason = 'verifyDefinititionsInfo NYI';
@ -1526,10 +1531,10 @@ module FourSlash {
var actualDefinitionContainerName = definitions && definitions.length ? definitions[0].containerName : "";
if (negative) {
assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.notEqual(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Container Name"));
assert.notEqual(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
} else {
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Name"));
assert.equal(actualDefinitionName, expectedName, this.messageAtLastKnownMarker("Definition Info Container Name"));
assert.equal(actualDefinitionContainerName, expectedContainerName, this.messageAtLastKnownMarker("Definition Info Container Name"));
}
}
@ -1621,7 +1626,7 @@ module FourSlash {
'\t Actual: undefined');
}
var actual = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(span.start(), span.end());
var actual = this.languageServiceShimHost.getScriptSnapshot(this.activeFile.fileName).getText(span.start, ts.textSpanEnd(span));
if (actual !== text) {
this.raiseError('verifyCurrentNameOrDottedNameSpanText\n' +
'\tExpected: "' + text + '"\n' +
@ -1676,15 +1681,15 @@ module FourSlash {
if (expectedSpan) {
var expectedLength = expectedSpan.end - expectedSpan.start;
if (expectedSpan.start !== actualSpan.start() || expectedLength !== actualSpan.length()) {
if (expectedSpan.start !== actualSpan.start || expectedLength !== actualSpan.length) {
this.raiseError("verifyClassifications failed - expected span of text to be " +
"{start=" + expectedSpan.start + ", length=" + expectedLength + "}, but was " +
"{start=" + actualSpan.start() + ", length=" + actualSpan.length() + "}" +
"{start=" + actualSpan.start + ", length=" + actualSpan.length + "}" +
jsonMismatchString());
}
}
var actualText = this.activeFile.content.substr(actualSpan.start(), actualSpan.length());
var actualText = this.activeFile.content.substr(actualSpan.start, actualSpan.length);
if (expectedClassification.text !== actualText) {
this.raiseError('verifyClassifications failed - expected classified text to be ' +
expectedClassification.text + ', but was ' +
@ -1702,14 +1707,14 @@ module FourSlash {
public verifySemanticClassifications(expected: { classificationType: string; text: string }[]) {
var actual = this.languageService.getSemanticClassifications(this.activeFile.fileName,
new ts.TextSpan(0, this.activeFile.content.length));
ts.createTextSpan(0, this.activeFile.content.length));
this.verifyClassifications(expected, actual);
}
public verifySyntacticClassifications(expected: { classificationType: string; text: string }[]) {
var actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName,
new ts.TextSpan(0, this.activeFile.content.length));
var actual = this.languageService.getSyntacticClassifications(this.activeFile.fileName,
ts.createTextSpan(0, this.activeFile.content.length));
this.verifyClassifications(expected, actual);
}
@ -1726,8 +1731,8 @@ module FourSlash {
for (var i = 0; i < spans.length; i++) {
var expectedSpan = spans[i];
var actualSpan = actual[i];
if (expectedSpan.start !== actualSpan.textSpan.start() || expectedSpan.end !== actualSpan.textSpan.end()) {
this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualSpan.textSpan.start() + ',' + actualSpan.textSpan.end() + ')');
if (expectedSpan.start !== actualSpan.textSpan.start || expectedSpan.end !== ts.textSpanEnd(actualSpan.textSpan)) {
this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualSpan.textSpan.start + ',' + ts.textSpanEnd(actualSpan.textSpan) + ')');
}
}
}
@ -1743,10 +1748,10 @@ module FourSlash {
for (var i = 0; i < spans.length; i++) {
var expectedSpan = spans[i];
var actualComment = actual[i];
var actualCommentSpan = new ts.TextSpan(actualComment.position, actualComment.message.length);
var actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length);
if (expectedSpan.start !== actualCommentSpan.start() || expectedSpan.end !== actualCommentSpan.end()) {
this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualCommentSpan.start() + ',' + actualCommentSpan.end() + ')');
if (expectedSpan.start !== actualCommentSpan.start || expectedSpan.end !== ts.textSpanEnd(actualCommentSpan)) {
this.raiseError('verifyOutliningSpans failed - span ' + (i + 1) + ' expected: (' + expectedSpan.start + ',' + expectedSpan.end + '), actual: (' + actualCommentSpan.start + ',' + ts.textSpanEnd(actualCommentSpan) + ')');
}
}
}
@ -1761,12 +1766,12 @@ module FourSlash {
}
var actualMatchPosition = -1;
if (bracePosition === actual[0].start()) {
actualMatchPosition = actual[1].start();
} else if (bracePosition === actual[1].start()) {
actualMatchPosition = actual[0].start();
if (bracePosition === actual[0].start) {
actualMatchPosition = actual[1].start;
} else if (bracePosition === actual[1].start) {
actualMatchPosition = actual[0].start;
} else {
this.raiseError('verifyMatchingBracePosition failed - could not find the brace position: ' + bracePosition + ' in the returned list: (' + actual[0].start() + ',' + actual[0].end() + ') and (' + actual[1].start() + ',' + actual[1].end() + ')');
this.raiseError('verifyMatchingBracePosition failed - could not find the brace position: ' + bracePosition + ' in the returned list: (' + actual[0].start + ',' + ts.textSpanEnd(actual[0]) + ') and (' + actual[1].start + ',' + ts.textSpanEnd(actual[1]) + ')');
}
if (actualMatchPosition !== expectedMatchPosition) {
@ -2006,7 +2011,7 @@ module FourSlash {
for (var i = 0; i < occurances.length; i++) {
var occurance = occurances[i];
if (occurance && occurance.fileName === fileName && occurance.textSpan.start() === start && occurance.textSpan.end() === end) {
if (occurance && occurance.fileName === fileName && occurance.textSpan.start === start && ts.textSpanEnd(occurance.textSpan) === end) {
if (typeof isWriteAccess !== "undefined" && occurance.isWriteAccess !== isWriteAccess) {
this.raiseError('verifyOccurancesAtPositionListContains failed - item isWriteAccess value doe not match, actual: ' + occurance.isWriteAccess + ', expected: ' + isWriteAccess + '.');
}
@ -2196,13 +2201,13 @@ module FourSlash {
ts.sys.useCaseSensitiveFileNames);
// TODO (drosen): We need to enforce checking on these tests.
var program = ts.createProgram([Harness.Compiler.fourslashFilename, fileName], { out: "fourslashTestOutput.js", noResolve: true, target: ts.ScriptTarget.ES3 }, host);
var checker = ts.createTypeChecker(program, /*fullTypeCheckMode*/ true);
var checker = ts.createTypeChecker(program, /*produceDiagnostics*/ true);
var errors = program.getDiagnostics().concat(checker.getDiagnostics());
if (errors.length > 0) {
throw new Error('Error compiling ' + fileName + ': ' + errors.map(e => e.messageText).join('\r\n'));
}
checker.emitFiles();
program.emitFiles();
result = result || ''; // Might have an empty fourslash file
// Compile and execute the test
@ -2590,4 +2595,4 @@ module FourSlash {
fileName: fileName
};
}
}
}

View file

@ -16,8 +16,6 @@
/// <reference path='..\services\services.ts' />
/// <reference path='..\services\shims.ts' />
/// <reference path='..\compiler\core.ts' />
/// <reference path='..\compiler\sys.ts' />
/// <reference path='external\mocha.d.ts'/>
/// <reference path='external\chai.d.ts'/>
/// <reference path='sourceMapRecorder.ts'/>
@ -290,6 +288,29 @@ module Utils {
}
}
export function assertDiagnosticsEquals(array1: ts.Diagnostic[], array2: ts.Diagnostic[]) {
if (array1 === array2) {
return;
}
assert(array1, "array1");
assert(array2, "array2");
assert.equal(array1.length, array2.length, "array1.length !== array2.length");
for (var i = 0, n = array1.length; i < n; i++) {
var d1 = array1[i];
var d2 = array2[i];
assert.equal(d1.start, d2.start, "d1.start !== d2.start");
assert.equal(d1.length, d2.length, "d1.length !== d2.length");
assert.equal(d1.messageText, d2.messageText, "d1.messageText !== d2.messageText");
assert.equal(d1.category, d2.category, "d1.category !== d2.category");
assert.equal(d1.code, d2.code, "d1.code !== d2.code");
assert.equal(d1.isEarly, d2.isEarly, "d1.isEarly !== d2.isEarly");
}
}
export function assertStructuralEquals(node1: ts.Node, node2: ts.Node) {
if (node1 === node2) {
return;
@ -886,7 +907,7 @@ module Harness {
public compileFiles(inputFiles: { unitName: string; content: string }[],
otherFiles: { unitName: string; content: string }[],
onComplete: (result: CompilerResult, checker: ts.TypeChecker) => void,
onComplete: (result: CompilerResult, program: ts.Program) => void,
settingsCallback?: (settings: ts.CompilerOptions) => void,
options?: ts.CompilerOptions) {
@ -1045,14 +1066,14 @@ module Harness {
options.target,
useCaseSensitiveFileNames));
var checker = program.getTypeChecker(/*fullTypeCheckMode*/ true);
var checker = program.getTypeChecker(/*produceDiagnostics*/ true);
var isEmitBlocked = checker.isEmitBlocked();
var isEmitBlocked = program.isEmitBlocked();
// only emit if there weren't parse errors
var emitResult: ts.EmitResult;
if (!isEmitBlocked) {
emitResult = checker.emitFiles();
emitResult = program.emitFiles();
}
var errors: HarnessDiagnostic[] = [];
@ -1063,7 +1084,7 @@ module Harness {
this.lastErrors = errors;
var result = new CompilerResult(fileOutputs, errors, program, ts.sys.getCurrentDirectory(), emitResult ? emitResult.sourceMaps : undefined);
onComplete(result, checker);
onComplete(result, program);
// reset what newline means in case the last test changed it
ts.sys.newLine = '\r\n';
@ -1106,29 +1127,27 @@ module Harness {
}
function findResultCodeFile(fileName: string) {
var dTsFileName = ts.forEach(result.program.getSourceFiles(), sourceFile => {
if (sourceFile.filename === fileName) {
// Is this file going to be emitted separately
var sourceFileName: string;
if (ts.isExternalModule(sourceFile) || !options.out) {
if (options.outDir) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, result.currentDirectoryForProgram);
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
}
else {
sourceFileName = sourceFile.filename;
}
}
else {
// Goes to single --out file
sourceFileName = options.out;
}
return ts.removeFileExtension(sourceFileName) + ".d.ts";
var sourceFile = result.program.getSourceFile(fileName);
assert(sourceFile, "Program has no source file with name '" + fileName + "'");
// Is this file going to be emitted separately
var sourceFileName: string;
if (ts.isExternalModule(sourceFile) || !options.out) {
if (options.outDir) {
var sourceFilePath = ts.getNormalizedAbsolutePath(sourceFile.filename, result.currentDirectoryForProgram);
sourceFilePath = sourceFilePath.replace(result.program.getCommonSourceDirectory(), "");
sourceFileName = ts.combinePaths(options.outDir, sourceFilePath);
}
});
else {
sourceFileName = sourceFile.filename;
}
}
else {
// Goes to single --out file
sourceFileName = options.out;
}
var dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
@ -1196,7 +1215,7 @@ module Harness {
// Report global errors
var globalErrors = diagnostics.filter(err => !err.filename);
globalErrors.forEach(err => outputErrorText(err));
globalErrors.forEach(outputErrorText);
// 'merge' the lines of each input file with any errors associated with it
inputFiles.filter(f => f.content !== undefined).forEach(inputFile => {

View file

@ -32,8 +32,8 @@ module Harness.LanguageService {
// Store edit range + new length of script
this.editRanges.push({
length: this.content.length,
textChangeRange: new ts.TextChangeRange(
ts.TextSpan.fromBounds(minChar, limChar), newText.length)
textChangeRange: ts.createTextChangeRange(
ts.createTextSpanFromBounds(minChar, limChar), newText.length)
});
// Update version #
@ -43,14 +43,14 @@ module Harness.LanguageService {
public getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange {
if (startVersion === endVersion) {
// No edits!
return ts.TextChangeRange.unchanged;
return ts.unchangedTextChangeRange;
}
var initialEditRangeIndex = this.editRanges.length - (this.version - startVersion);
var lastEditRangeIndex = this.editRanges.length - (this.version - endVersion);
var entries = this.editRanges.slice(initialEditRangeIndex, lastEditRangeIndex);
return ts.TextChangeRange.collapseChangesAcrossMultipleVersions(entries.map(e => e.textChangeRange));
return ts.collapseTextChangeRangesAcrossMultipleVersions(entries.map(e => e.textChangeRange));
}
}
@ -87,7 +87,7 @@ module Harness.LanguageService {
return null;
}
return JSON.stringify({ span: { start: range.span().start(), length: range.span().length() }, newLength: range.newLength() });
return JSON.stringify({ span: { start: range.span.start, length: range.span.length }, newLength: range.newLength });
}
}
@ -126,7 +126,7 @@ module Harness.LanguageService {
isOpen: boolean,
textChangeRange: ts.TextChangeRange
): ts.SourceFile {
return document.update(scriptSnapshot, version, isOpen, textChangeRange);
return ts.updateLanguageServiceSourceFile(document, scriptSnapshot, version, isOpen, textChangeRange);
}
public releaseDocument(fileName: string, compilationSettings: ts.CompilerOptions): void {
@ -346,9 +346,9 @@ module Harness.LanguageService {
for (var i = edits.length - 1; i >= 0; i--) {
var edit = edits[i];
var prefix = result.substring(0, edit.span.start());
var prefix = result.substring(0, edit.span.start);
var middle = edit.newText;
var suffix = result.substring(edit.span.end());
var suffix = result.substring(ts.textSpanEnd(edit.span));
result = prefix + middle + suffix;
}
return result;
@ -367,7 +367,7 @@ module Harness.LanguageService {
}
var temp = mapEdits(edits).sort(function (a, b) {
var result = a.edit.span.start() - b.edit.span.start();
var result = a.edit.span.start - b.edit.span.start;
if (result === 0)
result = a.index - b.index;
return result;
@ -386,7 +386,7 @@ module Harness.LanguageService {
}
var nextEdit = temp[next].edit;
var gap = nextEdit.span.start() - currentEdit.span.end();
var gap = nextEdit.span.start - ts.textSpanEnd(currentEdit.span);
// non-overlapping edits
if (gap >= 0) {
@ -398,7 +398,7 @@ module Harness.LanguageService {
// overlapping edits: for now, we only support ignoring an next edit
// entirely contained in the current edit.
if (currentEdit.span.end() >= nextEdit.span.end()) {
if (ts.textSpanEnd(currentEdit.span) >= ts.textSpanEnd(nextEdit.span)) {
next++;
continue;
}

View file

@ -130,9 +130,9 @@ class ProjectRunner extends RunnerBase {
var errors = program.getDiagnostics();
var sourceMapData: ts.SourceMapData[] = null;
if (!errors.length) {
var checker = program.getTypeChecker(/*fullTypeCheck*/ true);
var checker = program.getTypeChecker(/*produceDiagnostics:*/ true);
errors = checker.getDiagnostics();
var emitResult = checker.emitFiles();
var emitResult = program.emitFiles();
errors = ts.concatenate(errors, emitResult.diagnostics);
sourceMapData = emitResult.sourceMaps;

View file

@ -28,12 +28,6 @@ module RWC {
var compilerOptions: ts.CompilerOptions;
var baselineOpts: Harness.Baseline.BaselineOptions = { Subfolder: 'rwc' };
var baseName = /(.*)\/(.*).json/.exec(ts.normalizeSlashes(jsonPath))[2];
// Compile .d.ts files
var declFileCompilationResult: {
declInputFiles: { unitName: string; content: string }[];
declOtherFiles: { unitName: string; content: string }[];
declResult: Harness.Compiler.CompilerResult;
};
after(() => {
// Mocha holds onto the closure environment of the describe callback even after the test is done.
@ -44,7 +38,6 @@ module RWC {
compilerOptions = undefined;
baselineOpts = undefined;
baseName = undefined;
declFileCompilationResult = undefined;
});
it('can compile', () => {
@ -103,11 +96,6 @@ module RWC {
}
});
// Baselines
it('Correct compiler generated.d.ts', () => {
declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult, /*settingscallback*/ undefined, compilerOptions);
});
it('has the expected emitted code', () => {
Harness.Baseline.runBaseline('has the expected emitted code', baseName + '.output.js', () => {
@ -152,9 +140,12 @@ module RWC {
}, false, baselineOpts);
});
it('has no errors in generated declaration files', () => {
// Ideally, a generated declaration file will have no errors. But we allow generated
// declaration file errors as part of the baseline.
it('has the expected errors in generated declaration files', () => {
if (compilerOptions.declaration && !compilerResult.errors.length) {
Harness.Baseline.runBaseline('has no errors in generated declaration files', baseName + '.dts.errors.txt', () => {
Harness.Baseline.runBaseline('has the expected errors in generated declaration files', baseName + '.dts.errors.txt', () => {
var declFileCompilationResult = Harness.Compiler.getCompiler().compileDeclarationFiles(inputFiles, otherFiles, compilerResult, /*settingscallback*/ undefined, compilerOptions);
if (declFileCompilationResult.declResult.errors.length === 0) {
return null;
}

View file

@ -29,7 +29,7 @@ class Test262BaselineRunner extends RunnerBase {
filename: string;
compilerResult: Harness.Compiler.CompilerResult;
inputFiles: { unitName: string; content: string }[];
checker: ts.TypeChecker;
program: ts.Program;
};
before(() => {
@ -46,12 +46,12 @@ class Test262BaselineRunner extends RunnerBase {
filename: testFilename,
inputFiles: inputFiles,
compilerResult: undefined,
checker: undefined,
program: undefined,
};
Harness.Compiler.getCompiler().compileFiles([Test262BaselineRunner.helperFile].concat(inputFiles), /*otherFiles*/ [], (compilerResult, checker) => {
Harness.Compiler.getCompiler().compileFiles([Test262BaselineRunner.helperFile].concat(inputFiles), /*otherFiles*/ [], (compilerResult, program) => {
testState.compilerResult = compilerResult;
testState.checker = checker;
testState.program = program;
}, /*settingsCallback*/ undefined, Test262BaselineRunner.options);
});
@ -78,13 +78,13 @@ class Test262BaselineRunner extends RunnerBase {
});
it('satisfies invariants', () => {
var sourceFile = testState.checker.getProgram().getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
Utils.assertInvariants(sourceFile, /*parent:*/ undefined);
});
it('has the expected AST',() => {
Harness.Baseline.runBaseline('has the expected AST', testState.filename + '.AST.txt',() => {
var sourceFile = testState.checker.getProgram().getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
var sourceFile = testState.program.getSourceFile(Test262BaselineRunner.getTestFilePath(testState.filename));
return Utils.sourceFileToJSON(sourceFile);
}, false, Test262BaselineRunner.baselineOptions);
});

View file

@ -10,11 +10,16 @@ class TypeWriterWalker {
results: TypeWriterResult[];
currentSourceFile: ts.SourceFile;
constructor(public checker: ts.TypeChecker) {
private checker: ts.TypeChecker;
constructor(private program: ts.Program) {
// Consider getting both the diagnostics checker and the non-diagnostics checker to verify
// they are consistent.
this.checker = program.getTypeChecker(/*produceDiagnostics:*/ true);
}
public getTypes(fileName: string): TypeWriterResult[] {
var sourceFile = this.checker.getProgram().getSourceFile(fileName);
var sourceFile = this.program.getSourceFile(fileName);
this.currentSourceFile = sourceFile;
this.results = [];
this.visitNode(sourceFile);

View file

@ -78,7 +78,7 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr
var processedFiles: ProcessedFile[] = [];
for (var i = 0, len = sourceFiles.length; i < len; ++i) {
var f = sourceFiles[i];
var fileSpan = new ts.TextSpan(0, f.text.length);
var fileSpan = ts.createTextSpan(0, f.text.length);
var syntacticClassifications = ls.getSyntacticClassifications(f.filename, fileSpan);
var convertedSyntactic = convertClassifications(syntacticClassifications, f, /*addHyperlinks*/ true);
@ -235,8 +235,8 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr
}
var classification = c.classificationType;
var start = c.textSpan.start();
var length = c.textSpan.length();
var start = c.textSpan.start;
var length = c.textSpan.length;
var hyperlinks: Hyperlink[];
var definitionSymbolId: string;
@ -305,7 +305,7 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr
hyperlinks = [];
}
var defStart = d.textSpan.start();
var defStart = d.textSpan.start;
var defFile = program.getSourceFile(d.fileName);
var token = ts.getTouchingToken(defFile, defStart, /*includeItemAtEndPosition*/ undefined);
@ -321,7 +321,7 @@ function analyze(libFileName: string, files: string[], outputFolder: string): Pr
}
var link: Hyperlink = {
sourceFile: d.fileName,
start: d.textSpan.start(),
start: d.textSpan.start,
symbolId: makeSymbolId(d.fileName, defStart)
};
hyperlinks.push(link);

View file

@ -38,7 +38,7 @@ module ts.BreakpointResolver {
return spanInNode(tokenAtLocation);
function textSpan(startNode: Node, endNode?: Node) {
return TextSpan.fromBounds(startNode.getStart(), (endNode || startNode).getEnd());
return createTextSpanFromBounds(startNode.getStart(), (endNode || startNode).getEnd());
}
function spanInNodeIfStartsOnSameLine(node: Node, otherwiseOnNode?: Node): TextSpan {
@ -83,7 +83,7 @@ module ts.BreakpointResolver {
switch (node.kind) {
case SyntaxKind.VariableStatement:
// Span on first variable declaration
return spanInVariableDeclaration((<VariableStatement>node).declarations[0]);
return spanInVariableDeclaration((<VariableStatement>node).declarationList.declarations[0]);
case SyntaxKind.VariableDeclaration:
case SyntaxKind.PropertyDeclaration:
@ -108,8 +108,6 @@ module ts.BreakpointResolver {
return spanInFunctionBlock(<Block>node);
}
// Fall through
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
return spanInBlock(<Block>node);
@ -263,16 +261,16 @@ module ts.BreakpointResolver {
function spanInVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan {
// If declaration of for in statement, just set the span in parent
if (variableDeclaration.parent.kind === SyntaxKind.ForInStatement) {
return spanInNode(variableDeclaration.parent);
if (variableDeclaration.parent.parent.kind === SyntaxKind.ForInStatement) {
return spanInNode(variableDeclaration.parent.parent);
}
var isParentVariableStatement = variableDeclaration.parent.kind === SyntaxKind.VariableStatement;
var isDeclarationOfForStatement = variableDeclaration.parent.kind === SyntaxKind.ForStatement && contains((<ForStatement>variableDeclaration.parent).declarations, variableDeclaration);
var isParentVariableStatement = variableDeclaration.parent.parent.kind === SyntaxKind.VariableStatement;
var isDeclarationOfForStatement = variableDeclaration.parent.parent.kind === SyntaxKind.ForStatement && contains((<VariableDeclarationList>(<ForStatement>variableDeclaration.parent.parent).initializer).declarations, variableDeclaration);
var declarations = isParentVariableStatement
? (<VariableStatement>variableDeclaration.parent).declarations
? (<VariableStatement>variableDeclaration.parent.parent).declarationList.declarations
: isDeclarationOfForStatement
? (<ForStatement>variableDeclaration.parent).declarations
? (<VariableDeclarationList>(<ForStatement>variableDeclaration.parent.parent).initializer).declarations
: undefined;
// Breakpoint is possible in variableDeclaration only if there is initialization
@ -376,12 +374,18 @@ module ts.BreakpointResolver {
}
function spanInForStatement(forStatement: ForStatement): TextSpan {
if (forStatement.declarations) {
return spanInNode(forStatement.declarations[0]);
}
if (forStatement.initializer) {
return spanInNode(forStatement.initializer);
if (forStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
var variableDeclarationList = <VariableDeclarationList>forStatement.initializer;
if (variableDeclarationList.declarations.length > 0) {
return spanInNode(variableDeclarationList.declarations[0]);
}
}
else {
return spanInNode(forStatement.initializer);
}
}
if (forStatement.condition) {
return textSpan(forStatement.condition);
}
@ -429,9 +433,7 @@ module ts.BreakpointResolver {
}
// fall through.
case SyntaxKind.TryBlock:
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyBlock:
return spanInNode((<Block>node.parent).statements[(<Block>node.parent).statements.length - 1]);;
case SyntaxKind.SwitchStatement:

View file

@ -154,8 +154,6 @@ module ts.formatting {
return body && body.kind === SyntaxKind.Block && rangeContainsRange((<Block>body).statements, node);
case SyntaxKind.SourceFile:
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
return rangeContainsRange((<Block>parent).statements, node);
case SyntaxKind.CatchClause:
@ -875,7 +873,7 @@ module ts.formatting {
}
function newTextChange(start: number, len: number, newText: string): TextChange {
return { span: new TextSpan(start, len), newText }
return { span: createTextSpan(start, len), newText }
}
function recordDelete(start: number, len: number) {
@ -939,9 +937,6 @@ module ts.formatting {
function isSomeBlock(kind: SyntaxKind): boolean {
switch (kind) {
case SyntaxKind.Block:
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
return true;
}

View file

@ -525,8 +525,6 @@ module ts.formatting {
case SyntaxKind.Block:
case SyntaxKind.SwitchStatement:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
return true;
}
@ -580,9 +578,7 @@ module ts.formatting {
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.SwitchStatement:
return true;
@ -603,7 +599,6 @@ module ts.formatting {
// TODO
// case SyntaxKind.ElseClause:
case SyntaxKind.CatchClause:
case SyntaxKind.FinallyBlock:
return true;
default:

View file

@ -327,8 +327,6 @@ module ts.formatting {
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.Block:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.TypeLiteral:
@ -404,7 +402,6 @@ module ts.formatting {
case SyntaxKind.EnumDeclaration:
case SyntaxKind.ObjectLiteralExpression:
case SyntaxKind.Block:
case SyntaxKind.FinallyBlock:
case SyntaxKind.ModuleBlock:
case SyntaxKind.SwitchStatement:
return nodeEndsWith(n, SyntaxKind.CloseBraceToken, sourceFile);

View file

@ -125,10 +125,8 @@ module ts.formatting {
static Any: TokenRange = TokenRange.AllTokens();
static AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([SyntaxKind.MultiLineCommentTrivia]));
static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword);
static Operators = TokenRange.FromRange(SyntaxKind.FirstOperator, SyntaxKind.LastOperator);
static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator);
static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword]);
static ReservedKeywords = TokenRange.FromRange(SyntaxKind.FirstFutureReservedWord, SyntaxKind.LastFutureReservedWord);
static UnaryPrefixOperators = TokenRange.FromTokens([SyntaxKind.PlusPlusToken, SyntaxKind.MinusMinusToken, SyntaxKind.TildeToken, SyntaxKind.ExclamationToken]);
static UnaryPrefixExpressions = TokenRange.FromTokens([SyntaxKind.NumericLiteral, SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.OpenBracketToken, SyntaxKind.OpenBraceToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);
static UnaryPreincrementExpressions = TokenRange.FromTokens([SyntaxKind.Identifier, SyntaxKind.OpenParenToken, SyntaxKind.ThisKeyword, SyntaxKind.NewKeyword]);

View file

@ -44,7 +44,7 @@ module ts.NavigationBar {
function visit(node: Node) {
switch (node.kind) {
case SyntaxKind.VariableStatement:
forEach((<VariableStatement>node).declarations, visit);
forEach((<VariableStatement>node).declarationList.declarations, visit);
break;
case SyntaxKind.ObjectBindingPattern:
case SyntaxKind.ArrayBindingPattern:
@ -462,8 +462,8 @@ module ts.NavigationBar {
function getNodeSpan(node: Node) {
return node.kind === SyntaxKind.SourceFile
? TextSpan.fromBounds(node.getFullStart(), node.getEnd())
: TextSpan.fromBounds(node.getStart(), node.getEnd());
? createTextSpanFromBounds(node.getFullStart(), node.getEnd())
: createTextSpanFromBounds(node.getStart(), node.getEnd());
}
function getTextOfNode(node: Node): string {

View file

@ -22,8 +22,8 @@ module ts {
function addOutliningSpan(hintSpanNode: Node, startElement: Node, endElement: Node, autoCollapse: boolean) {
if (hintSpanNode && startElement && endElement) {
var span: OutliningSpan = {
textSpan: TextSpan.fromBounds(startElement.pos, endElement.end),
hintSpan: TextSpan.fromBounds(hintSpanNode.getStart(), hintSpanNode.end),
textSpan: createTextSpanFromBounds(startElement.pos, endElement.end),
hintSpan: createTextSpanFromBounds(hintSpanNode.getStart(), hintSpanNode.end),
bannerText: collapseText,
autoCollapse: autoCollapse
};
@ -68,25 +68,41 @@ module ts {
parent.kind === SyntaxKind.CatchClause) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
else {
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
var span = TextSpan.fromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
if (parent.kind === SyntaxKind.TryStatement) {
// Could be the try-block, or the finally-block.
var tryStatement = <TryStatement>parent;
if (tryStatement.tryBlock === n) {
addOutliningSpan(parent, openBrace, closeBrace, autoCollapse(n));
break;
}
else if (tryStatement.finallyBlock === n) {
var finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile);
if (finallyKeyword) {
addOutliningSpan(finallyKeyword, openBrace, closeBrace, autoCollapse(n));
break;
}
}
// fall through.
}
// Block was a standalone block. In this case we want to only collapse
// the span of the block, independent of any parent span.
var span = createTextSpanFromBounds(n.getStart(), n.end);
elements.push({
textSpan: span,
hintSpan: span,
bannerText: collapseText,
autoCollapse: autoCollapse(n)
});
break;
}
// Fallthrough.
case SyntaxKind.ModuleBlock:
case SyntaxKind.TryBlock:
case SyntaxKind.FinallyBlock:
var openBrace = findChildOfKind(n, SyntaxKind.OpenBraceToken, sourceFile);
var closeBrace = findChildOfKind(n, SyntaxKind.CloseBraceToken, sourceFile);
addOutliningSpan(n.parent, openBrace, closeBrace, autoCollapse(n));

File diff suppressed because it is too large Load diff

View file

@ -203,8 +203,8 @@ module ts {
}
var decoded: { span: { start: number; length: number; }; newLength: number; } = JSON.parse(encoded);
return new TextChangeRange(
new TextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
return createTextChangeRange(
createTextSpan(decoded.span.start, decoded.span.length), decoded.newLength);
}
}
@ -391,7 +391,7 @@ module ts {
return this.forwardJSONCall(
"getSyntacticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
var classifications = this.languageService.getSyntacticClassifications(fileName, new TextSpan(start, length));
var classifications = this.languageService.getSyntacticClassifications(fileName, createTextSpan(start, length));
return classifications;
});
}
@ -400,7 +400,7 @@ module ts {
return this.forwardJSONCall(
"getSemanticClassifications('" + fileName + "', " + start + ", " + length + ")",
() => {
var classifications = this.languageService.getSemanticClassifications(fileName, new TextSpan(start, length));
var classifications = this.languageService.getSemanticClassifications(fileName, createTextSpan(start, length));
return classifications;
});
}

View file

@ -367,7 +367,7 @@ module ts.SignatureHelp {
// but not including parentheses)
var applicableSpanStart = argumentsList.getFullStart();
var applicableSpanEnd = skipTrivia(sourceFile.text, argumentsList.getEnd(), /*stopAfterLineBreak*/ false);
return new TextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getApplicableSpanForTaggedTemplate(taggedTemplate: TaggedTemplateExpression): TextSpan {
@ -391,7 +391,7 @@ module ts.SignatureHelp {
}
}
return new TextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
return createTextSpan(applicableSpanStart, applicableSpanEnd - applicableSpanStart);
}
function getContainingArgumentInfo(node: Node): ArgumentListInfo {

View file

@ -271,7 +271,7 @@ module ts {
}
export function getNodeModifiers(node: Node): string {
var flags = node.flags;
var flags = getCombinedNodeFlags(node);
var result: string[] = [];
if (flags & NodeFlags.Private) result.push(ScriptElementKindModifier.privateMemberModifier);

View file

@ -1,13 +1,10 @@
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,10): error TS2391: Function implementation is missing or not immediately following the declaration.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,14): error TS1138: Parameter declaration expected.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,14): error TS2304: Cannot find name 'yield'.
tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts(1,19): error TS1005: ';' expected.
==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts (4 errors) ====
==== tests/cases/conformance/es6/functionDeclarations/FunctionDeclaration5_es6.ts (3 errors) ====
function*foo(yield) {
~~~
!!! error TS2391: Function implementation is missing or not immediately following the declaration.
~~~~~
!!! error TS1138: Parameter declaration expected.
~~~~~

View file

@ -1,7 +1,7 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration10_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration10_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration10_es6.ts (1 errors) ====
let a: number = 1
~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,10 +1,10 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts(1,7): error TS1155: 'const' declarations must be initialized
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration2_es6.ts (2 errors) ====
const a
~
~~~~~
!!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
~
!!! error TS1155: 'const' declarations must be initialized

View file

@ -1,7 +1,7 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration3_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration3_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration3_es6.ts (1 errors) ====
const a = 1
~
~~~~~
!!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,10 +1,10 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts(1,7): error TS1155: 'const' declarations must be initialized
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration4_es6.ts (2 errors) ====
const a: number
~
~~~~~
!!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
~
!!! error TS1155: 'const' declarations must be initialized

View file

@ -1,7 +1,7 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration5_es6.ts(1,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration5_es6.ts(1,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration5_es6.ts (1 errors) ====
const a: number = 1
~
~~~~~
!!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,7 +1,7 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration7_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration7_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration7_es6.ts (1 errors) ====
let a
~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,7 +1,7 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration8_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration8_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration8_es6.ts (1 errors) ====
let a = 1
~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,7 +1,7 @@
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration9_es6.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/conformance/es6/variableDeclarations/VariableDeclaration9_es6.ts(1,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/conformance/es6/variableDeclarations/VariableDeclaration9_es6.ts (1 errors) ====
let a: number
~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,29 +1,18 @@
tests/cases/compiler/anonymousModules.ts(1,1): error TS2304: Cannot find name 'module'.
tests/cases/compiler/anonymousModules.ts(1,8): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(2,2): error TS1129: Statement expected.
tests/cases/compiler/anonymousModules.ts(2,2): error TS1148: Cannot compile external modules unless the '--module' flag is provided.
tests/cases/compiler/anonymousModules.ts(4,2): error TS2304: Cannot find name 'module'.
tests/cases/compiler/anonymousModules.ts(4,9): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(5,3): error TS1129: Statement expected.
tests/cases/compiler/anonymousModules.ts(5,14): error TS2395: Individual declarations in merged declaration bar must be all exported or all local.
tests/cases/compiler/anonymousModules.ts(6,2): error TS1128: Declaration or statement expected.
tests/cases/compiler/anonymousModules.ts(8,6): error TS2395: Individual declarations in merged declaration bar must be all exported or all local.
tests/cases/compiler/anonymousModules.ts(10,2): error TS2304: Cannot find name 'module'.
tests/cases/compiler/anonymousModules.ts(10,9): error TS1005: ';' expected.
tests/cases/compiler/anonymousModules.ts(13,1): error TS1128: Declaration or statement expected.
==== tests/cases/compiler/anonymousModules.ts (13 errors) ====
==== tests/cases/compiler/anonymousModules.ts (6 errors) ====
module {
~~~~~~
!!! error TS2304: Cannot find name 'module'.
~
!!! error TS1005: ';' expected.
export var foo = 1;
~~~~~~
!!! error TS1129: Statement expected.
~~~~~~~~~~~~~~~~~~~
!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided.
module {
~~~~~~
@ -31,17 +20,9 @@ tests/cases/compiler/anonymousModules.ts(13,1): error TS1128: Declaration or sta
~
!!! error TS1005: ';' expected.
export var bar = 1;
~~~~~~
!!! error TS1129: Statement expected.
~~~
!!! error TS2395: Individual declarations in merged declaration bar must be all exported or all local.
}
~
!!! error TS1128: Declaration or statement expected.
var bar = 2;
~~~
!!! error TS2395: Individual declarations in merged declaration bar must be all exported or all local.
module {
~~~~~~
@ -50,6 +31,4 @@ tests/cases/compiler/anonymousModules.ts(13,1): error TS1128: Declaration or sta
!!! error TS1005: ';' expected.
var x = bar;
}
}
~
!!! error TS1128: Declaration or statement expected.
}

View file

@ -76,21 +76,21 @@
--------------------------------
7 > export const cc1 = false;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (181 to 210) SpanInfo: {"start":185,"length":24}
>export const cc1 = false
>:=> (line 7, col 4) to (line 7, col 28)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (181 to 210) SpanInfo: {"start":192,"length":17}
>const cc1 = false
>:=> (line 7, col 11) to (line 7, col 28)
--------------------------------
8 > export const cc2: number = 23;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (211 to 245) SpanInfo: {"start":215,"length":29}
>export const cc2: number = 23
>:=> (line 8, col 4) to (line 8, col 33)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (211 to 245) SpanInfo: {"start":222,"length":22}
>const cc2: number = 23
>:=> (line 8, col 11) to (line 8, col 33)
--------------------------------
9 > export const cc3 = 0, cc4 :string = "", cc5 = null;
~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (246 to 270) SpanInfo: {"start":250,"length":20}
>export const cc3 = 0
>:=> (line 9, col 4) to (line 9, col 24)
~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (246 to 270) SpanInfo: {"start":257,"length":13}
>const cc3 = 0
>:=> (line 9, col 11) to (line 9, col 24)
9 > export const cc3 = 0, cc4 :string = "", cc5 = null;
~~~~~~~~~~~~~~~~~~ => Pos: (271 to 288) SpanInfo: {"start":272,"length":16}

View file

@ -84,9 +84,9 @@
--------------------------------
11 > export let ll2 = 0;
~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (221 to 244) SpanInfo: {"start":225,"length":18}
>export let ll2 = 0
>:=> (line 11, col 4) to (line 11, col 22)
~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (221 to 244) SpanInfo: {"start":232,"length":11}
>let ll2 = 0
>:=> (line 11, col 11) to (line 11, col 22)
--------------------------------
12 >}
~ => Pos: (245 to 245) SpanInfo: {"start":245,"length":1}

View file

@ -50,9 +50,9 @@
--------------------------------
7 > export var x = 30;
~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (67 to 93) SpanInfo: {"start":75,"length":17}
>export var x = 30
>:=> (line 7, col 8) to (line 7, col 25)
~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (67 to 93) SpanInfo: {"start":82,"length":10}
>var x = 30
>:=> (line 7, col 15) to (line 7, col 25)
--------------------------------
8 > }
@ -172,15 +172,15 @@
--------------------------------
25 > {
~~~~~~ => Pos: (261 to 266) SpanInfo: {"start":275,"length":17}
>export var x = 30
>:=> (line 26, col 8) to (line 26, col 25)
~~~~~~ => Pos: (261 to 266) SpanInfo: {"start":282,"length":10}
>var x = 30
>:=> (line 26, col 15) to (line 26, col 25)
--------------------------------
26 > export var x = 30;
~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (267 to 293) SpanInfo: {"start":275,"length":17}
>export var x = 30
>:=> (line 26, col 8) to (line 26, col 25)
~~~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (267 to 293) SpanInfo: {"start":282,"length":10}
>var x = 30
>:=> (line 26, col 15) to (line 26, col 25)
--------------------------------
27 > }

View file

@ -58,15 +58,13 @@
--------------------------------
9 > export var xx1;
~~~~~~~~~~~~~~~~~~~~ => Pos: (119 to 138) SpanInfo: {"start":123,"length":14}
>export var xx1
>:=> (line 9, col 4) to (line 9, col 18)
~~~~~~~~~~~~~~~~~~~~ => Pos: (119 to 138) SpanInfo: undefined
--------------------------------
10 > export var xx2 = 10, xx3 = 10;
~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (139 to 162) SpanInfo: {"start":143,"length":19}
>export var xx2 = 10
>:=> (line 10, col 4) to (line 10, col 23)
~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (139 to 162) SpanInfo: {"start":150,"length":12}
>var xx2 = 10
>:=> (line 10, col 11) to (line 10, col 23)
10 > export var xx2 = 10, xx3 = 10;
~~~~~~~~~~~ => Pos: (163 to 173) SpanInfo: {"start":164,"length":8}
@ -75,14 +73,7 @@
--------------------------------
11 > export var xx4, xx5;
~~~~~~~~~~~~~~~~~~~ => Pos: (174 to 192) SpanInfo: {"start":178,"length":14}
>export var xx4
>:=> (line 11, col 4) to (line 11, col 18)
11 > export var xx4, xx5;
~~~~~~ => Pos: (193 to 198) SpanInfo: {"start":194,"length":3}
>xx5
>:=> (line 11, col 20) to (line 11, col 23)
~~~~~~~~~~~~~~~~~~~~~~~~~ => Pos: (174 to 198) SpanInfo: undefined
--------------------------------
12 >}
~ => Pos: (199 to 199) SpanInfo: {"start":199,"length":1}

View file

@ -1,11 +1,12 @@
tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(4,14): error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(11,9): error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(20,5): error TS2300: Duplicate identifier 'foo'.
tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(20,9): error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(20,15): error TS1005: '{' expected.
tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts(21,5): error TS2300: Duplicate identifier 'foo'.
==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts (5 errors) ====
==== tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWithParameterInitializers2.ts (6 errors) ====
// Optional parameters allow initializers only in implementation signatures
// All the below declarations are errors
@ -32,6 +33,8 @@ tests/cases/conformance/types/objectTypeLiteral/callSignatures/callSignaturesWit
foo(x = 1), // error
~~~
!!! error TS2300: Duplicate identifier 'foo'.
~~~~~
!!! error TS2371: A parameter initializer is only allowed in a function or constructor implementation.
~
!!! error TS1005: '{' expected.
foo(x = 1) { }, // error

View file

@ -0,0 +1,22 @@
tests/cases/compiler/cloduleWithPriorInstantiatedModule.ts(2,8): error TS2434: A module declaration cannot be located prior to a class or function with which it is merged
==== tests/cases/compiler/cloduleWithPriorInstantiatedModule.ts (1 errors) ====
// Non-ambient & instantiated module.
module Moclodule {
~~~~~~~~~
!!! error TS2434: A module declaration cannot be located prior to a class or function with which it is merged
export interface Someinterface {
foo(): void;
}
var x = 10;
}
class Moclodule {
}
// Instantiated module.
module Moclodule {
export class Manager {
}
}

View file

@ -0,0 +1,39 @@
//// [cloduleWithPriorInstantiatedModule.ts]
// Non-ambient & instantiated module.
module Moclodule {
export interface Someinterface {
foo(): void;
}
var x = 10;
}
class Moclodule {
}
// Instantiated module.
module Moclodule {
export class Manager {
}
}
//// [cloduleWithPriorInstantiatedModule.js]
// Non-ambient & instantiated module.
var Moclodule;
(function (Moclodule) {
var x = 10;
})(Moclodule || (Moclodule = {}));
var Moclodule = (function () {
function Moclodule() {
}
return Moclodule;
})();
// Instantiated module.
var Moclodule;
(function (Moclodule) {
var Manager = (function () {
function Manager() {
}
return Manager;
})();
Moclodule.Manager = Manager;
})(Moclodule || (Moclodule = {}));

View file

@ -0,0 +1,33 @@
//// [cloduleWithPriorUninstantiatedModule.ts]
// Non-ambient & uninstantiated module.
module Moclodule {
export interface Someinterface {
foo(): void;
}
}
class Moclodule {
}
// Instantiated module.
module Moclodule {
export class Manager {
}
}
//// [cloduleWithPriorUninstantiatedModule.js]
var Moclodule = (function () {
function Moclodule() {
}
return Moclodule;
})();
// Instantiated module.
var Moclodule;
(function (Moclodule) {
var Manager = (function () {
function Manager() {
}
return Manager;
})();
Moclodule.Manager = Manager;
})(Moclodule || (Moclodule = {}));

View file

@ -0,0 +1,25 @@
=== tests/cases/compiler/cloduleWithPriorUninstantiatedModule.ts ===
// Non-ambient & uninstantiated module.
module Moclodule {
>Moclodule : typeof Moclodule
export interface Someinterface {
>Someinterface : Someinterface
foo(): void;
>foo : () => void
}
}
class Moclodule {
>Moclodule : Moclodule
}
// Instantiated module.
module Moclodule {
>Moclodule : typeof Moclodule
export class Manager {
>Manager : Manager
}
}

View file

@ -1,25 +1,19 @@
tests/cases/compiler/conflictMarkerTrivia1.ts(2,1): error TS1184: Merge conflict marker encountered.
tests/cases/compiler/conflictMarkerTrivia1.ts(3,5): error TS2300: Duplicate identifier 'v'.
tests/cases/compiler/conflictMarkerTrivia1.ts(4,1): error TS1184: Merge conflict marker encountered.
tests/cases/compiler/conflictMarkerTrivia1.ts(5,5): error TS2300: Duplicate identifier 'v'.
tests/cases/compiler/conflictMarkerTrivia1.ts(6,1): error TS1184: Merge conflict marker encountered.
tests/cases/compiler/conflictMarkerTrivia1.ts(2,1): error TS1185: Merge conflict marker encountered.
tests/cases/compiler/conflictMarkerTrivia1.ts(4,1): error TS1185: Merge conflict marker encountered.
tests/cases/compiler/conflictMarkerTrivia1.ts(6,1): error TS1185: Merge conflict marker encountered.
==== tests/cases/compiler/conflictMarkerTrivia1.ts (5 errors) ====
==== tests/cases/compiler/conflictMarkerTrivia1.ts (3 errors) ====
class C {
<<<<<<< HEAD
!!! error TS1184: Merge conflict marker encountered.
~~~~~~~
!!! error TS1185: Merge conflict marker encountered.
v = 1;
~
!!! error TS2300: Duplicate identifier 'v'.
=======
!!! error TS1184: Merge conflict marker encountered.
~~~~~~~
!!! error TS1185: Merge conflict marker encountered.
v = 2;
~
!!! error TS2300: Duplicate identifier 'v'.
>>>>>>> Branch-a
!!! error TS1184: Merge conflict marker encountered.
~~~~~~~
!!! error TS1185: Merge conflict marker encountered.
}

View file

@ -0,0 +1,28 @@
tests/cases/compiler/conflictMarkerTrivia2.ts(3,1): error TS1185: Merge conflict marker encountered.
tests/cases/compiler/conflictMarkerTrivia2.ts(4,6): error TS2304: Cannot find name 'a'.
tests/cases/compiler/conflictMarkerTrivia2.ts(6,1): error TS1185: Merge conflict marker encountered.
tests/cases/compiler/conflictMarkerTrivia2.ts(9,1): error TS1185: Merge conflict marker encountered.
==== tests/cases/compiler/conflictMarkerTrivia2.ts (4 errors) ====
class C {
foo() {
<<<<<<< B
~~~~~~~
!!! error TS1185: Merge conflict marker encountered.
a();
~
!!! error TS2304: Cannot find name 'a'.
}
=======
~~~~~~~
!!! error TS1185: Merge conflict marker encountered.
b();
}
>>>>>>> A
~~~~~~~
!!! error TS1185: Merge conflict marker encountered.
public bar() { }
}

View file

@ -1,17 +1,17 @@
tests/cases/compiler/constDeclarations-es5.ts(2,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/constDeclarations-es5.ts(3,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/constDeclarations-es5.ts(4,7): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/constDeclarations-es5.ts(2,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/constDeclarations-es5.ts(3,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/constDeclarations-es5.ts(4,1): error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/compiler/constDeclarations-es5.ts (3 errors) ====
const z7 = false;
~~
~~~~~
!!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
const z8: number = 23;
~~
~~~~~
!!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.
const z9 = 0, z10 :string = "", z11 = null;
~~
~~~~~
!!! error TS1154: 'const' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,14 +1,9 @@
tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(2,22): error TS2339: Property 'foo' does not exist on type 'string'.
tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts(3,10): error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly.
Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'number'.
==== tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts (2 errors) ====
==== tests/cases/compiler/contextualTypingWithFixedTypeParameters1.ts (1 errors) ====
var f10: <T>(x: T, b: () => (a: T) => void, y: T) => T;
f10('', () => a => a.foo, ''); // a is string
~~~
!!! error TS2339: Property 'foo' does not exist on type 'string'.
var r9 = f10('', () => (a => a.foo), 1); // error
~~~
!!! error TS2453: The type argument for type parameter 'T' cannot be inferred from the usage. Consider specifying the type arguments explicitly.
!!! error TS2453: Type argument candidate 'string' is not a valid type argument because it is not a supertype of candidate 'number'.
var r9 = f10('', () => (a => a.foo), 1); // error

View file

@ -1,14 +1,11 @@
tests/cases/compiler/dottedModuleName.ts(3,18): error TS2391: Function implementation is missing or not immediately following the declaration.
tests/cases/compiler/dottedModuleName.ts(3,29): error TS1144: '{' or ';' expected.
tests/cases/compiler/dottedModuleName.ts(3,33): error TS2304: Cannot find name 'x'.
==== tests/cases/compiler/dottedModuleName.ts (3 errors) ====
==== tests/cases/compiler/dottedModuleName.ts (2 errors) ====
module M {
export module N {
export function f(x:number)=>2*x;
~
!!! error TS2391: Function implementation is missing or not immediately following the declaration.
~~
!!! error TS1144: '{' or ';' expected.
~

View file

@ -0,0 +1,35 @@
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(2,4): error TS1184: Modifiers cannot appear here.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(2,21): error TS2393: Duplicate function implementation.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(2,25): error TS1184: An implementation cannot be declared in ambient contexts.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(3,4): error TS1184: Modifiers cannot appear here.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(3,20): error TS2393: Duplicate function implementation.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,4): error TS1184: Modifiers cannot appear here.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,12): error TS1029: 'export' modifier must precede 'declare' modifier.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,28): error TS2393: Duplicate function implementation.
tests/cases/compiler/functionsWithModifiersInBlocks1.ts(4,32): error TS1184: An implementation cannot be declared in ambient contexts.
==== tests/cases/compiler/functionsWithModifiersInBlocks1.ts (9 errors) ====
{
declare function f() { }
~~~~~~~
!!! error TS1184: Modifiers cannot appear here.
~
!!! error TS2393: Duplicate function implementation.
~
!!! error TS1184: An implementation cannot be declared in ambient contexts.
export function f() { }
~~~~~~
!!! error TS1184: Modifiers cannot appear here.
~
!!! error TS2393: Duplicate function implementation.
declare export function f() { }
~~~~~~~
!!! error TS1184: Modifiers cannot appear here.
~~~~~~
!!! error TS1029: 'export' modifier must precede 'declare' modifier.
~
!!! error TS2393: Duplicate function implementation.
~
!!! error TS1184: An implementation cannot be declared in ambient contexts.
}

View file

@ -0,0 +1,17 @@
tests/cases/compiler/genericAndNonGenericInheritedSignature1.ts(7,11): error TS2320: Interface 'Hello' cannot simultaneously extend types 'Foo' and 'Bar'.
Named properties 'f' of types 'Foo' and 'Bar' are not identical.
==== tests/cases/compiler/genericAndNonGenericInheritedSignature1.ts (1 errors) ====
interface Foo {
f(x: any): any;
}
interface Bar {
f<T>(x: T): T;
}
interface Hello extends Foo, Bar {
~~~~~
!!! error TS2320: Interface 'Hello' cannot simultaneously extend types 'Foo' and 'Bar'.
!!! error TS2320: Named properties 'f' of types 'Foo' and 'Bar' are not identical.
}

View file

@ -0,0 +1,12 @@
//// [genericAndNonGenericInheritedSignature1.ts]
interface Foo {
f(x: any): any;
}
interface Bar {
f<T>(x: T): T;
}
interface Hello extends Foo, Bar {
}
//// [genericAndNonGenericInheritedSignature1.js]

View file

@ -0,0 +1,17 @@
tests/cases/compiler/genericAndNonGenericInheritedSignature2.ts(7,11): error TS2320: Interface 'Hello' cannot simultaneously extend types 'Bar' and 'Foo'.
Named properties 'f' of types 'Bar' and 'Foo' are not identical.
==== tests/cases/compiler/genericAndNonGenericInheritedSignature2.ts (1 errors) ====
interface Foo {
f(x: any): any;
}
interface Bar {
f<T>(x: T): T;
}
interface Hello extends Bar, Foo {
~~~~~
!!! error TS2320: Interface 'Hello' cannot simultaneously extend types 'Bar' and 'Foo'.
!!! error TS2320: Named properties 'f' of types 'Bar' and 'Foo' are not identical.
}

View file

@ -0,0 +1,12 @@
//// [genericAndNonGenericInheritedSignature2.ts]
interface Foo {
f(x: any): any;
}
interface Bar {
f<T>(x: T): T;
}
interface Hello extends Bar, Foo {
}
//// [genericAndNonGenericInheritedSignature2.js]

View file

@ -0,0 +1,17 @@
//// [inferenceFromParameterlessLambda.ts]
function foo<T>(o: Take<T>, i: Make<T>) { }
interface Make<T> {
(): T;
}
interface Take<T> {
(n: T): void;
}
// Infer string from second argument because it isn't context sensitive
foo(n => n.length, () => 'hi');
//// [inferenceFromParameterlessLambda.js]
function foo(o, i) {
}
// Infer string from second argument because it isn't context sensitive
foo(function (n) { return n.length; }, function () { return 'hi'; });

View file

@ -0,0 +1,37 @@
=== tests/cases/compiler/inferenceFromParameterlessLambda.ts ===
function foo<T>(o: Take<T>, i: Make<T>) { }
>foo : <T>(o: Take<T>, i: Make<T>) => void
>T : T
>o : Take<T>
>Take : Take<T>
>T : T
>i : Make<T>
>Make : Make<T>
>T : T
interface Make<T> {
>Make : Make<T>
>T : T
(): T;
>T : T
}
interface Take<T> {
>Take : Take<T>
>T : T
(n: T): void;
>n : T
>T : T
}
// Infer string from second argument because it isn't context sensitive
foo(n => n.length, () => 'hi');
>foo(n => n.length, () => 'hi') : void
>foo : <T>(o: Take<T>, i: Make<T>) => void
>n => n.length : (n: string) => number
>n : string
>n.length : number
>n : string
>length : number
>() => 'hi' : () => string

View file

@ -1,11 +1,8 @@
tests/cases/compiler/innerModExport1.ts(5,5): error TS2304: Cannot find name 'module'.
tests/cases/compiler/innerModExport1.ts(5,12): error TS1005: ';' expected.
tests/cases/compiler/innerModExport1.ts(7,9): error TS1129: Statement expected.
tests/cases/compiler/innerModExport1.ts(14,5): error TS1148: Cannot compile external modules unless the '--module' flag is provided.
tests/cases/compiler/innerModExport1.ts(17,1): error TS1128: Declaration or statement expected.
==== tests/cases/compiler/innerModExport1.ts (5 errors) ====
==== tests/cases/compiler/innerModExport1.ts (2 errors) ====
module Outer {
// inner mod 1
@ -17,8 +14,6 @@ tests/cases/compiler/innerModExport1.ts(17,1): error TS1128: Declaration or stat
!!! error TS1005: ';' expected.
var non_export_var = 0;
export var export_var = 1;
~~~~~~
!!! error TS1129: Statement expected.
function NonExportFunc() { return 0; }
@ -26,12 +21,8 @@ tests/cases/compiler/innerModExport1.ts(17,1): error TS1128: Declaration or stat
}
export var outer_var_export = 0;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided.
export function outerFuncExport() { return 0; }
}
~
!!! error TS1128: Declaration or statement expected.
Outer.ExportFunc();

View file

@ -1,12 +1,11 @@
tests/cases/compiler/innerModExport2.ts(5,5): error TS2304: Cannot find name 'module'.
tests/cases/compiler/innerModExport2.ts(5,12): error TS1005: ';' expected.
tests/cases/compiler/innerModExport2.ts(7,9): error TS1129: Statement expected.
tests/cases/compiler/innerModExport2.ts(15,5): error TS1148: Cannot compile external modules unless the '--module' flag is provided.
tests/cases/compiler/innerModExport2.ts(18,1): error TS1128: Declaration or statement expected.
tests/cases/compiler/innerModExport2.ts(7,20): error TS2395: Individual declarations in merged declaration export_var must be all exported or all local.
tests/cases/compiler/innerModExport2.ts(13,9): error TS2395: Individual declarations in merged declaration export_var must be all exported or all local.
tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExportFunc' does not exist on type 'typeof Outer'.
==== tests/cases/compiler/innerModExport2.ts (6 errors) ====
==== tests/cases/compiler/innerModExport2.ts (5 errors) ====
module Outer {
// inner mod 1
@ -18,23 +17,21 @@ tests/cases/compiler/innerModExport2.ts(20,7): error TS2339: Property 'NonExport
!!! error TS1005: ';' expected.
var non_export_var = 0;
export var export_var = 1;
~~~~~~
!!! error TS1129: Statement expected.
~~~~~~~~~~
!!! error TS2395: Individual declarations in merged declaration export_var must be all exported or all local.
function NonExportFunc() { return 0; }
export function ExportFunc() { return 0; }
}
var export_var: number;
~~~~~~~~~~
!!! error TS2395: Individual declarations in merged declaration export_var must be all exported or all local.
export var outer_var_export = 0;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS1148: Cannot compile external modules unless the '--module' flag is provided.
export function outerFuncExport() { return 0; }
}
~
!!! error TS1128: Declaration or statement expected.
Outer.NonExportFunc();
~~~~~~~~~~~~~

View file

@ -1,27 +1,27 @@
tests/cases/compiler/letDeclarations-es5-1.ts(1,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(2,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(3,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(4,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(5,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(6,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(1,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(2,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(3,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(4,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(5,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5-1.ts(6,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/compiler/letDeclarations-es5-1.ts (6 errors) ====
let l1;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l2: number;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l3, l4, l5 :string, l6;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l7 = false;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l8: number = 23;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l9 = 0, l10 :string = "", l11 = null;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -1,40 +1,40 @@
tests/cases/compiler/letDeclarations-es5.ts(2,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(3,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(4,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(6,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(7,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(8,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(10,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(12,9): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(2,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(3,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(4,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(6,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(7,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(8,1): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(10,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
tests/cases/compiler/letDeclarations-es5.ts(12,5): error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
==== tests/cases/compiler/letDeclarations-es5.ts (8 errors) ====
let l1;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l2: number;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l3, l4, l5 :string, l6;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l7 = false;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l8: number = 23;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
let l9 = 0, l10 :string = "", l11 = null;
~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
for(let l11 in {}) { }
~~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.
for(let l12 = 0; l12 < 9; l12++) { }
~~~
~~~
!!! error TS1153: 'let' declarations are only available when targeting ECMAScript 6 and higher.

View file

@ -0,0 +1,9 @@
tests/cases/compiler/modifiersOnInterfaceIndexSignature1.ts(2,3): error TS1145: Modifiers not permitted on index signature members.
==== tests/cases/compiler/modifiersOnInterfaceIndexSignature1.ts (1 errors) ====
interface I {
public [a: string]: number;
~~~~~~
!!! error TS1145: Modifiers not permitted on index signature members.
}

View file

@ -0,0 +1,35 @@
//// [moduleSharesNameWithImportDeclarationInsideIt.ts]
module Z.M {
export function bar() {
return "";
}
}
module A.M {
import M = Z.M;
export function bar() {
}
M.bar(); // Should call Z.M.bar
}
//// [moduleSharesNameWithImportDeclarationInsideIt.js]
var Z;
(function (Z) {
var M;
(function (M) {
function bar() {
return "";
}
M.bar = bar;
})(M = Z.M || (Z.M = {}));
})(Z || (Z = {}));
var A;
(function (A) {
var M;
(function (_M) {
var M = Z.M;
function bar() {
}
_M.bar = bar;
M.bar(); // Should call Z.M.bar
})(M = A.M || (A.M = {}));
})(A || (A = {}));

View file

@ -0,0 +1,29 @@
=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt.ts ===
module Z.M {
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => string
return "";
}
}
module A.M {
>A : typeof A
>M : typeof A.M
import M = Z.M;
>M : typeof M
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => void
}
M.bar(); // Should call Z.M.bar
>M.bar() : string
>M.bar : () => string
>M : typeof M
>bar : () => string
}

View file

@ -0,0 +1,35 @@
//// [moduleSharesNameWithImportDeclarationInsideIt2.ts]
module Z.M {
export function bar() {
return "";
}
}
module A.M {
export import M = Z.M;
export function bar() {
}
M.bar(); // Should call Z.M.bar
}
//// [moduleSharesNameWithImportDeclarationInsideIt2.js]
var Z;
(function (Z) {
var M;
(function (M) {
function bar() {
return "";
}
M.bar = bar;
})(M = Z.M || (Z.M = {}));
})(Z || (Z = {}));
var A;
(function (A) {
var M;
(function (M) {
M.M = Z.M;
function bar() {
}
M.bar = bar;
M.M.bar(); // Should call Z.M.bar
})(M = A.M || (A.M = {}));
})(A || (A = {}));

View file

@ -0,0 +1,29 @@
=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt2.ts ===
module Z.M {
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => string
return "";
}
}
module A.M {
>A : typeof A
>M : typeof A.M
export import M = Z.M;
>M : typeof M
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => void
}
M.bar(); // Should call Z.M.bar
>M.bar() : string
>M.bar : () => string
>M : typeof M
>bar : () => string
}

View file

@ -0,0 +1,25 @@
tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts(10,12): error TS2300: Duplicate identifier 'M'.
tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts(11,12): error TS2300: Duplicate identifier 'M'.
==== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt3.ts (2 errors) ====
module Z {
export module M {
export function bar() {
return "";
}
}
export interface I { }
}
module A.M {
import M = Z.M;
~
!!! error TS2300: Duplicate identifier 'M'.
import M = Z.I;
~
!!! error TS2300: Duplicate identifier 'M'.
export function bar() {
}
M.bar(); // Should call Z.M.bar
}

View file

@ -0,0 +1,40 @@
//// [moduleSharesNameWithImportDeclarationInsideIt3.ts]
module Z {
export module M {
export function bar() {
return "";
}
}
export interface I { }
}
module A.M {
import M = Z.M;
import M = Z.I;
export function bar() {
}
M.bar(); // Should call Z.M.bar
}
//// [moduleSharesNameWithImportDeclarationInsideIt3.js]
var Z;
(function (Z) {
var M;
(function (M) {
function bar() {
return "";
}
M.bar = bar;
})(M = Z.M || (Z.M = {}));
})(Z || (Z = {}));
var A;
(function (A) {
var M;
(function (_M) {
var M = Z.M;
function bar() {
}
_M.bar = bar;
M.bar(); // Should call Z.M.bar
})(M = A.M || (A.M = {}));
})(A || (A = {}));

View file

@ -0,0 +1,36 @@
//// [moduleSharesNameWithImportDeclarationInsideIt4.ts]
module Z.M {
export function bar() {
return "";
}
}
module A.M {
interface M { }
import M = Z.M;
export function bar() {
}
M.bar(); // Should call Z.M.bar
}
//// [moduleSharesNameWithImportDeclarationInsideIt4.js]
var Z;
(function (Z) {
var M;
(function (M) {
function bar() {
return "";
}
M.bar = bar;
})(M = Z.M || (Z.M = {}));
})(Z || (Z = {}));
var A;
(function (A) {
var M;
(function (_M) {
var M = Z.M;
function bar() {
}
_M.bar = bar;
M.bar(); // Should call Z.M.bar
})(M = A.M || (A.M = {}));
})(A || (A = {}));

View file

@ -0,0 +1,32 @@
=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt4.ts ===
module Z.M {
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => string
return "";
}
}
module A.M {
>A : typeof A
>M : typeof A.M
interface M { }
>M : M
import M = Z.M;
>M : typeof M
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => void
}
M.bar(); // Should call Z.M.bar
>M.bar() : string
>M.bar : () => string
>M : typeof M
>bar : () => string
}

View file

@ -0,0 +1,25 @@
tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts(10,12): error TS2300: Duplicate identifier 'M'.
tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts(11,12): error TS2300: Duplicate identifier 'M'.
==== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt5.ts (2 errors) ====
module Z {
export module M {
export function bar() {
return "";
}
}
export interface I { }
}
module A.M {
import M = Z.I;
~
!!! error TS2300: Duplicate identifier 'M'.
import M = Z.M;
~
!!! error TS2300: Duplicate identifier 'M'.
export function bar() {
}
M.bar(); // Should call Z.M.bar
}

View file

@ -0,0 +1,39 @@
//// [moduleSharesNameWithImportDeclarationInsideIt5.ts]
module Z {
export module M {
export function bar() {
return "";
}
}
export interface I { }
}
module A.M {
import M = Z.I;
import M = Z.M;
export function bar() {
}
M.bar(); // Should call Z.M.bar
}
//// [moduleSharesNameWithImportDeclarationInsideIt5.js]
var Z;
(function (Z) {
var M;
(function (M) {
function bar() {
return "";
}
M.bar = bar;
})(M = Z.M || (Z.M = {}));
})(Z || (Z = {}));
var A;
(function (A) {
var M;
(function (M) {
function bar() {
}
M.bar = bar;
M.bar(); // Should call Z.M.bar
})(M = A.M || (A.M = {}));
})(A || (A = {}));

View file

@ -0,0 +1,32 @@
//// [moduleSharesNameWithImportDeclarationInsideIt6.ts]
module Z.M {
export function bar() {
return "";
}
}
module A.M {
import M = Z.M;
export function bar() {
}
}
//// [moduleSharesNameWithImportDeclarationInsideIt6.js]
var Z;
(function (Z) {
var M;
(function (M) {
function bar() {
return "";
}
M.bar = bar;
})(M = Z.M || (Z.M = {}));
})(Z || (Z = {}));
var A;
(function (A) {
var M;
(function (M) {
function bar() {
}
M.bar = bar;
})(M = A.M || (A.M = {}));
})(A || (A = {}));

View file

@ -0,0 +1,24 @@
=== tests/cases/compiler/moduleSharesNameWithImportDeclarationInsideIt6.ts ===
module Z.M {
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => string
return "";
}
}
module A.M {
>A : typeof A
>M : typeof A.M
import M = Z.M;
>M : typeof M
>Z : typeof Z
>M : typeof M
export function bar() {
>bar : () => void
}
}

View file

@ -1,2 +1,2 @@
//// [noCatchBlock.js.map]
{"version":3,"file":"noCatchBlock.js","sourceRoot":"","sources":["noCatchBlock.ts"],"names":[],"mappings":"AACA,IAAA,CAAC;AAED,CAAC;QAAC,CAAC;AAEH,CAAC"}
{"version":3,"file":"noCatchBlock.js","sourceRoot":"","sources":["noCatchBlock.ts"],"names":[],"mappings":"AACA,IAAI,CAAC;AAEL,CAAC;QAAS,CAAC;AAEX,CAAC"}

View file

@ -14,17 +14,17 @@ sourceFile:noCatchBlock.ts
3 > ^
1 >
>
2 >
3 > t
2 >try
3 > {
1 >Emitted(1, 1) Source(2, 1) + SourceIndex(0)
2 >Emitted(1, 5) Source(2, 1) + SourceIndex(0)
3 >Emitted(1, 6) Source(2, 2) + SourceIndex(0)
2 >Emitted(1, 5) Source(2, 5) + SourceIndex(0)
3 >Emitted(1, 6) Source(2, 6) + SourceIndex(0)
---
>>>}
1 >
2 >^
3 > ^^^^^^^^^->
1 >ry {
1 >
> // ...
>
2 >}
@ -34,16 +34,16 @@ sourceFile:noCatchBlock.ts
>>>finally {
1->^^^^^^^^
2 > ^
1->
2 > f
1->Emitted(3, 9) Source(4, 3) + SourceIndex(0)
2 >Emitted(3, 10) Source(4, 4) + SourceIndex(0)
1-> finally
2 > {
1->Emitted(3, 9) Source(4, 11) + SourceIndex(0)
2 >Emitted(3, 10) Source(4, 12) + SourceIndex(0)
---
>>>}
1 >
2 >^
3 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^->
1 >inally {
1 >
> // N.B. No 'catch' block
>
2 >}

View file

@ -0,0 +1,7 @@
tests/cases/compiler/objectLiteralMemberWithModifiers1.ts(1,11): error TS1184: Modifiers cannot appear here.
==== tests/cases/compiler/objectLiteralMemberWithModifiers1.ts (1 errors) ====
var v = { public foo() { } }
~~~~~~
!!! error TS1184: Modifiers cannot appear here.

View file

@ -0,0 +1,6 @@
//// [objectLiteralMemberWithModifiers1.ts]
var v = { public foo() { } }
//// [objectLiteralMemberWithModifiers1.js]
var v = { foo: function () {
} };

View file

@ -0,0 +1,10 @@
tests/cases/compiler/objectLiteralMemberWithModifiers2.ts(1,22): error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
tests/cases/compiler/objectLiteralMemberWithModifiers2.ts(1,22): error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement.
==== tests/cases/compiler/objectLiteralMemberWithModifiers2.ts (2 errors) ====
var v = { public get foo() { } }
~~~
!!! error TS1056: Accessors are only available when targeting ECMAScript 5 and higher.
~~~
!!! error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement.

View file

@ -0,0 +1,7 @@
tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts(1,14): error TS1112: A class member cannot be declared optional.
==== tests/cases/compiler/objectLiteralMemberWithQuestionMark1.ts (1 errors) ====
var v = { foo?() { } }
~
!!! error TS1112: A class member cannot be declared optional.

View file

@ -0,0 +1,7 @@
tests/cases/compiler/objectLiteralMemberWithoutBlock1.ts(1,16): error TS1005: '{' expected.
==== tests/cases/compiler/objectLiteralMemberWithoutBlock1.ts (1 errors) ====
var v = { foo(); }
~
!!! error TS1005: '{' expected.

View file

@ -2,12 +2,10 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(4,9): error TS1131: Property or signature expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(8,8): error TS1005: ';' expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(8,9): error TS1131: Property or signature expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(12,5): error TS2391: Function implementation is missing or not immediately following the declaration.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(12,8): error TS1144: '{' or ';' expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(12,9): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(16,8): error TS1005: ';' expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(16,9): error TS1131: Property or signature expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(20,5): error TS2391: Function implementation is missing or not immediately following the declaration.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(20,8): error TS1144: '{' or ';' expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(20,9): error TS1068: Unexpected token. A constructor, method, accessor, or property was expected.
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(25,8): error TS1005: '{' expected.
@ -15,7 +13,7 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith
tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts(26,1): error TS1005: ':' expected.
==== tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts (15 errors) ====
==== tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWithOptionalProperties2.ts (13 errors) ====
// Illegal attempts to define optional methods
var a: {
@ -36,8 +34,6 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith
class C {
x()?: number; // error
~
!!! error TS2391: Function implementation is missing or not immediately following the declaration.
~
!!! error TS1144: '{' or ';' expected.
~
@ -54,8 +50,6 @@ tests/cases/conformance/types/objectTypeLiteral/methodSignatures/objectTypesWith
class C2<T> {
x()?: T; // error
~
!!! error TS2391: Function implementation is missing or not immediately following the declaration.
~
!!! error TS1144: '{' or ';' expected.
~

View file

@ -1,15 +1,9 @@
tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,10): error TS1005: ':' expected.
tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,10): error TS2304: Cannot find name 'get'.
tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,14): error TS1005: ',' expected.
tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts(2,14): error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement.
==== tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts (3 errors) ====
==== tests/cases/conformance/parser/ecmascript5/Accessors/parserAccessors10.ts (1 errors) ====
var v = {
public get foo() { }
~~~
!!! error TS1005: ':' expected.
~~~
!!! error TS2304: Cannot find name 'get'.
~~~
!!! error TS1005: ',' expected.
!!! error TS2378: A 'get' accessor must return a value or consist of a single 'throw' statement.
};

View file

@ -0,0 +1,10 @@
//// [parserAccessors10.ts]
var v = {
public get foo() { }
};
//// [parserAccessors10.js]
var v = {
get foo() {
}
};

View file

@ -1,19 +1,7 @@
tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,18): error TS1005: ':' expected.
tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,18): error TS2304: Cannot find name 'get'.
tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,23): error TS2304: Cannot find name 'e'.
tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,28): error TS1005: ',' expected.
tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,32): error TS1128: Declaration or statement expected.
tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts(1,22): error TS9002: Computed property names are not currently supported.
==== tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts (5 errors) ====
==== tests/cases/conformance/parser/ecmascript6/ComputedPropertyNames/parserComputedPropertyName5.ts (1 errors) ====
var v = { public get [e]() { } };
~~~
!!! error TS1005: ':' expected.
~~~
!!! error TS2304: Cannot find name 'get'.
~
!!! error TS2304: Cannot find name 'e'.
~
!!! error TS1005: ',' expected.
~
!!! error TS1128: Declaration or statement expected.
~~~
!!! error TS9002: Computed property names are not currently supported.

Some files were not shown because too many files have changed in this diff Show more