Merge branch 'master' into asyncFunctions

This commit is contained in:
Ron Buckton
2015-07-01 09:27:45 -07:00
1228 changed files with 34838 additions and 19373 deletions
+24 -2
View File
@@ -103,7 +103,15 @@ var serverSources = [
"server.ts"
].map(function (f) {
return path.join(serverDirectory, f);
});
}).concat(servicesSources);
var languageServiceLibrarySources = [
"editorServices.ts",
"protocol.d.ts",
"session.ts"
].map(function (f) {
return path.join(serverDirectory, f);
}).concat(servicesSources);
var harnessSources = [
"harness.ts",
@@ -361,7 +369,7 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca
// Create the node definition file by replacing 'ts' module with '"typescript"' as a module.
jake.cpR(standaloneDefinitionsFile, nodeDefinitionsFile, {silent: true});
var definitionFileContents = fs.readFileSync(nodeDefinitionsFile).toString();
definitionFileContents = definitionFileContents.replace(/declare module ts/g, 'declare module "typescript"');
definitionFileContents = definitionFileContents.replace(/declare (namespace|module) ts/g, 'declare module "typescript"');
fs.writeFileSync(nodeDefinitionsFile, definitionFileContents);
});
@@ -369,6 +377,20 @@ compileFile(servicesFile, servicesSources,[builtLocalDirectory, copyright].conca
var serverFile = path.join(builtLocalDirectory, "tsserver.js");
compileFile(serverFile, serverSources,[builtLocalDirectory, copyright].concat(serverSources), /*prefixes*/ [copyright], /*useBuiltCompiler*/ true);
var lsslFile = path.join(builtLocalDirectory, "tslssl.js");
compileFile(
lsslFile,
languageServiceLibrarySources,
[builtLocalDirectory, copyright].concat(languageServiceLibrarySources),
/*prefixes*/ [copyright],
/*useBuiltCompiler*/ true,
/*noOutFile*/ false,
/*generateDeclarations*/ true);
// Local target to build the language service server library
desc("Builds language service server library");
task("lssl", [lsslFile]);
// Local target to build the compiler and services
desc("Builds the full compiler and services");
task("local", ["generate-diagnostics", "lib", tscFile, servicesFile, nodeDefinitionsFile, serverFile]);
+1 -1
View File
@@ -1165,7 +1165,7 @@ interface ArrayConstructor {
(arrayLength?: number): any[];
<T>(arrayLength: number): T[];
<T>(...items: T[]): T[];
isArray(arg: any): boolean;
isArray(arg: any): arg is Array<any>;
prototype: Array<any>;
}
+5 -1
View File
@@ -1165,7 +1165,7 @@ interface ArrayConstructor {
(arrayLength?: number): any[];
<T>(arrayLength: number): T[];
<T>(...items: T[]): T[];
isArray(arg: any): boolean;
isArray(arg: any): arg is Array<any>;
prototype: Array<any>;
}
@@ -1880,6 +1880,7 @@ interface Map<K, V> {
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
prototype: Map<any, any>;
@@ -1896,6 +1897,7 @@ interface WeakMap<K, V> {
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
prototype: WeakMap<any, any>;
@@ -1917,6 +1919,7 @@ interface Set<T> {
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
prototype: Set<any>;
@@ -1932,6 +1935,7 @@ interface WeakSet<T> {
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
prototype: WeakSet<any>;
+7 -2
View File
@@ -1165,7 +1165,7 @@ interface ArrayConstructor {
(arrayLength?: number): any[];
<T>(arrayLength: number): T[];
<T>(...items: T[]): T[];
isArray(arg: any): boolean;
isArray(arg: any): arg is Array<any>;
prototype: Array<any>;
}
@@ -3531,6 +3531,11 @@ declare module Intl {
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumintegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
@@ -3593,7 +3598,7 @@ declare module Intl {
}
interface DateTimeFormat {
format(date: number): string;
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
+6 -1
View File
@@ -2361,6 +2361,11 @@ declare module Intl {
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumintegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
@@ -2423,7 +2428,7 @@ declare module Intl {
}
interface DateTimeFormat {
format(date: number): string;
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
+21 -2
View File
@@ -1165,7 +1165,7 @@ interface ArrayConstructor {
(arrayLength?: number): any[];
<T>(arrayLength: number): T[];
<T>(...items: T[]): T[];
isArray(arg: any): boolean;
isArray(arg: any): arg is Array<any>;
prototype: Array<any>;
}
@@ -1880,6 +1880,7 @@ interface Map<K, V> {
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
prototype: Map<any, any>;
@@ -1896,6 +1897,7 @@ interface WeakMap<K, V> {
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
prototype: WeakMap<any, any>;
@@ -1917,6 +1919,7 @@ interface Set<T> {
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
prototype: Set<any>;
@@ -1932,6 +1935,7 @@ interface WeakSet<T> {
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
prototype: WeakSet<any>;
@@ -4909,6 +4913,11 @@ declare module Intl {
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumintegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
@@ -4971,7 +4980,7 @@ declare module Intl {
}
interface DateTimeFormat {
format(date: number): string;
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
@@ -18015,7 +18024,17 @@ declare function addEventListener(type: "volumechange", listener: (ev: Event) =>
declare function addEventListener(type: "waiting", listener: (ev: Event) => any, useCapture?: boolean): void;
declare function addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
declare function addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
interface DOMTokenList {
[Symbol.iterator](): IterableIterator<string>;
}
interface NodeList {
[Symbol.iterator](): IterableIterator<Node>
}
interface NodeListOf<TNode extends Node> {
[Symbol.iterator](): IterableIterator<TNode>
}
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
+6 -1
View File
@@ -2361,6 +2361,11 @@ declare module Intl {
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumintegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
@@ -2423,7 +2428,7 @@ declare module Intl {
}
interface DateTimeFormat {
format(date: number): string;
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
+3588 -2987
View File
File diff suppressed because it is too large Load Diff
+4539 -3870
View File
File diff suppressed because it is too large Load Diff
+190 -161
View File
@@ -17,6 +17,13 @@ declare module "typescript" {
interface Map<T> {
[index: string]: T;
}
interface FileMap<T> {
get(fileName: string): T;
set(fileName: string, value: T): void;
contains(fileName: string): boolean;
remove(fileName: string): void;
forEachValue(f: (v: T) => void): void;
}
interface TextRange {
pos: number;
end: number;
@@ -139,156 +146,158 @@ declare module "typescript" {
ConstructorKeyword = 114,
DeclareKeyword = 115,
GetKeyword = 116,
ModuleKeyword = 117,
NamespaceKeyword = 118,
RequireKeyword = 119,
NumberKeyword = 120,
SetKeyword = 121,
StringKeyword = 122,
SymbolKeyword = 123,
TypeKeyword = 124,
FromKeyword = 125,
OfKeyword = 126,
QualifiedName = 127,
ComputedPropertyName = 128,
TypeParameter = 129,
Parameter = 130,
Decorator = 131,
PropertySignature = 132,
PropertyDeclaration = 133,
MethodSignature = 134,
MethodDeclaration = 135,
Constructor = 136,
GetAccessor = 137,
SetAccessor = 138,
CallSignature = 139,
ConstructSignature = 140,
IndexSignature = 141,
TypeReference = 142,
FunctionType = 143,
ConstructorType = 144,
TypeQuery = 145,
TypeLiteral = 146,
ArrayType = 147,
TupleType = 148,
UnionType = 149,
ParenthesizedType = 150,
ObjectBindingPattern = 151,
ArrayBindingPattern = 152,
BindingElement = 153,
ArrayLiteralExpression = 154,
ObjectLiteralExpression = 155,
PropertyAccessExpression = 156,
ElementAccessExpression = 157,
CallExpression = 158,
NewExpression = 159,
TaggedTemplateExpression = 160,
TypeAssertionExpression = 161,
ParenthesizedExpression = 162,
FunctionExpression = 163,
ArrowFunction = 164,
DeleteExpression = 165,
TypeOfExpression = 166,
VoidExpression = 167,
PrefixUnaryExpression = 168,
PostfixUnaryExpression = 169,
BinaryExpression = 170,
ConditionalExpression = 171,
TemplateExpression = 172,
YieldExpression = 173,
SpreadElementExpression = 174,
ClassExpression = 175,
OmittedExpression = 176,
ExpressionWithTypeArguments = 177,
TemplateSpan = 178,
SemicolonClassElement = 179,
Block = 180,
VariableStatement = 181,
EmptyStatement = 182,
ExpressionStatement = 183,
IfStatement = 184,
DoStatement = 185,
WhileStatement = 186,
ForStatement = 187,
ForInStatement = 188,
ForOfStatement = 189,
ContinueStatement = 190,
BreakStatement = 191,
ReturnStatement = 192,
WithStatement = 193,
SwitchStatement = 194,
LabeledStatement = 195,
ThrowStatement = 196,
TryStatement = 197,
DebuggerStatement = 198,
VariableDeclaration = 199,
VariableDeclarationList = 200,
FunctionDeclaration = 201,
ClassDeclaration = 202,
InterfaceDeclaration = 203,
TypeAliasDeclaration = 204,
EnumDeclaration = 205,
ModuleDeclaration = 206,
ModuleBlock = 207,
CaseBlock = 208,
ImportEqualsDeclaration = 209,
ImportDeclaration = 210,
ImportClause = 211,
NamespaceImport = 212,
NamedImports = 213,
ImportSpecifier = 214,
ExportAssignment = 215,
ExportDeclaration = 216,
NamedExports = 217,
ExportSpecifier = 218,
MissingDeclaration = 219,
ExternalModuleReference = 220,
CaseClause = 221,
DefaultClause = 222,
HeritageClause = 223,
CatchClause = 224,
PropertyAssignment = 225,
ShorthandPropertyAssignment = 226,
EnumMember = 227,
SourceFile = 228,
JSDocTypeExpression = 229,
JSDocAllType = 230,
JSDocUnknownType = 231,
JSDocArrayType = 232,
JSDocUnionType = 233,
JSDocTupleType = 234,
JSDocNullableType = 235,
JSDocNonNullableType = 236,
JSDocRecordType = 237,
JSDocRecordMember = 238,
JSDocTypeReference = 239,
JSDocOptionalType = 240,
JSDocFunctionType = 241,
JSDocVariadicType = 242,
JSDocConstructorType = 243,
JSDocThisType = 244,
JSDocComment = 245,
JSDocTag = 246,
JSDocParameterTag = 247,
JSDocReturnTag = 248,
JSDocTypeTag = 249,
JSDocTemplateTag = 250,
SyntaxList = 251,
Count = 252,
IsKeyword = 117,
ModuleKeyword = 118,
NamespaceKeyword = 119,
RequireKeyword = 120,
NumberKeyword = 121,
SetKeyword = 122,
StringKeyword = 123,
SymbolKeyword = 124,
TypeKeyword = 125,
FromKeyword = 126,
OfKeyword = 127,
QualifiedName = 128,
ComputedPropertyName = 129,
TypeParameter = 130,
Parameter = 131,
Decorator = 132,
PropertySignature = 133,
PropertyDeclaration = 134,
MethodSignature = 135,
MethodDeclaration = 136,
Constructor = 137,
GetAccessor = 138,
SetAccessor = 139,
CallSignature = 140,
ConstructSignature = 141,
IndexSignature = 142,
TypePredicate = 143,
TypeReference = 144,
FunctionType = 145,
ConstructorType = 146,
TypeQuery = 147,
TypeLiteral = 148,
ArrayType = 149,
TupleType = 150,
UnionType = 151,
ParenthesizedType = 152,
ObjectBindingPattern = 153,
ArrayBindingPattern = 154,
BindingElement = 155,
ArrayLiteralExpression = 156,
ObjectLiteralExpression = 157,
PropertyAccessExpression = 158,
ElementAccessExpression = 159,
CallExpression = 160,
NewExpression = 161,
TaggedTemplateExpression = 162,
TypeAssertionExpression = 163,
ParenthesizedExpression = 164,
FunctionExpression = 165,
ArrowFunction = 166,
DeleteExpression = 167,
TypeOfExpression = 168,
VoidExpression = 169,
PrefixUnaryExpression = 170,
PostfixUnaryExpression = 171,
BinaryExpression = 172,
ConditionalExpression = 173,
TemplateExpression = 174,
YieldExpression = 175,
SpreadElementExpression = 176,
ClassExpression = 177,
OmittedExpression = 178,
ExpressionWithTypeArguments = 179,
TemplateSpan = 180,
SemicolonClassElement = 181,
Block = 182,
VariableStatement = 183,
EmptyStatement = 184,
ExpressionStatement = 185,
IfStatement = 186,
DoStatement = 187,
WhileStatement = 188,
ForStatement = 189,
ForInStatement = 190,
ForOfStatement = 191,
ContinueStatement = 192,
BreakStatement = 193,
ReturnStatement = 194,
WithStatement = 195,
SwitchStatement = 196,
LabeledStatement = 197,
ThrowStatement = 198,
TryStatement = 199,
DebuggerStatement = 200,
VariableDeclaration = 201,
VariableDeclarationList = 202,
FunctionDeclaration = 203,
ClassDeclaration = 204,
InterfaceDeclaration = 205,
TypeAliasDeclaration = 206,
EnumDeclaration = 207,
ModuleDeclaration = 208,
ModuleBlock = 209,
CaseBlock = 210,
ImportEqualsDeclaration = 211,
ImportDeclaration = 212,
ImportClause = 213,
NamespaceImport = 214,
NamedImports = 215,
ImportSpecifier = 216,
ExportAssignment = 217,
ExportDeclaration = 218,
NamedExports = 219,
ExportSpecifier = 220,
MissingDeclaration = 221,
ExternalModuleReference = 222,
CaseClause = 223,
DefaultClause = 224,
HeritageClause = 225,
CatchClause = 226,
PropertyAssignment = 227,
ShorthandPropertyAssignment = 228,
EnumMember = 229,
SourceFile = 230,
JSDocTypeExpression = 231,
JSDocAllType = 232,
JSDocUnknownType = 233,
JSDocArrayType = 234,
JSDocUnionType = 235,
JSDocTupleType = 236,
JSDocNullableType = 237,
JSDocNonNullableType = 238,
JSDocRecordType = 239,
JSDocRecordMember = 240,
JSDocTypeReference = 241,
JSDocOptionalType = 242,
JSDocFunctionType = 243,
JSDocVariadicType = 244,
JSDocConstructorType = 245,
JSDocThisType = 246,
JSDocComment = 247,
JSDocTag = 248,
JSDocParameterTag = 249,
JSDocReturnTag = 250,
JSDocTypeTag = 251,
JSDocTemplateTag = 252,
SyntaxList = 253,
Count = 254,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
LastReservedWord = 101,
FirstKeyword = 66,
LastKeyword = 126,
LastKeyword = 127,
FirstFutureReservedWord = 102,
LastFutureReservedWord = 110,
FirstTypeNode = 142,
LastTypeNode = 150,
FirstTypeNode = 144,
LastTypeNode = 152,
FirstPunctuation = 14,
LastPunctuation = 64,
FirstToken = 0,
LastToken = 126,
LastToken = 127,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
@@ -297,7 +306,7 @@ declare module "typescript" {
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 64,
FirstNode = 127,
FirstNode = 128,
}
const enum NodeFlags {
Export = 1,
@@ -458,6 +467,10 @@ declare module "typescript" {
typeName: EntityName;
typeArguments?: NodeArray<TypeNode>;
}
interface TypePredicateNode extends TypeNode {
parameterName: Identifier;
type: TypeNode;
}
interface TypeQueryNode extends TypeNode {
exprName: EntityName;
}
@@ -587,12 +600,12 @@ declare module "typescript" {
tag: LeftHandSideExpression;
template: LiteralExpression | TemplateExpression;
}
type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression;
type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
interface TypeAssertion extends UnaryExpression {
type: TypeNode;
expression: UnaryExpression;
}
interface Statement extends Node, ModuleElement {
interface Statement extends Node {
_statementBrand: any;
}
interface Block extends Statement {
@@ -672,9 +685,6 @@ declare module "typescript" {
variableDeclaration: VariableDeclaration;
block: Block;
}
interface ModuleElement extends Node {
_moduleElementBrand: any;
}
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@@ -700,6 +710,7 @@ declare module "typescript" {
}
interface TypeAliasDeclaration extends Declaration, Statement {
name: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
type: TypeNode;
}
interface EnumMember extends Declaration {
@@ -710,21 +721,21 @@ declare module "typescript" {
name: Identifier;
members: NodeArray<EnumMember>;
}
interface ModuleDeclaration extends Declaration, ModuleElement {
interface ModuleDeclaration extends Declaration, Statement {
name: Identifier | LiteralExpression;
body: ModuleBlock | ModuleDeclaration;
}
interface ModuleBlock extends Node, ModuleElement {
statements: NodeArray<ModuleElement>;
interface ModuleBlock extends Node, Statement {
statements: NodeArray<Statement>;
}
interface ImportEqualsDeclaration extends Declaration, ModuleElement {
interface ImportEqualsDeclaration extends Declaration, Statement {
name: Identifier;
moduleReference: EntityName | ExternalModuleReference;
}
interface ExternalModuleReference extends Node {
expression?: Expression;
}
interface ImportDeclaration extends ModuleElement {
interface ImportDeclaration extends Statement {
importClause?: ImportClause;
moduleSpecifier: Expression;
}
@@ -735,7 +746,7 @@ declare module "typescript" {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface ExportDeclaration extends Declaration, ModuleElement {
interface ExportDeclaration extends Declaration, Statement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
}
@@ -750,7 +761,7 @@ declare module "typescript" {
}
type ImportSpecifier = ImportOrExportSpecifier;
type ExportSpecifier = ImportOrExportSpecifier;
interface ExportAssignment extends Declaration, ModuleElement {
interface ExportAssignment extends Declaration, Statement {
isExportEquals?: boolean;
expression: Expression;
}
@@ -838,7 +849,7 @@ declare module "typescript" {
isBracketed: boolean;
}
interface SourceFile extends Declaration {
statements: NodeArray<ModuleElement>;
statements: NodeArray<Statement>;
endOfFileToken: Node;
fileName: string;
text: string;
@@ -846,8 +857,16 @@ declare module "typescript" {
path: string;
name: string;
}[];
amdModuleName: string;
moduleName: string;
referencedFiles: FileReference[];
/**
* lib.d.ts should have a reference comment like
*
* /// <reference no-default-lib="true"/>
*
* If any other file has this comment, it signals not to include lib.d.ts
* because this containing file is intended to act as a default library.
*/
hasNoDefaultLib: boolean;
languageVersion: ScriptTarget;
}
@@ -878,8 +897,9 @@ declare module "typescript" {
* will be invoked when writing the JavaScript and declaration files.
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getOptionsDiagnostics(): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
/**
@@ -998,6 +1018,11 @@ declare module "typescript" {
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
}
interface TypePredicate {
parameterName: string;
parameterIndex: number;
type: Type;
}
const enum SymbolFlags {
None = 0,
FunctionScopedVariable = 1,
@@ -1060,6 +1085,7 @@ declare module "typescript" {
ExportHasLocal = 944,
HasExports = 1952,
HasMembers = 6240,
BlockScoped = 418,
PropertyOrAccessor = 98308,
Export = 7340032,
}
@@ -1111,9 +1137,8 @@ declare module "typescript" {
typeParameters: TypeParameter[];
outerTypeParameters: TypeParameter[];
localTypeParameters: TypeParameter[];
}
interface InterfaceTypeWithBaseTypes extends InterfaceType {
baseTypes: ObjectType[];
resolvedBaseConstructorType?: Type;
resolvedBaseTypes: ObjectType[];
}
interface InterfaceTypeWithDeclaredMembers extends InterfaceType {
declaredProperties: Symbol[];
@@ -1146,6 +1171,7 @@ declare module "typescript" {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
typePredicate?: TypePredicate;
}
const enum IndexKind {
String = 0,
@@ -1323,6 +1349,7 @@ declare module "typescript" {
function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter;
function isWhiteSpace(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function couldStartTrivia(text: string, pos: number): boolean;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[];
function getTrailingCommentRanges(text: string, pos: number): CommentRange[];
function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean;
@@ -1338,6 +1365,7 @@ declare module "typescript" {
function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan;
function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean;
function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean;
function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean;
function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan;
function createTextSpan(start: number, length: number): TextSpan;
@@ -1490,6 +1518,7 @@ declare module "typescript" {
log?(s: string): void;
trace?(s: string): void;
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -1948,11 +1977,11 @@ declare module "typescript" {
isCancellationRequested(): boolean;
throwIfCancellationRequested(): void;
}
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string;
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createDocumentRegistry(): DocumentRegistry;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry;
function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
function createClassifier(): Classifier;
+5190 -4323
View File
File diff suppressed because it is too large Load Diff
+198 -169
View File
@@ -13,10 +13,17 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
declare module ts {
declare namespace ts {
interface Map<T> {
[index: string]: T;
}
interface FileMap<T> {
get(fileName: string): T;
set(fileName: string, value: T): void;
contains(fileName: string): boolean;
remove(fileName: string): void;
forEachValue(f: (v: T) => void): void;
}
interface TextRange {
pos: number;
end: number;
@@ -139,156 +146,158 @@ declare module ts {
ConstructorKeyword = 114,
DeclareKeyword = 115,
GetKeyword = 116,
ModuleKeyword = 117,
NamespaceKeyword = 118,
RequireKeyword = 119,
NumberKeyword = 120,
SetKeyword = 121,
StringKeyword = 122,
SymbolKeyword = 123,
TypeKeyword = 124,
FromKeyword = 125,
OfKeyword = 126,
QualifiedName = 127,
ComputedPropertyName = 128,
TypeParameter = 129,
Parameter = 130,
Decorator = 131,
PropertySignature = 132,
PropertyDeclaration = 133,
MethodSignature = 134,
MethodDeclaration = 135,
Constructor = 136,
GetAccessor = 137,
SetAccessor = 138,
CallSignature = 139,
ConstructSignature = 140,
IndexSignature = 141,
TypeReference = 142,
FunctionType = 143,
ConstructorType = 144,
TypeQuery = 145,
TypeLiteral = 146,
ArrayType = 147,
TupleType = 148,
UnionType = 149,
ParenthesizedType = 150,
ObjectBindingPattern = 151,
ArrayBindingPattern = 152,
BindingElement = 153,
ArrayLiteralExpression = 154,
ObjectLiteralExpression = 155,
PropertyAccessExpression = 156,
ElementAccessExpression = 157,
CallExpression = 158,
NewExpression = 159,
TaggedTemplateExpression = 160,
TypeAssertionExpression = 161,
ParenthesizedExpression = 162,
FunctionExpression = 163,
ArrowFunction = 164,
DeleteExpression = 165,
TypeOfExpression = 166,
VoidExpression = 167,
PrefixUnaryExpression = 168,
PostfixUnaryExpression = 169,
BinaryExpression = 170,
ConditionalExpression = 171,
TemplateExpression = 172,
YieldExpression = 173,
SpreadElementExpression = 174,
ClassExpression = 175,
OmittedExpression = 176,
ExpressionWithTypeArguments = 177,
TemplateSpan = 178,
SemicolonClassElement = 179,
Block = 180,
VariableStatement = 181,
EmptyStatement = 182,
ExpressionStatement = 183,
IfStatement = 184,
DoStatement = 185,
WhileStatement = 186,
ForStatement = 187,
ForInStatement = 188,
ForOfStatement = 189,
ContinueStatement = 190,
BreakStatement = 191,
ReturnStatement = 192,
WithStatement = 193,
SwitchStatement = 194,
LabeledStatement = 195,
ThrowStatement = 196,
TryStatement = 197,
DebuggerStatement = 198,
VariableDeclaration = 199,
VariableDeclarationList = 200,
FunctionDeclaration = 201,
ClassDeclaration = 202,
InterfaceDeclaration = 203,
TypeAliasDeclaration = 204,
EnumDeclaration = 205,
ModuleDeclaration = 206,
ModuleBlock = 207,
CaseBlock = 208,
ImportEqualsDeclaration = 209,
ImportDeclaration = 210,
ImportClause = 211,
NamespaceImport = 212,
NamedImports = 213,
ImportSpecifier = 214,
ExportAssignment = 215,
ExportDeclaration = 216,
NamedExports = 217,
ExportSpecifier = 218,
MissingDeclaration = 219,
ExternalModuleReference = 220,
CaseClause = 221,
DefaultClause = 222,
HeritageClause = 223,
CatchClause = 224,
PropertyAssignment = 225,
ShorthandPropertyAssignment = 226,
EnumMember = 227,
SourceFile = 228,
JSDocTypeExpression = 229,
JSDocAllType = 230,
JSDocUnknownType = 231,
JSDocArrayType = 232,
JSDocUnionType = 233,
JSDocTupleType = 234,
JSDocNullableType = 235,
JSDocNonNullableType = 236,
JSDocRecordType = 237,
JSDocRecordMember = 238,
JSDocTypeReference = 239,
JSDocOptionalType = 240,
JSDocFunctionType = 241,
JSDocVariadicType = 242,
JSDocConstructorType = 243,
JSDocThisType = 244,
JSDocComment = 245,
JSDocTag = 246,
JSDocParameterTag = 247,
JSDocReturnTag = 248,
JSDocTypeTag = 249,
JSDocTemplateTag = 250,
SyntaxList = 251,
Count = 252,
IsKeyword = 117,
ModuleKeyword = 118,
NamespaceKeyword = 119,
RequireKeyword = 120,
NumberKeyword = 121,
SetKeyword = 122,
StringKeyword = 123,
SymbolKeyword = 124,
TypeKeyword = 125,
FromKeyword = 126,
OfKeyword = 127,
QualifiedName = 128,
ComputedPropertyName = 129,
TypeParameter = 130,
Parameter = 131,
Decorator = 132,
PropertySignature = 133,
PropertyDeclaration = 134,
MethodSignature = 135,
MethodDeclaration = 136,
Constructor = 137,
GetAccessor = 138,
SetAccessor = 139,
CallSignature = 140,
ConstructSignature = 141,
IndexSignature = 142,
TypePredicate = 143,
TypeReference = 144,
FunctionType = 145,
ConstructorType = 146,
TypeQuery = 147,
TypeLiteral = 148,
ArrayType = 149,
TupleType = 150,
UnionType = 151,
ParenthesizedType = 152,
ObjectBindingPattern = 153,
ArrayBindingPattern = 154,
BindingElement = 155,
ArrayLiteralExpression = 156,
ObjectLiteralExpression = 157,
PropertyAccessExpression = 158,
ElementAccessExpression = 159,
CallExpression = 160,
NewExpression = 161,
TaggedTemplateExpression = 162,
TypeAssertionExpression = 163,
ParenthesizedExpression = 164,
FunctionExpression = 165,
ArrowFunction = 166,
DeleteExpression = 167,
TypeOfExpression = 168,
VoidExpression = 169,
PrefixUnaryExpression = 170,
PostfixUnaryExpression = 171,
BinaryExpression = 172,
ConditionalExpression = 173,
TemplateExpression = 174,
YieldExpression = 175,
SpreadElementExpression = 176,
ClassExpression = 177,
OmittedExpression = 178,
ExpressionWithTypeArguments = 179,
TemplateSpan = 180,
SemicolonClassElement = 181,
Block = 182,
VariableStatement = 183,
EmptyStatement = 184,
ExpressionStatement = 185,
IfStatement = 186,
DoStatement = 187,
WhileStatement = 188,
ForStatement = 189,
ForInStatement = 190,
ForOfStatement = 191,
ContinueStatement = 192,
BreakStatement = 193,
ReturnStatement = 194,
WithStatement = 195,
SwitchStatement = 196,
LabeledStatement = 197,
ThrowStatement = 198,
TryStatement = 199,
DebuggerStatement = 200,
VariableDeclaration = 201,
VariableDeclarationList = 202,
FunctionDeclaration = 203,
ClassDeclaration = 204,
InterfaceDeclaration = 205,
TypeAliasDeclaration = 206,
EnumDeclaration = 207,
ModuleDeclaration = 208,
ModuleBlock = 209,
CaseBlock = 210,
ImportEqualsDeclaration = 211,
ImportDeclaration = 212,
ImportClause = 213,
NamespaceImport = 214,
NamedImports = 215,
ImportSpecifier = 216,
ExportAssignment = 217,
ExportDeclaration = 218,
NamedExports = 219,
ExportSpecifier = 220,
MissingDeclaration = 221,
ExternalModuleReference = 222,
CaseClause = 223,
DefaultClause = 224,
HeritageClause = 225,
CatchClause = 226,
PropertyAssignment = 227,
ShorthandPropertyAssignment = 228,
EnumMember = 229,
SourceFile = 230,
JSDocTypeExpression = 231,
JSDocAllType = 232,
JSDocUnknownType = 233,
JSDocArrayType = 234,
JSDocUnionType = 235,
JSDocTupleType = 236,
JSDocNullableType = 237,
JSDocNonNullableType = 238,
JSDocRecordType = 239,
JSDocRecordMember = 240,
JSDocTypeReference = 241,
JSDocOptionalType = 242,
JSDocFunctionType = 243,
JSDocVariadicType = 244,
JSDocConstructorType = 245,
JSDocThisType = 246,
JSDocComment = 247,
JSDocTag = 248,
JSDocParameterTag = 249,
JSDocReturnTag = 250,
JSDocTypeTag = 251,
JSDocTemplateTag = 252,
SyntaxList = 253,
Count = 254,
FirstAssignment = 53,
LastAssignment = 64,
FirstReservedWord = 66,
LastReservedWord = 101,
FirstKeyword = 66,
LastKeyword = 126,
LastKeyword = 127,
FirstFutureReservedWord = 102,
LastFutureReservedWord = 110,
FirstTypeNode = 142,
LastTypeNode = 150,
FirstTypeNode = 144,
LastTypeNode = 152,
FirstPunctuation = 14,
LastPunctuation = 64,
FirstToken = 0,
LastToken = 126,
LastToken = 127,
FirstTriviaToken = 2,
LastTriviaToken = 6,
FirstLiteralToken = 7,
@@ -297,7 +306,7 @@ declare module ts {
LastTemplateToken = 13,
FirstBinaryOperator = 24,
LastBinaryOperator = 64,
FirstNode = 127,
FirstNode = 128,
}
const enum NodeFlags {
Export = 1,
@@ -458,6 +467,10 @@ declare module ts {
typeName: EntityName;
typeArguments?: NodeArray<TypeNode>;
}
interface TypePredicateNode extends TypeNode {
parameterName: Identifier;
type: TypeNode;
}
interface TypeQueryNode extends TypeNode {
exprName: EntityName;
}
@@ -587,12 +600,12 @@ declare module ts {
tag: LeftHandSideExpression;
template: LiteralExpression | TemplateExpression;
}
type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression;
type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
interface TypeAssertion extends UnaryExpression {
type: TypeNode;
expression: UnaryExpression;
}
interface Statement extends Node, ModuleElement {
interface Statement extends Node {
_statementBrand: any;
}
interface Block extends Statement {
@@ -672,9 +685,6 @@ declare module ts {
variableDeclaration: VariableDeclaration;
block: Block;
}
interface ModuleElement extends Node {
_moduleElementBrand: any;
}
interface ClassLikeDeclaration extends Declaration {
name?: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
@@ -700,6 +710,7 @@ declare module ts {
}
interface TypeAliasDeclaration extends Declaration, Statement {
name: Identifier;
typeParameters?: NodeArray<TypeParameterDeclaration>;
type: TypeNode;
}
interface EnumMember extends Declaration {
@@ -710,21 +721,21 @@ declare module ts {
name: Identifier;
members: NodeArray<EnumMember>;
}
interface ModuleDeclaration extends Declaration, ModuleElement {
interface ModuleDeclaration extends Declaration, Statement {
name: Identifier | LiteralExpression;
body: ModuleBlock | ModuleDeclaration;
}
interface ModuleBlock extends Node, ModuleElement {
statements: NodeArray<ModuleElement>;
interface ModuleBlock extends Node, Statement {
statements: NodeArray<Statement>;
}
interface ImportEqualsDeclaration extends Declaration, ModuleElement {
interface ImportEqualsDeclaration extends Declaration, Statement {
name: Identifier;
moduleReference: EntityName | ExternalModuleReference;
}
interface ExternalModuleReference extends Node {
expression?: Expression;
}
interface ImportDeclaration extends ModuleElement {
interface ImportDeclaration extends Statement {
importClause?: ImportClause;
moduleSpecifier: Expression;
}
@@ -735,7 +746,7 @@ declare module ts {
interface NamespaceImport extends Declaration {
name: Identifier;
}
interface ExportDeclaration extends Declaration, ModuleElement {
interface ExportDeclaration extends Declaration, Statement {
exportClause?: NamedExports;
moduleSpecifier?: Expression;
}
@@ -750,7 +761,7 @@ declare module ts {
}
type ImportSpecifier = ImportOrExportSpecifier;
type ExportSpecifier = ImportOrExportSpecifier;
interface ExportAssignment extends Declaration, ModuleElement {
interface ExportAssignment extends Declaration, Statement {
isExportEquals?: boolean;
expression: Expression;
}
@@ -838,7 +849,7 @@ declare module ts {
isBracketed: boolean;
}
interface SourceFile extends Declaration {
statements: NodeArray<ModuleElement>;
statements: NodeArray<Statement>;
endOfFileToken: Node;
fileName: string;
text: string;
@@ -846,8 +857,16 @@ declare module ts {
path: string;
name: string;
}[];
amdModuleName: string;
moduleName: string;
referencedFiles: FileReference[];
/**
* lib.d.ts should have a reference comment like
*
* /// <reference no-default-lib="true"/>
*
* If any other file has this comment, it signals not to include lib.d.ts
* because this containing file is intended to act as a default library.
*/
hasNoDefaultLib: boolean;
languageVersion: ScriptTarget;
}
@@ -878,8 +897,9 @@ declare module ts {
* will be invoked when writing the JavaScript and declaration files.
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getOptionsDiagnostics(): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
/**
@@ -998,6 +1018,11 @@ declare module ts {
WriteTypeParametersOrArguments = 1,
UseOnlyExternalAliasing = 2,
}
interface TypePredicate {
parameterName: string;
parameterIndex: number;
type: Type;
}
const enum SymbolFlags {
None = 0,
FunctionScopedVariable = 1,
@@ -1060,6 +1085,7 @@ declare module ts {
ExportHasLocal = 944,
HasExports = 1952,
HasMembers = 6240,
BlockScoped = 418,
PropertyOrAccessor = 98308,
Export = 7340032,
}
@@ -1111,9 +1137,8 @@ declare module ts {
typeParameters: TypeParameter[];
outerTypeParameters: TypeParameter[];
localTypeParameters: TypeParameter[];
}
interface InterfaceTypeWithBaseTypes extends InterfaceType {
baseTypes: ObjectType[];
resolvedBaseConstructorType?: Type;
resolvedBaseTypes: ObjectType[];
}
interface InterfaceTypeWithDeclaredMembers extends InterfaceType {
declaredProperties: Symbol[];
@@ -1146,6 +1171,7 @@ declare module ts {
declaration: SignatureDeclaration;
typeParameters: TypeParameter[];
parameters: Symbol[];
typePredicate?: TypePredicate;
}
const enum IndexKind {
String = 0,
@@ -1267,7 +1293,7 @@ declare module ts {
newLength: number;
}
}
declare module ts {
declare namespace ts {
interface System {
args: string[];
newLine: string;
@@ -1291,7 +1317,7 @@ declare module ts {
}
var sys: System;
}
declare module ts {
declare namespace ts {
interface ErrorCallback {
(message: DiagnosticMessage, length: number): void;
}
@@ -1323,12 +1349,13 @@ declare module ts {
function getLineAndCharacterOfPosition(sourceFile: SourceFile, position: number): LineAndCharacter;
function isWhiteSpace(ch: number): boolean;
function isLineBreak(ch: number): boolean;
function couldStartTrivia(text: string, pos: number): boolean;
function getLeadingCommentRanges(text: string, pos: number): CommentRange[];
function getTrailingCommentRanges(text: string, pos: number): CommentRange[];
function isIdentifierStart(ch: number, languageVersion: ScriptTarget): boolean;
function isIdentifierPart(ch: number, languageVersion: ScriptTarget): boolean;
}
declare module ts {
declare namespace ts {
function getDefaultLibFileName(options: CompilerOptions): string;
function textSpanEnd(span: TextSpan): number;
function textSpanIsEmpty(span: TextSpan): boolean;
@@ -1338,6 +1365,7 @@ declare module ts {
function textSpanOverlap(span1: TextSpan, span2: TextSpan): TextSpan;
function textSpanIntersectsWithTextSpan(span: TextSpan, other: TextSpan): boolean;
function textSpanIntersectsWith(span: TextSpan, start: number, length: number): boolean;
function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number): boolean;
function textSpanIntersectsWithPosition(span: TextSpan, position: number): boolean;
function textSpanIntersection(span1: TextSpan, span2: TextSpan): TextSpan;
function createTextSpan(start: number, length: number): TextSpan;
@@ -1357,14 +1385,14 @@ declare module ts {
function collapseTextChangeRangesAcrossMultipleVersions(changes: TextChangeRange[]): TextChangeRange;
function getTypeParameterOwner(d: Declaration): Declaration;
}
declare module ts {
declare namespace ts {
function getNodeConstructor(kind: SyntaxKind): new () => Node;
function createNode(kind: SyntaxKind): Node;
function forEachChild<T>(node: Node, cbNode: (node: Node) => T, cbNodeArray?: (nodes: Node[]) => T): T;
function createSourceFile(fileName: string, sourceText: string, languageVersion: ScriptTarget, setParentNodes?: boolean): SourceFile;
function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
}
declare module ts {
declare namespace ts {
/** The version of the TypeScript compiler release */
const version: string;
function findConfigFile(searchPath: string): string;
@@ -1373,7 +1401,7 @@ declare module ts {
function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string;
function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost): Program;
}
declare module ts {
declare namespace ts {
function parseCommandLine(commandLine: string[]): ParsedCommandLine;
/**
* Read tsconfig.json file
@@ -1400,7 +1428,7 @@ declare module ts {
*/
function parseConfigFile(json: any, host: ParseConfigHost, basePath: string): ParsedCommandLine;
}
declare module ts {
declare namespace ts {
/** The version of the language service API */
let servicesVersion: string;
interface Node {
@@ -1490,6 +1518,7 @@ declare module ts {
log?(s: string): void;
trace?(s: string): void;
error?(s: string): void;
useCaseSensitiveFileNames?(): boolean;
}
interface LanguageService {
cleanupSemanticCache(): void;
@@ -1948,11 +1977,11 @@ declare module ts {
isCancellationRequested(): boolean;
throwIfCancellationRequested(): void;
}
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[]): string;
function transpile(input: string, compilerOptions?: CompilerOptions, fileName?: string, diagnostics?: Diagnostic[], moduleName?: string): string;
function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean): SourceFile;
let disableIncrementalParsing: boolean;
function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile;
function createDocumentRegistry(): DocumentRegistry;
function createDocumentRegistry(useCaseSensitiveFileNames?: boolean): DocumentRegistry;
function preProcessFile(sourceText: string, readImportFiles?: boolean): PreProcessedFileInfo;
function createLanguageService(host: LanguageServiceHost, documentRegistry?: DocumentRegistry): LanguageService;
function createClassifier(): Classifier;
+5190 -4323
View File
File diff suppressed because it is too large Load Diff
+87
View File
@@ -0,0 +1,87 @@
declare var require: any;
let fs = require('fs');
let async = require('async');
let glob = require('glob');
fs.readFile('src/compiler/diagnosticMessages.json', 'utf-8', (err, data) => {
if (err) {
throw err;
}
let messages = JSON.parse(data);
let keys = Object.keys(messages);
console.log('Loaded ' + keys.length + ' errors');
for (let k of keys) {
messages[k]['seen'] = false;
}
let errRegex = /\(\d+,\d+\): error TS([^:]+):/g;
let baseDir = 'tests/baselines/reference/';
fs.readdir(baseDir, (err, files) => {
files = files.filter(f => f.indexOf('.errors.txt') > 0);
let tasks: Array<(callback: () => void) => void> = [];
files.forEach(f => tasks.push(done => {
fs.readFile(baseDir + f, 'utf-8', (err, baseline) => {
if (err) throw err;
let g: string[];
while (g = errRegex.exec(baseline)) {
var errCode = +g[1];
let msg = keys.filter(k => messages[k].code === errCode)[0];
messages[msg]['seen'] = true;
}
done();
});
}));
async.parallelLimit(tasks, 25, done => {
console.log('== List of errors not present in baselines ==');
let count = 0;
for (let k of keys) {
if (messages[k]['seen'] !== true) {
console.log(k);
count++;
}
}
console.log(count + ' of ' + keys.length + ' errors are not in baselines');
});
});
});
fs.readFile('src/compiler/diagnosticInformationMap.generated.ts', 'utf-8', (err, data) => {
let errorRegexp = /\s(\w+): \{ code/g;
let errorNames: string[] = [];
let errMatch: string[];
while (errMatch = errorRegexp.exec(data)) {
errorNames.push(errMatch[1]);
}
let allSrc: string = '';
glob('./src/**/*.ts', {}, (err, files) => {
console.log('Reading ' + files.length + ' source files');
for(let file of files) {
if (file.indexOf('diagnosticInformationMap.generated.ts') > 0) {
continue;
}
let src = fs.readFileSync(file, 'utf-8');
allSrc = allSrc + src;
}
console.log('Consumed ' + allSrc.length + ' characters of source');
let count = 0;
console.log('== List of errors not used in source ==')
for(let errName of errorNames) {
if (allSrc.indexOf(errName) < 0) {
console.log(errName);
count++;
}
}
console.log(count + ' of ' + errorNames.length + ' errors are not used in source');
});
});
+3 -3
View File
@@ -630,7 +630,7 @@ namespace ts {
function getStrictModeIdentifierMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getAncestor(node, SyntaxKind.ClassDeclaration) || getAncestor(node, SyntaxKind.ClassExpression)) {
if (getContainingClass(node)) {
return Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
}
@@ -688,7 +688,7 @@ namespace ts {
function getStrictModeEvalOrArgumentsMessage(node: Node) {
// Provide specialized messages to help the user understand why we think they're in
// strict mode.
if (getAncestor(node, SyntaxKind.ClassDeclaration) || getAncestor(node, SyntaxKind.ClassExpression)) {
if (getContainingClass(node)) {
return Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
}
@@ -1031,7 +1031,7 @@ namespace ts {
// containing class.
if (node.flags & NodeFlags.AccessibilityModifier &&
node.parent.kind === SyntaxKind.Constructor &&
(node.parent.parent.kind === SyntaxKind.ClassDeclaration || node.parent.parent.kind === SyntaxKind.ClassExpression)) {
isClassLike(node.parent.parent)) {
let classDeclaration = <ClassLikeDeclaration>node.parent.parent;
declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, SymbolFlags.Property, SymbolFlags.PropertyExcludes);
+1360 -326
View File
File diff suppressed because it is too large Load Diff
+28 -6
View File
@@ -38,6 +38,16 @@ namespace ts {
name: "inlineSources",
type: "boolean",
},
{
name: "jsx",
type: {
"preserve": JsxEmit.Preserve,
"react": JsxEmit.React
},
paramType: Diagnostics.KIND,
description: Diagnostics.Specify_JSX_code_generation_Colon_preserve_or_react,
error: Diagnostics.Argument_for_jsx_must_be_preserve_or_react
},
{
name: "listFiles",
type: "boolean",
@@ -110,6 +120,7 @@ namespace ts {
{
name: "out",
type: "string",
isFilePath: true,
description: Diagnostics.Concatenate_and_emit_output_to_single_file,
paramType: Diagnostics.FILE,
},
@@ -405,18 +416,29 @@ namespace ts {
}
function getFileNames(): string[] {
var fileNames: string[] = [];
let fileNames: string[] = [];
if (hasProperty(json, "files")) {
if (json["files"] instanceof Array) {
fileNames = map(<string[]>json["files"], s => combinePaths(basePath, s));
}
}
else {
var exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
var sysFiles = host.readDirectory(basePath, ".ts", exclude);
for (var i = 0; i < sysFiles.length; i++) {
var name = sysFiles[i];
if (!fileExtensionIs(name, ".d.ts") || !contains(sysFiles, name.substr(0, name.length - 5) + ".ts")) {
let exclude = json["exclude"] instanceof Array ? map(<string[]>json["exclude"], normalizeSlashes) : undefined;
let sysFiles = host.readDirectory(basePath, ".ts", exclude).concat(host.readDirectory(basePath, ".tsx", exclude));
for (let i = 0; i < sysFiles.length; i++) {
let name = sysFiles[i];
if (fileExtensionIs(name, ".d.ts")) {
let baseName = name.substr(0, name.length - ".d.ts".length);
if (!contains(sysFiles, baseName + ".tsx") && !contains(sysFiles, baseName + ".ts")) {
fileNames.push(name);
}
}
else if (fileExtensionIs(name, ".ts")) {
if (!contains(sysFiles, name + "x")) {
fileNames.push(name)
}
}
else {
fileNames.push(name);
}
}
+3 -3
View File
@@ -572,7 +572,7 @@ namespace ts {
export function getNormalizedPathComponents(path: string, currentDirectory: string) {
path = normalizeSlashes(path);
let rootLength = getRootLength(path);
if (rootLength == 0) {
if (rootLength === 0) {
// If the path is not rooted it is relative to current directory
path = combinePaths(normalizeSlashes(currentDirectory), path);
rootLength = getRootLength(path);
@@ -702,9 +702,9 @@ namespace ts {
/**
* List of supported extensions in order of file resolution precedence.
*/
export const supportedExtensions = [".ts", ".d.ts"];
export const supportedExtensions = [".tsx", ".ts", ".d.ts"];
const extensionsToRemove = [".d.ts", ".ts", ".js"];
const extensionsToRemove = [".d.ts", ".ts", ".js", ".tsx", ".jsx"];
export function removeFileExtension(path: string): string {
for (let ext of extensionsToRemove) {
if (fileExtensionIs(path, ext)) {
+6 -2
View File
@@ -40,7 +40,6 @@ namespace ts {
function emitDeclarations(host: EmitHost, resolver: EmitResolver, diagnostics: Diagnostic[], jsFilePath: string, root?: SourceFile): DeclarationEmit {
let newLine = host.getNewLine();
let compilerOptions = host.getCompilerOptions();
let languageVersion = compilerOptions.target || ScriptTarget.ES3;
let write: (s: string) => void;
let writeLine: () => void;
@@ -709,7 +708,12 @@ namespace ts {
function writeModuleDeclaration(node: ModuleDeclaration) {
emitJsDocComments(node);
emitModuleElementDeclarationFlags(node);
write("module ");
if (node.flags & NodeFlags.Namespace) {
write("namespace ");
}
else {
write("module ");
}
writeTextOfNode(currentSourceFile, node.name);
while (node.body.kind !== SyntaxKind.ModuleBlock) {
node = <ModuleDeclaration>node.body;
@@ -20,15 +20,10 @@ namespace ts {
An_index_signature_must_have_a_type_annotation: { code: 1021, category: DiagnosticCategory.Error, key: "An index signature must have a type annotation." },
An_index_signature_parameter_must_have_a_type_annotation: { code: 1022, category: DiagnosticCategory.Error, key: "An index signature parameter must have a type annotation." },
An_index_signature_parameter_type_must_be_string_or_number: { code: 1023, category: DiagnosticCategory.Error, key: "An index signature parameter type must be 'string' or 'number'." },
A_class_or_interface_declaration_can_only_have_one_extends_clause: { code: 1024, category: DiagnosticCategory.Error, key: "A class or interface declaration can only have one 'extends' clause." },
An_extends_clause_must_precede_an_implements_clause: { code: 1025, category: DiagnosticCategory.Error, key: "An 'extends' clause must precede an 'implements' clause." },
A_class_can_only_extend_a_single_class: { code: 1026, category: DiagnosticCategory.Error, key: "A class can only extend a single class." },
A_class_declaration_can_only_have_one_implements_clause: { code: 1027, category: DiagnosticCategory.Error, key: "A class declaration can only have one 'implements' clause." },
Accessibility_modifier_already_seen: { code: 1028, category: DiagnosticCategory.Error, key: "Accessibility modifier already seen." },
_0_modifier_must_precede_1_modifier: { code: 1029, category: DiagnosticCategory.Error, key: "'{0}' modifier must precede '{1}' modifier." },
_0_modifier_already_seen: { code: 1030, category: DiagnosticCategory.Error, key: "'{0}' modifier already seen." },
_0_modifier_cannot_appear_on_a_class_element: { code: 1031, category: DiagnosticCategory.Error, key: "'{0}' modifier cannot appear on a class element." },
An_interface_declaration_cannot_have_an_implements_clause: { code: 1032, category: DiagnosticCategory.Error, key: "An interface declaration cannot have an 'implements' clause." },
super_must_be_followed_by_an_argument_list_or_member_access: { code: 1034, category: DiagnosticCategory.Error, key: "'super' must be followed by an argument list or member access." },
Only_ambient_modules_can_use_quoted_names: { code: 1035, category: DiagnosticCategory.Error, key: "Only ambient modules can use quoted names." },
Statements_are_not_allowed_in_ambient_contexts: { code: 1036, category: DiagnosticCategory.Error, key: "Statements are not allowed in ambient contexts." },
@@ -104,7 +99,6 @@ namespace ts {
case_or_default_expected: { code: 1130, category: DiagnosticCategory.Error, key: "'case' or 'default' expected." },
Property_or_signature_expected: { code: 1131, category: DiagnosticCategory.Error, key: "Property or signature expected." },
Enum_member_expected: { code: 1132, category: DiagnosticCategory.Error, key: "Enum member expected." },
Type_reference_expected: { code: 1133, category: DiagnosticCategory.Error, key: "Type reference expected." },
Variable_declaration_expected: { code: 1134, category: DiagnosticCategory.Error, key: "Variable declaration expected." },
Argument_expression_expected: { code: 1135, category: DiagnosticCategory.Error, key: "Argument expression expected." },
Property_assignment_expected: { code: 1136, category: DiagnosticCategory.Error, key: "Property assignment expected." },
@@ -121,9 +115,6 @@ namespace ts {
Cannot_compile_modules_unless_the_module_flag_is_provided: { code: 1148, category: DiagnosticCategory.Error, key: "Cannot compile modules unless the '--module' flag is provided." },
File_name_0_differs_from_already_included_file_name_1_only_in_casing: { code: 1149, category: DiagnosticCategory.Error, key: "File name '{0}' differs from already included file name '{1}' only in casing" },
new_T_cannot_be_used_to_create_an_array_Use_new_Array_T_instead: { code: 1150, category: DiagnosticCategory.Error, key: "'new T[]' cannot be used to create an array. Use 'new Array<T>()' instead." },
var_let_or_const_expected: { code: 1152, category: DiagnosticCategory.Error, key: "'var', 'let' or 'const' expected." },
let_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1153, category: DiagnosticCategory.Error, key: "'let' declarations are only available when targeting ECMAScript 6 and higher." },
const_declarations_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1154, category: DiagnosticCategory.Error, key: "'const' declarations are only available when targeting ECMAScript 6 and higher." },
const_declarations_must_be_initialized: { code: 1155, category: DiagnosticCategory.Error, key: "'const' declarations must be initialized" },
const_declarations_can_only_be_declared_inside_a_block: { code: 1156, category: DiagnosticCategory.Error, key: "'const' declarations can only be declared inside a block." },
let_declarations_can_only_be_declared_inside_a_block: { code: 1157, category: DiagnosticCategory.Error, key: "'let' declarations can only be declared inside a block." },
@@ -134,7 +125,6 @@ namespace ts {
Computed_property_names_are_not_allowed_in_enums: { code: 1164, category: DiagnosticCategory.Error, key: "Computed property names are not allowed in enums." },
A_computed_property_name_in_an_ambient_context_must_directly_refer_to_a_built_in_symbol: { code: 1165, category: DiagnosticCategory.Error, key: "A computed property name in an ambient context must directly refer to a built-in symbol." },
A_computed_property_name_in_a_class_property_declaration_must_directly_refer_to_a_built_in_symbol: { code: 1166, category: DiagnosticCategory.Error, key: "A computed property name in a class property declaration must directly refer to a built-in symbol." },
Computed_property_names_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1167, category: DiagnosticCategory.Error, key: "Computed property names are only available when targeting ECMAScript 6 and higher." },
A_computed_property_name_in_a_method_overload_must_directly_refer_to_a_built_in_symbol: { code: 1168, category: DiagnosticCategory.Error, key: "A computed property name in a method overload must directly refer to a built-in symbol." },
A_computed_property_name_in_an_interface_must_directly_refer_to_a_built_in_symbol: { code: 1169, category: DiagnosticCategory.Error, key: "A computed property name in an interface must directly refer to a built-in symbol." },
A_computed_property_name_in_a_type_literal_must_directly_refer_to_a_built_in_symbol: { code: 1170, category: DiagnosticCategory.Error, key: "A computed property name in a type literal must directly refer to a built-in symbol." },
@@ -150,7 +140,6 @@ namespace ts {
Property_destructuring_pattern_expected: { code: 1180, category: DiagnosticCategory.Error, key: "Property destructuring pattern expected." },
Array_element_destructuring_pattern_expected: { code: 1181, category: DiagnosticCategory.Error, key: "Array element destructuring pattern expected." },
A_destructuring_declaration_must_have_an_initializer: { code: 1182, category: DiagnosticCategory.Error, key: "A destructuring declaration must have an initializer." },
Destructuring_declarations_are_not_allowed_in_ambient_contexts: { code: 1183, category: DiagnosticCategory.Error, key: "Destructuring declarations are not allowed in ambient contexts." },
An_implementation_cannot_be_declared_in_ambient_contexts: { code: 1184, category: DiagnosticCategory.Error, key: "An implementation cannot be declared in ambient contexts." },
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." },
@@ -205,6 +194,12 @@ namespace ts {
with_statements_are_not_allowed_in_an_async_function_block: { code: 1300, category: DiagnosticCategory.Error, key: "'with' statements are not allowed in an async function block." },
await_expression_is_only_allowed_within_an_async_function: { code: 1308, category: DiagnosticCategory.Error, key: "'await' expression is only allowed within an async function." },
Async_functions_are_only_available_when_targeting_ECMAScript_6_and_higher: { code: 1311, category: DiagnosticCategory.Error, key: "Async functions are only available when targeting ECMAScript 6 and higher." },
The_return_type_of_a_property_decorator_function_must_be_either_void_or_any: { code: 1236, category: DiagnosticCategory.Error, key: "The return type of a property decorator function must be either 'void' or 'any'." },
The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any: { code: 1237, category: DiagnosticCategory.Error, key: "The return type of a parameter decorator function must be either 'void' or 'any'." },
Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression: { code: 1238, category: DiagnosticCategory.Error, key: "Unable to resolve signature of class decorator when called as an expression." },
Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression: { code: 1239, category: DiagnosticCategory.Error, key: "Unable to resolve signature of parameter decorator when called as an expression." },
Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression: { code: 1240, category: DiagnosticCategory.Error, key: "Unable to resolve signature of property decorator when called as an expression." },
Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression: { code: 1241, category: DiagnosticCategory.Error, key: "Unable to resolve signature of method decorator when called as an expression." },
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." },
@@ -213,7 +208,6 @@ namespace ts {
Module_0_has_no_exported_member_1: { code: 2305, category: DiagnosticCategory.Error, key: "Module '{0}' has no exported member '{1}'." },
File_0_is_not_a_module: { code: 2306, category: DiagnosticCategory.Error, key: "File '{0}' is not a module." },
Cannot_find_module_0: { code: 2307, category: DiagnosticCategory.Error, key: "Cannot find module '{0}'." },
A_module_cannot_have_more_than_one_export_assignment: { code: 2308, category: DiagnosticCategory.Error, key: "A module cannot have more than one export assignment." },
An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements: { code: 2309, category: DiagnosticCategory.Error, key: "An export assignment cannot be used in a module with other exported elements." },
Type_0_recursively_references_itself_as_a_base_type: { code: 2310, category: DiagnosticCategory.Error, key: "Type '{0}' recursively references itself as a base type." },
A_class_may_only_extend_another_class: { code: 2311, category: DiagnosticCategory.Error, key: "A class may only extend another class." },
@@ -398,11 +392,26 @@ namespace ts {
Cannot_find_namespace_0: { code: 2503, category: DiagnosticCategory.Error, key: "Cannot find namespace '{0}'." },
No_best_common_type_exists_among_yield_expressions: { code: 2504, category: DiagnosticCategory.Error, key: "No best common type exists among yield expressions." },
A_generator_cannot_have_a_void_type_annotation: { code: 2505, category: DiagnosticCategory.Error, key: "A generator cannot have a 'void' type annotation." },
_0_is_referenced_directly_or_indirectly_in_its_own_base_expression: { code: 2506, category: DiagnosticCategory.Error, key: "'{0}' is referenced directly or indirectly in its own base expression." },
Type_0_is_not_a_constructor_function_type: { code: 2507, category: DiagnosticCategory.Error, key: "Type '{0}' is not a constructor function type." },
No_base_constructor_has_the_specified_number_of_type_arguments: { code: 2508, category: DiagnosticCategory.Error, key: "No base constructor has the specified number of type arguments." },
Base_constructor_return_type_0_is_not_a_class_or_interface_type: { code: 2509, category: DiagnosticCategory.Error, key: "Base constructor return type '{0}' is not a class or interface type." },
Base_constructors_must_all_have_the_same_return_type: { code: 2510, category: DiagnosticCategory.Error, key: "Base constructors must all have the same return type." },
Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions: { code: 2520, category: DiagnosticCategory.Error, key: "Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions." },
Expression_resolves_to_variable_declaration_0_that_compiler_uses_to_support_async_functions: { code: 2521, category: DiagnosticCategory.Error, key: "Expression resolves to variable declaration '{0}' that compiler uses to support async functions." },
The_arguments_object_cannot_be_referenced_in_an_async_arrow_function_Consider_using_a_standard_async_function_expression: { code: 2522, category: DiagnosticCategory.Error, key: "The 'arguments' object cannot be referenced in an async arrow function. Consider using a standard async function expression." },
yield_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2523, category: DiagnosticCategory.Error, key: "'yield' expressions cannot be used in a parameter initializer." },
await_expressions_cannot_be_used_in_a_parameter_initializer: { code: 2524, category: DiagnosticCategory.Error, key: "'await' expressions cannot be used in a parameter initializer." },
JSX_element_attributes_type_0_must_be_an_object_type: { code: 2600, category: DiagnosticCategory.Error, key: "JSX element attributes type '{0}' must be an object type." },
The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: { code: 2601, category: DiagnosticCategory.Error, key: "The return type of a JSX element constructor must return an object type." },
JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: { code: 2602, category: DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist." },
Property_0_in_type_1_is_not_assignable_to_type_2: { code: 2603, category: DiagnosticCategory.Error, key: "Property '{0}' in type '{1}' is not assignable to type '{2}'" },
JSX_element_type_0_does_not_have_any_construct_or_call_signatures: { code: 2604, category: DiagnosticCategory.Error, key: "JSX element type '{0}' does not have any construct or call signatures." },
JSX_element_type_0_is_not_a_constructor_function_for_JSX_elements: { code: 2605, category: DiagnosticCategory.Error, key: "JSX element type '{0}' is not a constructor function for JSX elements." },
Property_0_of_JSX_spread_attribute_is_not_assignable_to_target_property: { code: 2606, category: DiagnosticCategory.Error, key: "Property '{0}' of JSX spread attribute is not assignable to target property." },
JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property: { code: 2607, category: DiagnosticCategory.Error, key: "JSX element class does not support attributes because it does not have a '{0}' property" },
The_global_type_JSX_0_may_not_have_more_than_one_property: { code: 2608, category: DiagnosticCategory.Error, key: "The global type 'JSX.{0}' may not have more than one property" },
Cannot_emit_namespaced_JSX_elements_in_React: { code: 2650, category: DiagnosticCategory.Error, key: "Cannot emit namespaced JSX elements in React" },
Import_declaration_0_is_using_private_name_1: { code: 4000, category: DiagnosticCategory.Error, key: "Import declaration '{0}' is using private name '{1}'." },
Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: { code: 4002, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported class has or is using private name '{1}'." },
Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: { code: 4004, category: DiagnosticCategory.Error, key: "Type parameter '{0}' of exported interface has or is using private name '{1}'." },
@@ -539,12 +548,13 @@ namespace ts {
File_0_has_unsupported_extension_The_only_supported_extensions_are_1: { code: 6054, category: DiagnosticCategory.Error, key: "File '{0}' has unsupported extension. The only supported extensions are {1}." },
Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures: { code: 6055, category: DiagnosticCategory.Message, key: "Suppress noImplicitAny errors for indexing objects lacking index signatures." },
Do_not_emit_declarations_for_code_that_has_an_internal_annotation: { code: 6056, category: DiagnosticCategory.Message, key: "Do not emit declarations for code that has an '@internal' annotation." },
Preserve_new_lines_when_emitting_code: { code: 6057, category: DiagnosticCategory.Message, key: "Preserve new-lines when emitting code." },
Specifies_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir: { code: 6058, category: DiagnosticCategory.Message, key: "Specifies the root directory of input files. Use to control the output directory structure with --outDir." },
File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files: { code: 6059, category: DiagnosticCategory.Error, key: "File '{0}' is not under 'rootDir' '{1}'. 'rootDir' is expected to contain all source files." },
Specifies_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix: { code: 6060, category: DiagnosticCategory.Message, key: "Specifies the end of line sequence to be used when emitting files: 'CRLF' (dos) or 'LF' (unix)." },
NEWLINE: { code: 6061, category: DiagnosticCategory.Message, key: "NEWLINE" },
Argument_for_newLine_option_must_be_CRLF_or_LF: { code: 6062, category: DiagnosticCategory.Error, key: "Argument for '--newLine' option must be 'CRLF' or 'LF'." },
Specify_JSX_code_generation_Colon_preserve_or_react: { code: 6080, category: DiagnosticCategory.Message, key: "Specify JSX code generation: 'preserve' or 'react'" },
Argument_for_jsx_must_be_preserve_or_react: { code: 6081, category: DiagnosticCategory.Message, key: "Argument for '--jsx' must be 'preserve' or 'react'." },
Option_experimentalDecorators_must_also_be_specified_when_option_emitDecoratorMetadata_is_specified: { code: 6064, category: DiagnosticCategory.Error, key: "Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified." },
Enables_experimental_support_for_ES7_decorators: { code: 6065, category: DiagnosticCategory.Message, key: "Enables experimental support for ES7 decorators." },
Enables_experimental_support_for_emitting_type_metadata_for_decorators: { code: 6066, category: DiagnosticCategory.Message, key: "Enables experimental support for emitting type metadata for decorators." },
@@ -566,6 +576,7 @@ namespace ts {
_0_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7023, category: DiagnosticCategory.Error, key: "'{0}' implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_referenced_directly_or_indirectly_in_one_of_its_return_expressions: { code: 7024, category: DiagnosticCategory.Error, key: "Function implicitly has return type 'any' because it does not have a return type annotation and is referenced directly or indirectly in one of its return expressions." },
Generator_implicitly_has_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type: { code: 7025, category: DiagnosticCategory.Error, key: "Generator implicitly has type '{0}' because it does not yield any values. Consider supplying a return type." },
JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists: { code: 7026, category: DiagnosticCategory.Error, key: "JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists" },
You_cannot_rename_this_element: { code: 8000, category: DiagnosticCategory.Error, key: "You cannot rename this element." },
You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: DiagnosticCategory.Error, key: "You cannot rename elements that are defined in the standard TypeScript library." },
import_can_only_be_used_in_a_ts_file: { code: 8002, category: DiagnosticCategory.Error, key: "'import ... =' can only be used in a .ts file." },
@@ -585,5 +596,10 @@ namespace ts {
decorators_can_only_be_used_in_a_ts_file: { code: 8017, category: DiagnosticCategory.Error, key: "'decorators' can only be used in a .ts file." },
Only_identifiers_Slashqualified_names_with_optional_type_arguments_are_currently_supported_in_a_class_extends_clauses: { code: 9002, category: DiagnosticCategory.Error, key: "Only identifiers/qualified-names with optional type arguments are currently supported in a class 'extends' clauses." },
class_expressions_are_not_currently_supported: { code: 9003, category: DiagnosticCategory.Error, key: "'class' expressions are not currently supported." },
JSX_attributes_must_only_be_assigned_a_non_empty_expression: { code: 17000, category: DiagnosticCategory.Error, key: "JSX attributes must only be assigned a non-empty 'expression'." },
JSX_elements_cannot_have_multiple_attributes_with_the_same_name: { code: 17001, category: DiagnosticCategory.Error, key: "JSX elements cannot have multiple attributes with the same name." },
Expected_corresponding_JSX_closing_tag_for_0: { code: 17002, category: DiagnosticCategory.Error, key: "Expected corresponding JSX closing tag for '{0}'." },
JSX_attribute_expected: { code: 17003, category: DiagnosticCategory.Error, key: "JSX attribute expected." },
Cannot_use_JSX_unless_the_jsx_flag_is_provided: { code: 17004, category: DiagnosticCategory.Error, key: "Cannot use JSX unless the '--jsx' flag is provided." },
};
}
+126 -57
View File
@@ -67,22 +67,6 @@
"category": "Error",
"code": 1023
},
"A class or interface declaration can only have one 'extends' clause.": {
"category": "Error",
"code": 1024
},
"An 'extends' clause must precede an 'implements' clause.": {
"category": "Error",
"code": 1025
},
"A class can only extend a single class.": {
"category": "Error",
"code": 1026
},
"A class declaration can only have one 'implements' clause.": {
"category": "Error",
"code": 1027
},
"Accessibility modifier already seen.": {
"category": "Error",
"code": 1028
@@ -99,10 +83,6 @@
"category": "Error",
"code": 1031
},
"An interface declaration cannot have an 'implements' clause.": {
"category": "Error",
"code": 1032
},
"'super' must be followed by an argument list or member access.": {
"category": "Error",
"code": 1034
@@ -403,10 +383,6 @@
"category": "Error",
"code": 1132
},
"Type reference expected.": {
"category": "Error",
"code": 1133
},
"Variable declaration expected.": {
"category": "Error",
"code": 1134
@@ -471,18 +447,6 @@
"category": "Error",
"code": 1150
},
"'var', 'let' or 'const' expected.": {
"category": "Error",
"code": 1152
},
"'let' declarations are only available when targeting ECMAScript 6 and higher.": {
"category": "Error",
"code": 1153
},
"'const' declarations are only available when targeting ECMAScript 6 and higher.": {
"category": "Error",
"code": 1154
},
"'const' declarations must be initialized": {
"category": "Error",
"code": 1155
@@ -523,10 +487,6 @@
"category": "Error",
"code": 1166
},
"Computed property names are only available when targeting ECMAScript 6 and higher.": {
"category": "Error",
"code": 1167
},
"A computed property name in a method overload must directly refer to a built-in symbol.": {
"category": "Error",
"code": 1168
@@ -587,10 +547,6 @@
"category": "Error",
"code": 1182
},
"Destructuring declarations are not allowed in ambient contexts.": {
"category": "Error",
"code": 1183
},
"An implementation cannot be declared in ambient contexts.": {
"category": "Error",
"code": 1184
@@ -726,7 +682,7 @@
"Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning.": {
"category": "Error",
"code": 1219
},
},
"Generators are only available when targeting ECMAScript 6 or higher.": {
"category": "Error",
"code": 1220
@@ -810,6 +766,31 @@
"code": 1311
},
"The return type of a property decorator function must be either 'void' or 'any'.": {
"category": "Error",
"code": 1236
},
"The return type of a parameter decorator function must be either 'void' or 'any'.": {
"category": "Error",
"code": 1237
},
"Unable to resolve signature of class decorator when called as an expression.": {
"category": "Error",
"code": 1238
},
"Unable to resolve signature of parameter decorator when called as an expression.": {
"category": "Error",
"code": 1239
},
"Unable to resolve signature of property decorator when called as an expression.": {
"category": "Error",
"code": 1240
},
"Unable to resolve signature of method decorator when called as an expression.": {
"category": "Error",
"code": 1241
},
"Duplicate identifier '{0}'.": {
"category": "Error",
"code": 2300
@@ -842,10 +823,6 @@
"category": "Error",
"code": 2307
},
"A module cannot have more than one export assignment.": {
"category": "Error",
"code": 2308
},
"An export assignment cannot be used in a module with other exported elements.": {
"category": "Error",
"code": 2309
@@ -1582,6 +1559,27 @@
"category": "Error",
"code": 2505
},
"'{0}' is referenced directly or indirectly in its own base expression.": {
"category": "Error",
"code": 2506
},
"Type '{0}' is not a constructor function type.": {
"category": "Error",
"code": 2507
},
"No base constructor has the specified number of type arguments.": {
"category": "Error",
"code": 2508
},
"Base constructor return type '{0}' is not a class or interface type.": {
"category": "Error",
"code": 2509
},
"Base constructors must all have the same return type.": {
"category": "Error",
"code": 2510
},
"Duplicate identifier '{0}'. Compiler uses declaration '{1}' to support async functions.": {
"category": "Error",
"code": 2520
@@ -1603,6 +1601,47 @@
"code": 2524
},
"JSX element attributes type '{0}' must be an object type.": {
"category": "Error",
"code": 2600
},
"The return type of a JSX element constructor must return an object type.": {
"category": "Error",
"code": 2601
},
"JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist.": {
"category": "Error",
"code": 2602
},
"Property '{0}' in type '{1}' is not assignable to type '{2}'": {
"category": "Error",
"code": 2603
},
"JSX element type '{0}' does not have any construct or call signatures.": {
"category": "Error",
"code": 2604
},
"JSX element type '{0}' is not a constructor function for JSX elements.": {
"category": "Error",
"code": 2605
},
"Property '{0}' of JSX spread attribute is not assignable to target property.": {
"category": "Error",
"code": 2606
},
"JSX element class does not support attributes because it does not have a '{0}' property": {
"category": "Error",
"code": 2607
},
"The global type 'JSX.{0}' may not have more than one property": {
"category": "Error",
"code": 2608
},
"Cannot emit namespaced JSX elements in React": {
"category": "Error",
"code": 2650
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
"code": 4000
@@ -1971,7 +2010,7 @@
"category": "Error",
"code": 5050
},
"Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided.": {
"Option 'inlineSources' can only be used when either option '--inlineSourceMap' or option '--sourceMap' is provided.": {
"category": "Error",
"code": 5051
},
@@ -2148,10 +2187,6 @@
"category": "Message",
"code": 6056
},
"Preserve new-lines when emitting code.": {
"category": "Message",
"code": 6057
},
"Specifies the root directory of input files. Use to control the output directory structure with --outDir.": {
"category": "Message",
"code": 6058
@@ -2164,14 +2199,22 @@
"category": "Message",
"code": 6060
},
"NEWLINE": {
"category": "Message",
"NEWLINE": {
"category": "Message",
"code": 6061
},
"Argument for '--newLine' option must be 'CRLF' or 'LF'.": {
"category": "Error",
"category": "Error",
"code": 6062
},
"Specify JSX code generation: 'preserve' or 'react'": {
"category": "Message",
"code": 6080
},
"Argument for '--jsx' must be 'preserve' or 'react'.": {
"category": "Message",
"code": 6081
},
"Option 'experimentalDecorators' must also be specified when option 'emitDecoratorMetadata' is specified.": {
"category": "Error",
"code": 6064
@@ -2257,6 +2300,12 @@
"category": "Error",
"code": 7025
},
"JSX element implicitly has type 'any' because no interface 'JSX.{0}' exists": {
"category": "Error",
"code": 7026
},
"You cannot rename this element.": {
"category": "Error",
"code": 8000
@@ -2333,5 +2382,25 @@
"'class' expressions are not currently supported.": {
"category": "Error",
"code": 9003
},
"JSX attributes must only be assigned a non-empty 'expression'.": {
"category": "Error",
"code": 17000
},
"JSX elements cannot have multiple attributes with the same name.": {
"category": "Error",
"code": 17001
},
"Expected corresponding JSX closing tag for '{0}'.": {
"category": "Error",
"code": 17002
},
"JSX attribute expected.": {
"category": "Error",
"code": 17003
},
"Cannot use JSX unless the '--jsx' flag is provided.": {
"category": "Error",
"code": 17004
}
}
+398 -40
View File
@@ -21,8 +21,7 @@ namespace ts {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};`;
// emit output for the __decorate helper function
@@ -68,11 +67,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let sourceMapDataList: SourceMapData[] = compilerOptions.sourceMap || compilerOptions.inlineSourceMap ? [] : undefined;
let diagnostics: Diagnostic[] = [];
let newLine = host.getNewLine();
let jsxDesugaring = host.getCompilerOptions().jsx !== JsxEmit.Preserve;
let shouldEmitJsx = (s: SourceFile) => (s.languageVariant === LanguageVariant.JSX && !jsxDesugaring);
if (targetSourceFile === undefined) {
forEach(host.getSourceFiles(), sourceFile => {
if (shouldEmitToOwnFile(sourceFile, compilerOptions)) {
let jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, ".js");
let jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, shouldEmitJsx(sourceFile) ? ".jsx" : ".js");
emitFile(jsFilePath, sourceFile);
}
});
@@ -84,7 +85,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
else {
// targetSourceFile is specified (e.g calling emitter from language service or calling getSemanticDiagnostic from language service)
if (shouldEmitToOwnFile(targetSourceFile, compilerOptions)) {
let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, ".js");
let jsFilePath = getOwnEmitOutputFilePath(targetSourceFile, host, forEach(host.getSourceFiles(), shouldEmitJsx) ? ".jsx" : ".js");
emitFile(jsFilePath, targetSourceFile);
}
else if (!isDeclarationFile(targetSourceFile) && compilerOptions.out) {
@@ -281,6 +282,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return makeUniqueName("default");
}
function generateNameForClassExpression() {
return makeUniqueName("class");
}
function generateNameForNode(node: Node) {
switch (node.kind) {
case SyntaxKind.Identifier:
@@ -293,9 +298,10 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return generateNameForImportOrExportDeclaration(<ImportDeclaration | ExportDeclaration>node);
case SyntaxKind.FunctionDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.ExportAssignment:
return generateNameForExportDefault();
case SyntaxKind.ClassExpression:
return generateNameForClassExpression();
}
}
@@ -336,7 +342,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let prevEncodedEmittedColumn = lastEncodedSourceMapSpan.emittedColumn;
// Line/Comma delimiters
if (lastEncodedSourceMapSpan.emittedLine == lastRecordedSourceMapSpan.emittedLine) {
if (lastEncodedSourceMapSpan.emittedLine === lastRecordedSourceMapSpan.emittedLine) {
// Emit comma to separate the entry
if (sourceMapData.sourceMapMappings) {
sourceMapData.sourceMapMappings += ",";
@@ -419,8 +425,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// If this location wasn't recorded or the location in source is going backwards, record the span
if (!lastRecordedSourceMapSpan ||
lastRecordedSourceMapSpan.emittedLine != emittedLine ||
lastRecordedSourceMapSpan.emittedColumn != emittedColumn ||
lastRecordedSourceMapSpan.emittedLine !== emittedLine ||
lastRecordedSourceMapSpan.emittedColumn !== emittedColumn ||
(lastRecordedSourceMapSpan.sourceIndex === sourceMapSourceIndex &&
(lastRecordedSourceMapSpan.sourceLine > sourceLinePos.line ||
(lastRecordedSourceMapSpan.sourceLine === sourceLinePos.line && lastRecordedSourceMapSpan.sourceColumn > sourceLinePos.character)))) {
@@ -670,7 +676,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (nodeIsSynthesized(node)) {
return emitNodeWithoutSourceMap(node);
}
if (node.kind != SyntaxKind.SourceFile) {
if (node.kind !== SyntaxKind.SourceFile) {
recordEmitNodeStartSpan(node);
emitNodeWithoutSourceMap(node);
recordEmitNodeEndSpan(node);
@@ -1123,6 +1129,224 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(span.literal);
}
function jsxEmitReact(node: JsxElement|JsxSelfClosingElement) {
/// Emit a tag name, which is either '"div"' for lower-cased names, or
/// 'Div' for upper-cased or dotted names
function emitTagName(name: Identifier|QualifiedName) {
if (name.kind === SyntaxKind.Identifier && isIntrinsicJsxName((<Identifier>name).text)) {
write('"');
emit(name);
write('"');
}
else {
emit(name);
}
}
/// Emit an attribute name, which is quoted if it needs to be quoted. Because
/// these emit into an object literal property name, we don't need to be worried
/// about keywords, just non-identifier characters
function emitAttributeName(name: Identifier) {
if (/[A-Za-z_]+[\w*]/.test(name.text)) {
write('"');
emit(name);
write('"');
}
else {
emit(name);
}
}
/// Emit an name/value pair for an attribute (e.g. "x: 3")
function emitJsxAttribute(node: JsxAttribute) {
emitAttributeName(node.name);
write(": ");
if (node.initializer) {
emit(node.initializer);
}
else {
write("true");
}
}
function emitJsxElement(openingNode: JsxOpeningLikeElement, children?: JsxChild[]) {
// Call React.createElement(tag, ...
emitLeadingComments(openingNode);
write("React.createElement(");
emitTagName(openingNode.tagName);
write(", ");
// Attribute list
if (openingNode.attributes.length === 0) {
// When there are no attributes, React wants "null"
write("null");
}
else {
// Either emit one big object literal (no spread attribs), or
// a call to React.__spread
let attrs = openingNode.attributes;
if (forEach(attrs, attr => attr.kind === SyntaxKind.JsxSpreadAttribute)) {
write("React.__spread(");
let haveOpenedObjectLiteral = false;
for (let i = 0; i < attrs.length; i++) {
if (attrs[i].kind === SyntaxKind.JsxSpreadAttribute) {
// If this is the first argument, we need to emit a {} as the first argument
if (i === 0) {
write("{}, ");
}
if (haveOpenedObjectLiteral) {
write("}");
haveOpenedObjectLiteral = false;
}
if (i > 0) {
write(", ");
}
emit((<JsxSpreadAttribute>attrs[i]).expression);
}
else {
Debug.assert(attrs[i].kind === SyntaxKind.JsxAttribute);
if (haveOpenedObjectLiteral) {
write(", ");
}
else {
haveOpenedObjectLiteral = true;
if (i > 0) {
write(", ");
}
write("{");
}
emitJsxAttribute(<JsxAttribute>attrs[i]);
}
}
if (haveOpenedObjectLiteral) write("}");
write(")"); // closing paren to React.__spread(
}
else {
// One object literal with all the attributes in them
write("{");
for (var i = 0; i < attrs.length; i++) {
if (i > 0) {
write(", ");
}
emitJsxAttribute(<JsxAttribute>attrs[i]);
}
write("}");
}
}
// Children
if (children) {
for (var i = 0; i < children.length; i++) {
// Don't emit empty expressions
if (children[i].kind === SyntaxKind.JsxExpression && !((<JsxExpression>children[i]).expression)) {
continue;
}
// Don't emit empty strings
if (children[i].kind === SyntaxKind.JsxText) {
let text = getTextToEmit(<JsxText>children[i]);
if(text !== undefined) {
write(', "');
write(text);
write('"');
}
}
else {
write(", ");
emit(children[i]);
}
}
}
// Closing paren
write(")"); // closes "React.createElement("
emitTrailingComments(openingNode);
}
if (node.kind === SyntaxKind.JsxElement) {
emitJsxElement((<JsxElement>node).openingElement, (<JsxElement>node).children);
}
else {
Debug.assert(node.kind === SyntaxKind.JsxSelfClosingElement);
emitJsxElement(<JsxSelfClosingElement>node);
}
}
function jsxEmitPreserve(node: JsxElement|JsxSelfClosingElement) {
function emitJsxAttribute(node: JsxAttribute) {
emit(node.name);
write("=");
emit(node.initializer);
}
function emitJsxSpreadAttribute(node: JsxSpreadAttribute) {
write("{...");
emit(node.expression);
write("}");
}
function emitAttributes(attribs: NodeArray<JsxAttribute|JsxSpreadAttribute>) {
for (let i = 0, n = attribs.length; i < n; i++) {
if (i > 0) {
write(" ");
}
if (attribs[i].kind === SyntaxKind.JsxSpreadAttribute) {
emitJsxSpreadAttribute(<JsxSpreadAttribute>attribs[i]);
}
else {
Debug.assert(attribs[i].kind === SyntaxKind.JsxAttribute);
emitJsxAttribute(<JsxAttribute>attribs[i]);
}
}
}
function emitJsxOpeningOrSelfClosingElement(node: JsxOpeningElement|JsxSelfClosingElement) {
write("<");
emit(node.tagName);
if (node.attributes.length > 0 || (node.kind === SyntaxKind.JsxSelfClosingElement)) {
write(" ");
}
emitAttributes(node.attributes);
if (node.kind === SyntaxKind.JsxSelfClosingElement) {
write("/>");
}
else {
write(">");
}
}
function emitJsxClosingElement(node: JsxClosingElement) {
write("</");
emit(node.tagName);
write(">");
}
function emitJsxElement(node: JsxElement) {
emitJsxOpeningOrSelfClosingElement(node.openingElement);
for (var i = 0, n = node.children.length; i < n; i++) {
emit(node.children[i]);
}
emitJsxClosingElement(node.closingElement);
}
if (node.kind === SyntaxKind.JsxElement) {
emitJsxElement(<JsxElement>node);
}
else {
Debug.assert(node.kind === SyntaxKind.JsxSelfClosingElement);
emitJsxOpeningOrSelfClosingElement(<JsxSelfClosingElement>node);
}
}
// This function specifically handles numeric/string literals for enum and accessor 'identifiers'.
// In a sense, it does not actually emit identifiers as much as it declares a name for a specific property.
// For example, this is utilized when feeding in a result to Object.defineProperty.
@@ -1199,6 +1423,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.IfStatement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
case SyntaxKind.NewExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.PostfixUnaryExpression:
@@ -1704,8 +1930,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function parenthesizeForAccess(expr: Expression): LeftHandSideExpression {
// When diagnosing whether the expression needs parentheses, the decision should be based
// on the innermost expression in a chain of nested type assertions.
while (expr.kind === SyntaxKind.TypeAssertionExpression) {
expr = (<TypeAssertion>expr).expression;
while (expr.kind === SyntaxKind.TypeAssertionExpression || expr.kind === SyntaxKind.AsExpression) {
expr = (<AssertionExpression>expr).expression;
}
// isLeftHandSideExpression is almost the correct criterion for when it is not necessary
@@ -1824,7 +2050,21 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emit(node.expression);
let indentedBeforeDot = indentIfOnDifferentLines(node, node.expression, node.dotToken);
write(".");
// 1 .toString is a valid property access, emit a space after the literal
let shouldEmitSpace: boolean;
if (!indentedBeforeDot && node.expression.kind === SyntaxKind.NumericLiteral) {
let text = getSourceTextOfNodeFromSourceFile(currentSourceFile, node.expression);
shouldEmitSpace = text.indexOf(tokenToString(SyntaxKind.DotToken)) < 0;
}
if (shouldEmitSpace) {
write(" .");
}
else {
write(".");
}
let indentedAfterDot = indentIfOnDifferentLines(node, node.dotToken, node.name);
emit(node.name);
decreaseIndentIf(indentedBeforeDot, indentedAfterDot);
@@ -1851,8 +2091,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
function skipParentheses(node: Expression): Expression {
while (node.kind === SyntaxKind.ParenthesizedExpression || node.kind === SyntaxKind.TypeAssertionExpression) {
node = (<ParenthesizedExpression | TypeAssertion>node).expression;
while (node.kind === SyntaxKind.ParenthesizedExpression || node.kind === SyntaxKind.TypeAssertionExpression || node.kind === SyntaxKind.AsExpression) {
node = (<ParenthesizedExpression | AssertionExpression>node).expression;
}
return node;
}
@@ -2002,12 +2242,12 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
// not the user. If we didn't want them, the emitter would not have put them
// there.
if (!nodeIsSynthesized(node) && node.parent.kind !== SyntaxKind.ArrowFunction) {
if (node.expression.kind === SyntaxKind.TypeAssertionExpression) {
if (node.expression.kind === SyntaxKind.TypeAssertionExpression || node.expression.kind === SyntaxKind.AsExpression) {
let operand = (<TypeAssertion>node.expression).expression;
// Make sure we consider all nested cast expressions, e.g.:
// (<any><number><any>-A).x;
while (operand.kind == SyntaxKind.TypeAssertionExpression) {
while (operand.kind === SyntaxKind.TypeAssertionExpression || operand.kind === SyntaxKind.AsExpression) {
operand = (<TypeAssertion>operand).expression;
}
@@ -3181,33 +3421,49 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
function emitDefaultValueAssignments(node: FunctionLikeDeclaration) {
if (languageVersion < ScriptTarget.ES6) {
let tempIndex = 0;
forEach(node.parameters, p => {
forEach(node.parameters, parameter => {
// A rest parameter cannot have a binding pattern or an initializer,
// so let's just ignore it.
if (p.dotDotDotToken) {
if (parameter.dotDotDotToken) {
return;
}
if (isBindingPattern(p.name)) {
writeLine();
write("var ");
emitDestructuring(p, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]);
write(";");
tempIndex++;
let { name: paramName, initializer } = parameter;
if (isBindingPattern(paramName)) {
// In cases where a binding pattern is simply '[]' or '{}',
// we usually don't want to emit a var declaration; however, in the presence
// of an initializer, we must emit that expression to preserve side effects.
let hasBindingElements = paramName.elements.length > 0;
if (hasBindingElements || initializer) {
writeLine();
write("var ");
if (hasBindingElements) {
emitDestructuring(parameter, /*isAssignmentExpressionStatement*/ false, tempParameters[tempIndex]);
}
else {
emit(tempParameters[tempIndex]);
write(" = ");
emit(initializer);
}
write(";");
tempIndex++;
}
}
else if (p.initializer) {
else if (initializer) {
writeLine();
emitStart(p);
emitStart(parameter);
write("if (");
emitNodeWithoutSourceMap(p.name);
emitNodeWithoutSourceMap(paramName);
write(" === void 0)");
emitEnd(p);
emitEnd(parameter);
write(" { ");
emitStart(p);
emitNodeWithoutSourceMap(p.name);
emitStart(parameter);
emitNodeWithoutSourceMap(paramName);
write(" = ");
emitNodeWithoutSourceMap(p.initializer);
emitEnd(p);
emitNodeWithoutSourceMap(initializer);
emitEnd(parameter);
write("; }");
}
});
@@ -3990,7 +4246,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
emitClassLikeDeclarationForES6AndHigher(node);
}
}
function emitClassLikeDeclarationForES6AndHigher(node: ClassLikeDeclaration) {
let thisNodeIsDecorated = nodeIsDecorated(node);
if (node.kind === SyntaxKind.ClassDeclaration) {
@@ -4249,7 +4505,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write(".prototype");
}
}
function emitDecoratorsOfClass(node: ClassLikeDeclaration) {
emitDecoratorsOfMembers(node, /*staticFlag*/ 0);
emitDecoratorsOfMembers(node, NodeFlags.Static);
@@ -5161,7 +5417,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
let started = false;
for (let importNode of externalImports) {
// do not create variable declaration for exports and imports that lack import clause
let skipNode =
let skipNode =
importNode.kind === SyntaxKind.ExportDeclaration ||
(importNode.kind === SyntaxKind.ImportDeclaration && !(<ImportDeclaration>importNode).importClause)
@@ -5258,7 +5514,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
write("};");
return emitExportStarFunction(exportedNamesStorageRef);
function emitExportStarFunction(localNames: string): string {
const exportStarFunction = makeUniqueName("exportStar");
@@ -5285,7 +5541,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return exportStarFunction;
}
function writeExportedName(node: Identifier | Declaration): void {
// do not record default exports
// they are local to module and never overwritten (explicitly skipped) by star export
@@ -5530,7 +5786,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
decreaseIndent();
writeLine();
write("}"); // return
emitTempDeclarations(/*newLine*/ true)
emitTempDeclarations(/*newLine*/ true);
}
function emitSetters(exportStarFunction: string) {
@@ -5581,7 +5837,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (importNode.kind === SyntaxKind.ImportDeclaration &&
(<ImportDeclaration>importNode).importClause.namedBindings) {
let namedBindings = (<ImportDeclaration>importNode).importClause.namedBindings;
if (namedBindings.kind === SyntaxKind.NamespaceImport) {
// emit re-export for namespace
@@ -5840,6 +6096,99 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
}
}
function emitJsxElement(node: JsxElement | JsxSelfClosingElement) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
jsxEmitReact(node);
break;
case JsxEmit.Preserve:
// Fall back to preserve if None was specified (we'll error earlier)
default:
jsxEmitPreserve(node);
break;
}
}
function trimReactWhitespace(node: JsxText): string {
let result: string = undefined;
let text = getTextOfNode(node);
let firstNonWhitespace = 0;
let lastNonWhitespace = -1;
// JSX trims whitespace at the end and beginning of lines, except that the
// start/end of a tag is considered a start/end of a line only if that line is
// on the same line as the closing tag. See examples in tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
for (let i = 0; i < text.length; i++) {
let c = text.charCodeAt(i);
if (isLineBreak(c)) {
if (firstNonWhitespace !== -1 && (lastNonWhitespace - firstNonWhitespace + 1 > 0)) {
let part = text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1);
result = (result ? result + '" + \' \' + "' : '') + part;
}
firstNonWhitespace = -1;
}
else if (!isWhiteSpace(c)) {
lastNonWhitespace = i;
if (firstNonWhitespace === -1) {
firstNonWhitespace = i;
}
}
}
if (firstNonWhitespace !== -1) {
let part = text.substr(firstNonWhitespace);
result = (result ? result + '" + \' \' + "' : '') + part;
}
return result;
}
function getTextToEmit(node: JsxText) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
let text = trimReactWhitespace(node);
if (text.length === 0) {
return undefined;
}
else {
return text;
}
case JsxEmit.Preserve:
default:
return getTextOfNode(node, true);
}
}
function emitJsxText(node: JsxText) {
switch (compilerOptions.jsx) {
case JsxEmit.React:
write('"');
write(trimReactWhitespace(node));
write('"');
break;
case JsxEmit.Preserve:
default: // Emit JSX-preserve as default when no --jsx flag is specified
write(getTextOfNode(node, true));
break;
}
}
function emitJsxExpression(node: JsxExpression) {
if (node.expression) {
switch (compilerOptions.jsx) {
case JsxEmit.Preserve:
default:
write('{');
emit(node.expression);
write('}');
break;
case JsxEmit.React:
emit(node.expression);
break;
}
}
}
function emitDirectivePrologues(statements: Node[], startWithNewLine: boolean): number {
for (let i = 0; i < statements.length; ++i) {
if (isPrologueDirective(statements[i])) {
@@ -5987,7 +6336,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
if (node.kind !== SyntaxKind.Block &&
node.parent &&
node.parent.kind === SyntaxKind.ArrowFunction &&
(<ArrowFunction>node.parent).body === node &&
(<ArrowFunction>node.parent).body === node &&
compilerOptions.target <= ScriptTarget.ES5) {
return false;
@@ -6032,6 +6381,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return emitTemplateExpression(<TemplateExpression>node);
case SyntaxKind.TemplateSpan:
return emitTemplateSpan(<TemplateSpan>node);
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
return emitJsxElement(<JsxElement|JsxSelfClosingElement>node);
case SyntaxKind.JsxText:
return emitJsxText(<JsxText>node);
case SyntaxKind.JsxExpression:
return emitJsxExpression(<JsxExpression>node);
case SyntaxKind.QualifiedName:
return emitQualifiedName(<QualifiedName>node);
case SyntaxKind.ObjectBindingPattern:
@@ -6062,6 +6418,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promi
return emitTaggedTemplateExpression(<TaggedTemplateExpression>node);
case SyntaxKind.TypeAssertionExpression:
return emit((<TypeAssertion>node).expression);
case SyntaxKind.AsExpression:
return emit((<AsExpression>node).expression);
case SyntaxKind.ParenthesizedExpression:
return emitParenExpression(<ParenthesizedExpression>node);
case SyntaxKind.FunctionDeclaration:
+269 -7
View File
@@ -164,6 +164,9 @@ namespace ts {
return visitNode(cbNode, (<BinaryExpression>node).left) ||
visitNode(cbNode, (<BinaryExpression>node).operatorToken) ||
visitNode(cbNode, (<BinaryExpression>node).right);
case SyntaxKind.AsExpression:
return visitNode(cbNode, (<AsExpression>node).expression) ||
visitNode(cbNode, (<AsExpression>node).type);
case SyntaxKind.ConditionalExpression:
return visitNode(cbNode, (<ConditionalExpression>node).condition) ||
visitNode(cbNode, (<ConditionalExpression>node).questionToken) ||
@@ -321,6 +324,25 @@ namespace ts {
return visitNode(cbNode, (<ExternalModuleReference>node).expression);
case SyntaxKind.MissingDeclaration:
return visitNodes(cbNodes, node.decorators);
case SyntaxKind.JsxElement:
return visitNode(cbNode, (<JsxElement>node).openingElement) ||
visitNodes(cbNodes, (<JsxElement>node).children) ||
visitNode(cbNode, (<JsxElement>node).closingElement);
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.JsxOpeningElement:
return visitNode(cbNode, (<JsxOpeningLikeElement>node).tagName) ||
visitNodes(cbNodes, (<JsxOpeningLikeElement>node).attributes);
case SyntaxKind.JsxAttribute:
return visitNode(cbNode, (<JsxAttribute>node).name) ||
visitNode(cbNode, (<JsxAttribute>node).initializer);
case SyntaxKind.JsxSpreadAttribute:
return visitNode(cbNode, (<JsxSpreadAttribute>node).expression);
case SyntaxKind.JsxExpression:
return visitNode(cbNode, (<JsxExpression>node).expression);
case SyntaxKind.JsxClosingElement:
return visitNode(cbNode, (<JsxClosingElement>node).tagName);
case SyntaxKind.JSDocTypeExpression:
return visitNode(cbNode, (<JSDocTypeExpression>node).type);
case SyntaxKind.JSDocUnionType:
@@ -524,6 +546,7 @@ namespace ts {
scanner.setText(sourceText);
scanner.setOnError(scanError);
scanner.setScriptTarget(languageVersion);
scanner.setLanguageVariant(isTsx(fileName) ? LanguageVariant.JSX : LanguageVariant.Standard);
}
function clearState() {
@@ -636,6 +659,7 @@ namespace ts {
sourceFile.languageVersion = languageVersion;
sourceFile.fileName = normalizePath(fileName);
sourceFile.flags = fileExtensionIs(sourceFile.fileName, ".d.ts") ? NodeFlags.DeclarationFile : 0;
sourceFile.languageVariant = isTsx(sourceFile.fileName) ? LanguageVariant.JSX : LanguageVariant.Standard;
return sourceFile;
}
@@ -815,6 +839,10 @@ namespace ts {
return token = scanner.reScanTemplateToken();
}
function scanJsxIdentifier(): SyntaxKind {
return token = scanner.scanJsxIdentifier();
}
function speculationHelper<T>(callback: () => T, isLookAhead: boolean): T {
// Keep track of the state we'll need to rollback to if lookahead fails (or if the
// caller asked us to always reset our state).
@@ -1179,6 +1207,10 @@ namespace ts {
return isHeritageClause();
case ParsingContext.ImportOrExportSpecifiers:
return isIdentifierOrKeyword();
case ParsingContext.JsxAttributes:
return isIdentifierOrKeyword() || token === SyntaxKind.OpenBraceToken;
case ParsingContext.JsxChildren:
return true;
case ParsingContext.JSDocFunctionParameters:
case ParsingContext.JSDocTypeArguments:
case ParsingContext.JSDocTupleTypes:
@@ -1269,6 +1301,10 @@ namespace ts {
return token === SyntaxKind.GreaterThanToken || token === SyntaxKind.OpenParenToken;
case ParsingContext.HeritageClauses:
return token === SyntaxKind.OpenBraceToken || token === SyntaxKind.CloseBraceToken;
case ParsingContext.JsxAttributes:
return token === SyntaxKind.GreaterThanToken || token === SyntaxKind.SlashToken;
case ParsingContext.JsxChildren:
return token === SyntaxKind.LessThanToken && lookAhead(nextTokenIsSlash);
case ParsingContext.JSDocFunctionParameters:
return token === SyntaxKind.CloseParenToken || token === SyntaxKind.ColonToken || token === SyntaxKind.CloseBraceToken;
case ParsingContext.JSDocTypeArguments:
@@ -1485,6 +1521,12 @@ namespace ts {
// name list, and there can be left hand side expressions (which can have type
// arguments.)
case ParsingContext.HeritageClauseElement:
// Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
// on any given element. Same for children.
case ParsingContext.JsxAttributes:
case ParsingContext.JsxChildren:
}
return false;
@@ -1495,12 +1537,20 @@ namespace ts {
switch (node.kind) {
case SyntaxKind.Constructor:
case SyntaxKind.IndexSignature:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
case SyntaxKind.PropertyDeclaration:
case SyntaxKind.SemicolonClassElement:
return true;
case SyntaxKind.MethodDeclaration:
// Method declarations are not necessarily reusable. An object-literal
// may have a method calls "constructor(...)" and we must reparse that
// into an actual .ConstructorDeclaration.
let methodDeclaration = <MethodDeclaration>node;
let nameIsConstructor = methodDeclaration.name.kind === SyntaxKind.Identifier &&
(<Identifier>methodDeclaration.name).originalKeywordKind === SyntaxKind.ConstructorKeyword;
return !nameIsConstructor;
}
}
@@ -1643,6 +1693,8 @@ namespace ts {
case ParsingContext.TupleElementTypes: return Diagnostics.Type_expected;
case ParsingContext.HeritageClauses: return Diagnostics.Unexpected_token_expected;
case ParsingContext.ImportOrExportSpecifiers: return Diagnostics.Identifier_expected;
case ParsingContext.JsxAttributes: return Diagnostics.Identifier_expected;
case ParsingContext.JsxChildren: return Diagnostics.Identifier_expected;
case ParsingContext.JSDocFunctionParameters: return Diagnostics.Parameter_declaration_expected;
case ParsingContext.JSDocTypeArguments: return Diagnostics.Type_argument_expected;
case ParsingContext.JSDocTupleTypes: return Diagnostics.Type_expected;
@@ -2803,6 +2855,33 @@ namespace ts {
return Tristate.False;
}
// JSX overrides
if (sourceFile.languageVariant === LanguageVariant.JSX) {
let isArrowFunctionInJsx = lookAhead(() => {
let third = nextToken();
if (third === SyntaxKind.ExtendsKeyword) {
let fourth = nextToken();
switch (fourth) {
case SyntaxKind.EqualsToken:
case SyntaxKind.GreaterThanToken:
return false;
default:
return true;
}
}
else if (third === SyntaxKind.CommaToken) {
return true;
}
return false;
});
if (isArrowFunctionInJsx) {
return Tristate.True;
}
return Tristate.False;
}
// This *could* be a parenthesized arrow function.
return Tristate.Unknown;
}
@@ -2924,7 +3003,23 @@ namespace ts {
break;
}
leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
if (token === SyntaxKind.AsKeyword) {
// Make sure we *do* perform ASI for constructs like this:
// var x = foo
// as (Bar)
// This should be parsed as an initialized variable, followed
// by a function call to 'as' with the argument 'Bar'
if (scanner.hasPrecedingLineBreak()) {
break;
}
else {
nextToken();
leftOperand = makeAsExpression(leftOperand, parseType());
}
}
else {
leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence));
}
}
return leftOperand;
@@ -2961,6 +3056,7 @@ namespace ts {
case SyntaxKind.GreaterThanEqualsToken:
case SyntaxKind.InstanceOfKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.AsKeyword:
return 7;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.GreaterThanGreaterThanToken:
@@ -2988,6 +3084,13 @@ namespace ts {
return finishNode(node);
}
function makeAsExpression(left: Expression, right: TypeNode): AsExpression {
let node = <AsExpression>createNode(SyntaxKind.AsExpression, left.pos);
node.expression = left;
node.type = right;
return finishNode(node);
}
function parsePrefixUnaryExpression() {
let node = <PrefixUnaryExpression>createNode(SyntaxKind.PrefixUnaryExpression);
node.operator = token;
@@ -3057,7 +3160,13 @@ namespace ts {
case SyntaxKind.VoidKeyword:
return parseVoidExpression();
case SyntaxKind.LessThanToken:
return parseTypeAssertion();
if (sourceFile.languageVariant !== LanguageVariant.JSX) {
return parseTypeAssertion();
}
if(lookAhead(nextTokenIsIdentifier)) {
return parseJsxElementOrSelfClosingElement();
}
// Fall through
default:
return parsePostfixExpressionOrHigher();
}
@@ -3184,6 +3293,154 @@ namespace ts {
node.name = parseRightSideOfDot(/*allowIdentifierNames*/ true);
return finishNode(node);
}
function parseJsxElementOrSelfClosingElement(): JsxElement|JsxSelfClosingElement {
let opening = parseJsxOpeningOrSelfClosingElement();
if (opening.kind === SyntaxKind.JsxOpeningElement) {
let node = <JsxElement>createNode(SyntaxKind.JsxElement, opening.pos);
node.openingElement = opening;
node.children = parseJsxChildren(node.openingElement.tagName);
node.closingElement = parseJsxClosingElement();
return finishNode(node);
}
else {
Debug.assert(opening.kind === SyntaxKind.JsxSelfClosingElement);
// Nothing else to do for self-closing elements
return <JsxSelfClosingElement>opening;
}
}
function parseJsxText(): JsxText {
let node = <JsxText>createNode(SyntaxKind.JsxText, scanner.getStartPos());
token = scanner.scanJsxToken();
return finishNode(node);
}
function parseJsxChild(): JsxChild {
switch (token) {
case SyntaxKind.JsxText:
return parseJsxText();
case SyntaxKind.OpenBraceToken:
return parseJsxExpression();
case SyntaxKind.LessThanToken:
return parseJsxElementOrSelfClosingElement();
}
Debug.fail('Unknown JSX child kind ' + token);
}
function parseJsxChildren(openingTagName: EntityName): NodeArray<JsxChild> {
let result = <NodeArray<JsxChild>>[];
result.pos = scanner.getStartPos();
let saveParsingContext = parsingContext;
parsingContext |= 1 << ParsingContext.JsxChildren;
while(true) {
token = scanner.reScanJsxToken();
if (token === SyntaxKind.LessThanSlashToken) {
break;
}
else if (token === SyntaxKind.EndOfFileToken) {
parseErrorAtCurrentToken(Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, getTextOfNodeFromSourceText(sourceText, openingTagName));
break;
}
result.push(parseJsxChild());
}
result.end = scanner.getTokenPos();
parsingContext = saveParsingContext;
return result;
}
function parseJsxOpeningOrSelfClosingElement(): JsxOpeningElement|JsxSelfClosingElement {
let fullStart = scanner.getStartPos();
parseExpected(SyntaxKind.LessThanToken);
let tagName = parseJsxElementName();
let attributes = parseList(ParsingContext.JsxAttributes, parseJsxAttribute);
let node: JsxOpeningLikeElement;
if (parseOptional(SyntaxKind.GreaterThanToken)) {
node = <JsxOpeningElement>createNode(SyntaxKind.JsxOpeningElement, fullStart);
}
else {
parseExpected(SyntaxKind.SlashToken);
parseExpected(SyntaxKind.GreaterThanToken);
node = <JsxSelfClosingElement>createNode(SyntaxKind.JsxSelfClosingElement, fullStart);
}
node.tagName = tagName;
node.attributes = attributes;
return finishNode(node);
}
function parseJsxElementName(): EntityName {
scanJsxIdentifier();
let elementName: EntityName = parseIdentifier();
while (parseOptional(SyntaxKind.DotToken)) {
scanJsxIdentifier();
let node = <QualifiedName>createNode(SyntaxKind.QualifiedName, elementName.pos);
node.left = elementName;
node.right = parseIdentifierName();
elementName = finishNode(node);
}
return elementName;
}
function parseJsxExpression(): JsxExpression {
let node = <JsxExpression>createNode(SyntaxKind.JsxExpression);
parseExpected(SyntaxKind.OpenBraceToken);
if (token !== SyntaxKind.CloseBraceToken) {
node.expression = parseExpression();
}
parseExpected(SyntaxKind.CloseBraceToken);
return finishNode(node);
}
function parseJsxAttribute(): JsxAttribute | JsxSpreadAttribute {
if (token === SyntaxKind.OpenBraceToken) {
return parseJsxSpreadAttribute();
}
scanJsxIdentifier();
let node = <JsxAttribute>createNode(SyntaxKind.JsxAttribute);
node.name = parseIdentifierName();
if (parseOptional(SyntaxKind.EqualsToken)) {
switch (token) {
case SyntaxKind.StringLiteral:
node.initializer = parseLiteralNode();
break;
default:
node.initializer = parseJsxExpression();
break;
}
}
return finishNode(node);
}
function parseJsxSpreadAttribute(): JsxSpreadAttribute {
let node = <JsxSpreadAttribute>createNode(SyntaxKind.JsxSpreadAttribute);
parseExpected(SyntaxKind.OpenBraceToken);
parseExpected(SyntaxKind.DotDotDotToken);
node.expression = parseExpression();
parseExpected(SyntaxKind.CloseBraceToken);
return finishNode(node);
}
function parseJsxClosingElement(): JsxClosingElement {
let node = <JsxClosingElement>createNode(SyntaxKind.JsxClosingElement);
parseExpected(SyntaxKind.LessThanSlashToken);
node.tagName = parseJsxElementName();
parseExpected(SyntaxKind.GreaterThanToken);
return finishNode(node);
}
function parseTypeAssertion(): TypeAssertion {
let node = <TypeAssertion>createNode(SyntaxKind.TypeAssertionExpression);
@@ -4060,7 +4317,7 @@ namespace ts {
parseExportAssignment(fullStart, decorators, modifiers) :
parseExportDeclaration(fullStart, decorators, modifiers);
default:
if (decorators) {
if (decorators || modifiers) {
// We reached this point because we encountered decorators and/or modifiers and assumed a declaration
// would follow. For recovery and error reporting purposes, return an incomplete declaration.
let node = <Statement>createMissingNode(SyntaxKind.MissingDeclaration, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected);
@@ -4485,7 +4742,7 @@ namespace ts {
return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers);
}
if (decorators) {
if (decorators || modifiers) {
// treat this as a property declaration with a missing name.
let name = <Identifier>createMissingNode(SyntaxKind.Identifier, /*reportAtCurrentPosition*/ true, Diagnostics.Declaration_expected);
return parsePropertyDeclaration(fullStart, decorators, modifiers, name, /*questionToken*/ undefined);
@@ -4682,6 +4939,10 @@ namespace ts {
return nextToken() === SyntaxKind.OpenParenToken;
}
function nextTokenIsSlash() {
return nextToken() === SyntaxKind.SlashToken;
}
function nextTokenIsCommaOrFromKeyword() {
nextToken();
return token === SyntaxKind.CommaToken ||
@@ -4882,7 +5143,7 @@ namespace ts {
}
function processReferenceComments(sourceFile: SourceFile): void {
let triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, sourceText);
let triviaScanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/false, LanguageVariant.Standard, sourceText);
let referencedFiles: FileReference[] = [];
let amdDependencies: { path: string; name: string }[] = [];
let amdModuleName: string;
@@ -4969,6 +5230,8 @@ namespace ts {
ArrayBindingElements, // Binding elements in array binding list
ArgumentExpressions, // Expressions in argument list
ObjectLiteralMembers, // Members in object literal
JsxAttributes, // Attributes in jsx element
JsxChildren, // Things between opening and closing JSX tags
ArrayLiteralMembers, // Members in array literal
Parameters, // Parameters in parameter list
TypeParameters, // Type parameters in type parameter list
@@ -5443,7 +5706,6 @@ namespace ts {
let atToken = createNode(SyntaxKind.AtToken, pos - 1);
atToken.end = pos;
let startPos = pos;
let tagName = scanIdentifier();
if (!tagName) {
return;
+8 -10
View File
@@ -105,7 +105,10 @@ namespace ts {
}
export function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile): Diagnostic[] {
let diagnostics = program.getSyntacticDiagnostics(sourceFile).concat(program.getGlobalDiagnostics()).concat(program.getSemanticDiagnostics(sourceFile));
let diagnostics = program.getOptionsDiagnostics().concat(
program.getSyntacticDiagnostics(sourceFile),
program.getGlobalDiagnostics(),
program.getSemanticDiagnostics(sourceFile));
if (program.getCompilerOptions().declaration) {
diagnostics.concat(program.getDeclarationDiagnostics(sourceFile));
@@ -177,10 +180,10 @@ namespace ts {
getSourceFiles: () => files,
getCompilerOptions: () => options,
getSyntacticDiagnostics,
getOptionsDiagnostics,
getGlobalDiagnostics,
getSemanticDiagnostics,
getDeclarationDiagnostics,
getCompilerOptionsDiagnostics,
getTypeChecker,
getClassifiableNames,
getDiagnosticsProducingTypeChecker,
@@ -311,19 +314,15 @@ namespace ts {
}
}
function getCompilerOptionsDiagnostics(): Diagnostic[] {
function getOptionsDiagnostics(): Diagnostic[] {
let allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, diagnostics.getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function getGlobalDiagnostics(): Diagnostic[] {
let typeChecker = getDiagnosticsProducingTypeChecker();
let allDiagnostics: Diagnostic[] = [];
addRange(allDiagnostics, typeChecker.getGlobalDiagnostics());
addRange(allDiagnostics, diagnostics.getGlobalDiagnostics());
addRange(allDiagnostics, getDiagnosticsProducingTypeChecker().getGlobalDiagnostics());
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
@@ -338,7 +337,6 @@ namespace ts {
function processSourceFile(fileName: string, isDefaultLib: boolean, refFile?: SourceFile, refPos?: number, refEnd?: number) {
let start: number;
let length: number;
let extensions: string;
let diagnosticArgument: string[];
if (refEnd !== undefined && refPos !== undefined) {
start = refPos;
@@ -683,4 +681,4 @@ namespace ts {
}
}
}
}
}
+98 -2
View File
@@ -21,12 +21,16 @@ namespace ts {
reScanGreaterToken(): SyntaxKind;
reScanSlashToken(): SyntaxKind;
reScanTemplateToken(): SyntaxKind;
scanJsxIdentifier(): SyntaxKind;
reScanJsxToken(): SyntaxKind;
scanJsxToken(): SyntaxKind;
scan(): SyntaxKind;
// Sets the text for the scanner to scan. An optional subrange starting point and length
// can be provided to have the scanner only scan a portion of the text.
setText(text: string, start?: number, length?: number): void;
setOnError(onError: ErrorCallback): void;
setScriptTarget(scriptTarget: ScriptTarget): void;
setLanguageVariant(variant: LanguageVariant): void;
setTextPos(textPos: number): void;
// Invokes the provided callback then unconditionally restores the scanner to the state it
// was in immediately prior to invoking the callback. The result of invoking the callback
@@ -132,6 +136,7 @@ namespace ts {
"++": SyntaxKind.PlusPlusToken,
"--": SyntaxKind.MinusMinusToken,
"<<": SyntaxKind.LessThanLessThanToken,
"</": SyntaxKind.LessThanSlashToken,
">>": SyntaxKind.GreaterThanGreaterThanToken,
">>>": SyntaxKind.GreaterThanGreaterThanGreaterThanToken,
"&": SyntaxKind.AmpersandToken,
@@ -378,8 +383,31 @@ namespace ts {
return ch >= CharacterCodes._0 && ch <= CharacterCodes._7;
}
export function couldStartTrivia(text: string, pos: number): boolean {
// Keep in sync with skipTrivia
let ch = text.charCodeAt(pos);
switch (ch) {
case CharacterCodes.carriageReturn:
case CharacterCodes.lineFeed:
case CharacterCodes.tab:
case CharacterCodes.verticalTab:
case CharacterCodes.formFeed:
case CharacterCodes.space:
case CharacterCodes.slash:
// starts of normal trivia
case CharacterCodes.lessThan:
case CharacterCodes.equals:
case CharacterCodes.greaterThan:
// Starts of conflict marker trivia
return true;
default:
return ch > CharacterCodes.maxAsciiCharacter;
}
}
/* @internal */
export function skipTrivia(text: string, pos: number, stopAfterLineBreak?: boolean): number {
// Keep in sync with couldStartTrivia
while (true) {
let ch = text.charCodeAt(pos);
switch (ch) {
@@ -600,11 +628,12 @@ namespace ts {
ch >= CharacterCodes._0 && ch <= CharacterCodes._9 || ch === CharacterCodes.$ || ch === CharacterCodes._ ||
ch > CharacterCodes.maxAsciiCharacter && isUnicodeIdentifierPart(ch, languageVersion);
}
/* @internal */
// Creates a scanner over a (possibly unspecified) range of a piece of text.
export function createScanner(languageVersion: ScriptTarget,
skipTrivia: boolean,
languageVariant = LanguageVariant.Standard,
text?: string,
onError?: ErrorCallback,
start?: number,
@@ -644,9 +673,13 @@ namespace ts {
reScanGreaterToken,
reScanSlashToken,
reScanTemplateToken,
scanJsxIdentifier,
reScanJsxToken,
scanJsxToken,
scan,
setText,
setScriptTarget,
setLanguageVariant,
setOnError,
setTextPos,
tryScan,
@@ -936,7 +969,7 @@ namespace ts {
error(Diagnostics.Unexpected_end_of_text);
isInvalidExtendedEscape = true;
}
else if (text.charCodeAt(pos) == CharacterCodes.closeBrace) {
else if (text.charCodeAt(pos) === CharacterCodes.closeBrace) {
// Only swallow the following character up if it's a '}'.
pos++;
}
@@ -1281,6 +1314,9 @@ namespace ts {
if (text.charCodeAt(pos + 1) === CharacterCodes.equals) {
return pos += 2, token = SyntaxKind.LessThanEqualsToken;
}
if (text.charCodeAt(pos + 1) === CharacterCodes.slash && languageVariant === LanguageVariant.JSX) {
return pos += 2, token = SyntaxKind.LessThanSlashToken;
}
return pos++, token = SyntaxKind.LessThanToken;
case CharacterCodes.equals:
if (isConflictMarkerTrivia(text, pos)) {
@@ -1460,6 +1496,62 @@ namespace ts {
return token = scanTemplateAndSetTokenValue();
}
function reScanJsxToken(): SyntaxKind {
pos = tokenPos = startPos;
return token = scanJsxToken();
}
function scanJsxToken(): SyntaxKind {
startPos = tokenPos = pos;
if (pos >= end) {
return token = SyntaxKind.EndOfFileToken;
}
let char = text.charCodeAt(pos);
if (char === CharacterCodes.lessThan) {
if (text.charCodeAt(pos + 1) === CharacterCodes.slash) {
pos += 2;
return token = SyntaxKind.LessThanSlashToken;
}
pos++;
return token = SyntaxKind.LessThanToken;
}
if (char === CharacterCodes.openBrace) {
pos++;
return token = SyntaxKind.OpenBraceToken;
}
while (pos < end) {
pos++;
char = text.charCodeAt(pos);
if ((char === CharacterCodes.openBrace) || (char === CharacterCodes.lessThan)) {
break;
}
}
return token = SyntaxKind.JsxText;
}
// Scans a JSX identifier; these differ from normal identifiers in that
// they allow dashes
function scanJsxIdentifier(): SyntaxKind {
if (token === SyntaxKind.Identifier) {
let firstCharPosition = pos;
while (pos < end) {
let ch = text.charCodeAt(pos);
if (ch === CharacterCodes.minus || ((firstCharPosition === pos) ? isIdentifierStart(ch) : isIdentifierPart(ch))) {
pos++;
}
else {
break;
}
}
tokenValue += text.substr(firstCharPosition, pos - firstCharPosition);
}
return token;
}
function speculationHelper<T>(callback: () => T, isLookahead: boolean): T {
let savePos = pos;
let saveStartPos = startPos;
@@ -1504,6 +1596,10 @@ namespace ts {
languageVersion = scriptTarget;
}
function setLanguageVariant(variant: LanguageVariant) {
languageVariant = variant;
}
function setTextPos(textPos: number) {
Debug.assert(textPos >= 0);
pos = textPos;
+2 -1
View File
@@ -191,7 +191,8 @@ namespace ts {
return sys.exit(ExitStatus.Success);
}
if (commandLine.options.watch) {
// Firefox has Object.prototype.watch
if (commandLine.options.watch && commandLine.options.hasOwnProperty("watch")) {
if (!sys.watchFile) {
reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch"));
return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped);
+101 -8
View File
@@ -48,6 +48,7 @@ namespace ts {
SemicolonToken,
CommaToken,
LessThanToken,
LessThanSlashToken,
GreaterThanToken,
LessThanEqualsToken,
GreaterThanEqualsToken,
@@ -220,6 +221,8 @@ namespace ts {
ClassExpression,
OmittedExpression,
ExpressionWithTypeArguments,
AsExpression,
// Misc
TemplateSpan,
SemicolonClassElement,
@@ -268,6 +271,16 @@ namespace ts {
// Module references
ExternalModuleReference,
//JSX
JsxElement,
JsxSelfClosingElement,
JsxOpeningElement,
JsxText,
JsxClosingElement,
JsxAttribute,
JsxSpreadAttribute,
JsxExpression,
// Clauses
CaseClause,
DefaultClause,
@@ -403,6 +416,17 @@ namespace ts {
HasAggregatedChildData = 1 << 7
}
export const enum JsxFlags {
None = 0,
IntrinsicNamedElement = 1 << 0,
IntrinsicIndexedElement = 1 << 1,
ClassElement = 1 << 2,
UnknownElement = 1 << 3,
IntrinsicElement = IntrinsicNamedElement | IntrinsicIndexedElement
}
/* @internal */
export const enum RelationComparisonResult {
Succeeded = 1, // Should be truthy
@@ -808,13 +832,66 @@ namespace ts {
template: LiteralExpression | TemplateExpression;
}
export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression;
export type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator;
export interface AsExpression extends Expression {
expression: Expression;
type: TypeNode;
}
export interface TypeAssertion extends UnaryExpression {
type: TypeNode;
expression: UnaryExpression;
}
export type AssertionExpression = TypeAssertion | AsExpression;
/// A JSX expression of the form <TagName attrs>...</TagName>
export interface JsxElement extends PrimaryExpression {
openingElement: JsxOpeningElement;
children: NodeArray<JsxChild>;
closingElement: JsxClosingElement;
}
/// The opening element of a <Tag>...</Tag> JsxElement
export interface JsxOpeningElement extends Expression {
_openingElementBrand?: any;
tagName: EntityName;
attributes: NodeArray<JsxAttribute | JsxSpreadAttribute>;
}
/// A JSX expression of the form <TagName attrs />
export interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement {
_selfClosingElementBrand?: any;
}
/// Either the opening tag in a <Tag>...</Tag> pair, or the lone <Tag /> in a self-closing form
export type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement;
export interface JsxAttribute extends Node {
name: Identifier;
/// JSX attribute initializers are optional; <X y /> is sugar for <X y={true} />
initializer?: Expression;
}
export interface JsxSpreadAttribute extends Node {
expression: Expression;
}
export interface JsxClosingElement extends Node {
tagName: EntityName;
}
export interface JsxExpression extends Expression {
expression?: Expression;
}
export interface JsxText extends Node {
_jsxTextExpressionBrand: any;
}
export type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement;
export interface Statement extends Node {
_statementBrand: any;
}
@@ -1155,6 +1232,7 @@ namespace ts {
amdDependencies: {path: string; name: string}[];
moduleName: string;
referencedFiles: FileReference[];
languageVariant: LanguageVariant;
/**
* lib.d.ts should have a reference comment like
@@ -1223,11 +1301,11 @@ namespace ts {
*/
emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback): EmitResult;
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getOptionsDiagnostics(): Diagnostic[];
getGlobalDiagnostics(): Diagnostic[];
getSyntacticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getSemanticDiagnostics(sourceFile?: SourceFile): Diagnostic[];
getDeclarationDiagnostics(sourceFile?: SourceFile): Diagnostic[];
/* @internal */ getCompilerOptionsDiagnostics(): Diagnostic[];
/**
* Gets a type checker that can be used to semantically analyze source fils in the program.
@@ -1334,6 +1412,9 @@ namespace ts {
getAliasedSymbol(symbol: Symbol): Symbol;
getExportsOfModule(moduleSymbol: Symbol): Symbol[];
getJsxElementAttributesType(elementNode: JsxOpeningLikeElement): Type;
getJsxIntrinsicTagNames(): Symbol[];
// Should not be called directly. Should only be accessed through the Program instance.
/* @internal */ getDiagnostics(sourceFile?: SourceFile): Diagnostic[];
/* @internal */ getGlobalDiagnostics(): Diagnostic[];
@@ -1619,6 +1700,8 @@ namespace ts {
assignmentChecks?: Map<boolean>; // Cache of assignment checks
hasReportedStatementInAmbientContext?: boolean; // Cache boolean if we report statements in ambient context
importOnRightSide?: Symbol; // for import declarations - import that appear on the right side
jsxFlags?: JsxFlags; // flags for knowning what kind of element/attributes we're dealing with
resolvedJsxType?: Type; // resolved element attributes type of a JSX openinglike element
}
export const enum TypeFlags {
@@ -1685,10 +1768,8 @@ namespace ts {
typeParameters: TypeParameter[]; // Type parameters (undefined if non-generic)
outerTypeParameters: TypeParameter[]; // Outer type parameters (undefined if none)
localTypeParameters: TypeParameter[]; // Local type parameters (undefined if none)
}
export interface InterfaceTypeWithBaseTypes extends InterfaceType {
baseTypes: ObjectType[];
resolvedBaseConstructorType?: Type; // Resolved base constructor type of class
resolvedBaseTypes: ObjectType[]; // Resolved base types
}
export interface InterfaceTypeWithDeclaredMembers extends InterfaceType {
@@ -1852,6 +1933,7 @@ namespace ts {
help?: boolean;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: JsxEmit;
listFiles?: boolean;
locale?: string;
mapRoot?: string;
@@ -1896,11 +1978,17 @@ namespace ts {
System = 4,
}
export const enum JsxEmit {
None = 0,
Preserve = 1,
React = 2
}
export const enum NewLineKind {
CarriageReturnLineFeed = 0,
LineFeed = 1,
}
export interface LineAndCharacter {
line: number;
/*
@@ -1916,6 +2004,11 @@ namespace ts {
Latest = ES6,
}
export const enum LanguageVariant {
Standard,
JSX
}
export interface ParsedCommandLine {
options: CompilerOptions;
fileNames: string[];
+58 -32
View File
@@ -42,7 +42,7 @@ namespace ts {
// Pool writers to avoid needing to allocate them for every symbol we write.
let stringWriters: StringSymbolWriter[] = [];
export function getSingleLineStringWriter(): StringSymbolWriter {
if (stringWriters.length == 0) {
if (stringWriters.length === 0) {
let str = "";
let writeText: (text: string) => void = text => str += text;
@@ -169,13 +169,13 @@ namespace ts {
return skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
}
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node): string {
export function getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia = false): string {
if (nodeIsMissing(node)) {
return "";
}
let text = sourceFile.text;
return text.substring(skipTrivia(text, node.pos), node.end);
return text.substring(includeTrivia ? node.pos : skipTrivia(text, node.pos), node.end);
}
export function getTextOfNodeFromSourceText(sourceText: string, node: Node): string {
@@ -186,8 +186,8 @@ namespace ts {
return sourceText.substring(skipTrivia(sourceText, node.pos), node.end);
}
export function getTextOfNode(node: Node): string {
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node);
export function getTextOfNode(node: Node, includeTrivia = false): string {
return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
}
// Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__'
@@ -274,7 +274,7 @@ namespace ts {
}
export function getSpanOfTokenAtPosition(sourceFile: SourceFile, pos: number): TextSpan {
let scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.text, /*onError:*/ undefined, pos);
let scanner = createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
scanner.scan();
let start = scanner.getTokenPos();
return createTextSpanFromBounds(start, scanner.getTextPos());
@@ -426,7 +426,7 @@ namespace ts {
// Specialized signatures can have string literals as their parameters' type names
return node.parent.kind === SyntaxKind.Parameter;
case SyntaxKind.ExpressionWithTypeArguments:
return true;
return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
// Identifiers and qualified names may be type nodes, depending on their context. Climb
// above them to find the lowest container
@@ -460,7 +460,7 @@ namespace ts {
}
switch (parent.kind) {
case SyntaxKind.ExpressionWithTypeArguments:
return true;
return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
case SyntaxKind.TypeParameter:
return node === (<TypeParameterDeclaration>parent).constraint;
case SyntaxKind.PropertyDeclaration:
@@ -542,6 +542,7 @@ namespace ts {
case SyntaxKind.ModuleDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
// These are not allowed inside a generator now, but eventually they may be allowed
// as local types. Regardless, any yield statements contained within them should be
// skipped in this traversal.
@@ -579,26 +580,15 @@ namespace ts {
return true;
}
}
return false;
}
export function isAccessor(node: Node): boolean {
if (node) {
switch (node.kind) {
case SyntaxKind.GetAccessor:
case SyntaxKind.SetAccessor:
return true;
}
}
return false;
return node && (node.kind === SyntaxKind.GetAccessor || node.kind === SyntaxKind.SetAccessor);
}
export function isClassLike(node: Node): boolean {
if (node) {
return node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression;
}
return node && (node.kind === SyntaxKind.ClassDeclaration || node.kind === SyntaxKind.ClassExpression);
}
export function isFunctionLike(node: Node): boolean {
@@ -620,7 +610,6 @@ namespace ts {
return true;
}
}
return false;
}
@@ -640,7 +629,16 @@ namespace ts {
}
}
}
export function getContainingClass(node: Node): ClassLikeDeclaration {
while (true) {
node = node.parent;
if (!node || isClassLike(node)) {
return <ClassLikeDeclaration>node;
}
}
}
export function getThisContainer(node: Node, includeArrowFunctions: boolean): Node {
while (true) {
node = node.parent;
@@ -653,7 +651,7 @@ namespace ts {
// then the computed property is not a 'this' container.
// A computed property name in a class needs to be a this container
// so that we can error on it.
if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
if (isClassLike(node.parent.parent)) {
return node;
}
// If this is a computed property, then the parent should not
@@ -708,7 +706,7 @@ namespace ts {
// then the computed property is not a 'super' container.
// A computed property name in a class needs to be a super container
// so that we can error on it.
if (node.parent.parent.kind === SyntaxKind.ClassDeclaration) {
if (isClassLike(node.parent.parent)) {
return node;
}
// If this is a computed property, then the parent should not
@@ -770,8 +768,8 @@ namespace ts {
return (<TaggedTemplateExpression>node).tag;
}
// Will either be a CallExpression or NewExpression.
return (<CallExpression>node).expression;
// Will either be a CallExpression, NewExpression, or Decorator.
return (<CallExpression | Decorator>node).expression;
}
export function nodeCanBeDecorated(node: Node): boolean {
@@ -866,6 +864,7 @@ namespace ts {
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.FunctionExpression:
@@ -882,13 +881,14 @@ namespace ts {
case SyntaxKind.TemplateExpression:
case SyntaxKind.NoSubstitutionTemplateLiteral:
case SyntaxKind.OmittedExpression:
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.YieldExpression:
return true;
case SyntaxKind.QualifiedName:
while (node.parent.kind === SyntaxKind.QualifiedName) {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeQuery;
case SyntaxKind.Identifier:
if (node.parent.kind === SyntaxKind.TypeQuery) {
@@ -929,13 +929,16 @@ namespace ts {
return (forInStatement.initializer === node && forInStatement.initializer.kind !== SyntaxKind.VariableDeclarationList) ||
forInStatement.expression === node;
case SyntaxKind.TypeAssertionExpression:
return node === (<TypeAssertion>parent).expression;
case SyntaxKind.AsExpression:
return node === (<AssertionExpression>parent).expression;
case SyntaxKind.TemplateSpan:
return node === (<TemplateSpan>parent).expression;
case SyntaxKind.ComputedPropertyName:
return node === (<ComputedPropertyName>parent).expression;
case SyntaxKind.Decorator:
return true;
case SyntaxKind.ExpressionWithTypeArguments:
return (<ExpressionWithTypeArguments>parent).expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
default:
if (isExpression(parent)) {
return true;
@@ -1082,7 +1085,7 @@ namespace ts {
return SyntaxKind.FirstTemplateToken <= kind && kind <= SyntaxKind.LastTemplateToken;
}
export function isBindingPattern(node: Node) {
export function isBindingPattern(node: Node): node is BindingPattern {
return !!node && (node.kind === SyntaxKind.ArrayBindingPattern || node.kind === SyntaxKind.ObjectBindingPattern);
}
@@ -1102,6 +1105,7 @@ namespace ts {
case SyntaxKind.ArrowFunction:
case SyntaxKind.BindingElement:
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.Constructor:
case SyntaxKind.EnumDeclaration:
case SyntaxKind.EnumMember:
@@ -1250,7 +1254,7 @@ namespace ts {
return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
}
export function getClassImplementsHeritageClauseElements(node: ClassDeclaration) {
export function getClassImplementsHeritageClauseElements(node: ClassLikeDeclaration) {
let heritageClause = getHeritageClause(node.heritageClauses, SyntaxKind.ImplementsKeyword);
return heritageClause ? heritageClause.types : undefined;
}
@@ -1551,6 +1555,11 @@ namespace ts {
}
}
export function isIntrinsicJsxName(name: string) {
let ch = name.substr(0, 1);
return ch.toLowerCase() === ch;
}
function get16BitUnicodeEscapeSequence(charCode: number): string {
let hexCharCode = charCode.toString(16).toUpperCase();
let paddedHexCode = ("0000" + hexCharCode).slice(-4);
@@ -1907,6 +1916,8 @@ namespace ts {
case SyntaxKind.ElementAccessExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.CallExpression:
case SyntaxKind.JsxElement:
case SyntaxKind.JsxSelfClosingElement:
case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.ParenthesizedExpression:
@@ -1935,6 +1946,12 @@ namespace ts {
return token >= SyntaxKind.FirstAssignment && token <= SyntaxKind.LastAssignment;
}
export function isExpressionWithTypeArgumentsInClassExtendsClause(node: Node): boolean {
return node.kind === SyntaxKind.ExpressionWithTypeArguments &&
(<HeritageClause>node.parent).token === SyntaxKind.ExtendsKeyword &&
isClassLike(node.parent.parent);
}
// Returns false if this heritage clause element's expression contains something unsupported
// (i.e. not a name or dotted name).
export function isSupportedExpressionWithTypeArguments(node: ExpressionWithTypeArguments): boolean {
@@ -1966,6 +1983,10 @@ namespace ts {
return fileExtensionIs(fileName, ".js");
}
export function isTsx(fileName: string) {
return fileExtensionIs(fileName, ".tsx");
}
/**
* Replace each instance of non-ascii characters by one, two, three, or four escape sequences
* representing the UTF-8 encoding of the character, and return the expanded char code list.
@@ -1973,7 +1994,6 @@ namespace ts {
function getExpandedCharCodes(input: string): number[] {
let output: number[] = [];
let length = input.length;
let leadSurrogate: number = undefined;
for (let i = 0; i < length; i++) {
let charCode = input.charCodeAt(i);
@@ -2105,6 +2125,12 @@ namespace ts {
return start <= textSpanEnd(span) && end >= span.start;
}
export function decodedTextSpanIntersectsWith(start1: number, length1: number, start2: number, length2: number) {
let end1 = start1 + length1;
let end2 = start2 + length2;
return start2 <= end1 && end2 >= start1;
}
export function textSpanIntersectsWithPosition(span: TextSpan, position: number) {
return position <= textSpanEnd(span) && position >= span.start;
}
+8 -8
View File
@@ -149,7 +149,7 @@ class CompilerBaselineRunner extends RunnerBase {
// check errors
it('Correct errors for ' + fileName, () => {
if (this.errors) {
Harness.Baseline.runBaseline('Correct errors for ' + fileName, justName.replace(/\.ts$/, '.errors.txt'), (): string => {
Harness.Baseline.runBaseline('Correct errors for ' + fileName, justName.replace(/\.tsx?$/, '.errors.txt'), (): string => {
if (result.errors.length === 0) return null;
return getErrorBaseline(toBeCompiled, otherFiles, result);
});
@@ -159,7 +159,7 @@ class CompilerBaselineRunner extends RunnerBase {
// Source maps?
it('Correct sourcemap content for ' + fileName, () => {
if (options.sourceMap || options.inlineSourceMap) {
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.ts$/, '.sourcemap.txt'), () => {
Harness.Baseline.runBaseline('Correct sourcemap content for ' + fileName, justName.replace(/\.tsx?$/, '.sourcemap.txt'), () => {
var record = result.getSourceMapRecord();
if (options.noEmitOnError && result.errors.length !== 0 && record === undefined) {
// Because of the noEmitOnError option no files are created. We need to return null because baselining isn't required.
@@ -177,7 +177,7 @@ class CompilerBaselineRunner extends RunnerBase {
}
// check js output
Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.ts/, '.js'), () => {
Harness.Baseline.runBaseline('Correct JS output for ' + fileName, justName.replace(/\.tsx?/, '.js'), () => {
var tsCode = '';
var tsSources = otherFiles.concat(toBeCompiled);
if (tsSources.length > 1) {
@@ -235,7 +235,7 @@ class CompilerBaselineRunner extends RunnerBase {
throw new Error('Number of sourcemap files should be same as js files.');
}
Harness.Baseline.runBaseline('Correct Sourcemap output for ' + fileName, justName.replace(/\.ts/, '.js.map'), () => {
Harness.Baseline.runBaseline('Correct Sourcemap output for ' + fileName, justName.replace(/\.tsx?/, '.js.map'), () => {
if (options.noEmitOnError && result.errors.length !== 0 && result.sourceMaps.length === 0) {
// We need to return null here or the runBaseLine will actually create a empty file.
// Baselining isn't required here because there is no output.
@@ -320,11 +320,11 @@ class CompilerBaselineRunner extends RunnerBase {
let pullExtension = isSymbolBaseLine ? '.symbols.pull' : '.types.pull';
if (fullBaseLine !== pullBaseLine) {
Harness.Baseline.runBaseline('Correct full information for ' + fileName, justName.replace(/\.ts/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct pull information for ' + fileName, justName.replace(/\.ts/, pullExtension), () => pullBaseLine);
Harness.Baseline.runBaseline('Correct full information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct pull information for ' + fileName, justName.replace(/\.tsx?/, pullExtension), () => pullBaseLine);
}
else {
Harness.Baseline.runBaseline('Correct information for ' + fileName, justName.replace(/\.ts/, fullExtension), () => fullBaseLine);
Harness.Baseline.runBaseline('Correct information for ' + fileName, justName.replace(/\.tsx?/, fullExtension), () => fullBaseLine);
}
}
@@ -391,7 +391,7 @@ class CompilerBaselineRunner extends RunnerBase {
// this will set up a series of describe/it blocks to run between the setup and cleanup phases
if (this.tests.length === 0) {
var testFiles = this.enumerateFiles(this.basePath, /\.ts$/, { recursive: true });
var testFiles = this.enumerateFiles(this.basePath, /\.tsx?$/, { recursive: true });
testFiles.forEach(fn => {
fn = fn.replace(/\\/g, "/");
this.checkTestCodeOutput(fn);
+18 -10
View File
@@ -660,8 +660,7 @@ module FourSlash {
}
errorMsg += "]\n";
Harness.IO.log(errorMsg);
this.raiseError("Member list is not empty at Caret");
this.raiseError("Member list is not empty at Caret: " + errorMsg);
}
}
@@ -744,7 +743,7 @@ module FourSlash {
var reference = references[i];
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 + '.');
this.raiseError('verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ' + reference.isWriteAccess + ', expected: ' + isWriteAccess + '.');
}
return;
}
@@ -831,6 +830,7 @@ module FourSlash {
if (expectedText !== undefined) {
assert.notEqual(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
}
// TODO: should be '==='?
if (expectedDocumentation != undefined) {
assert.notEqual(actualQuickInfoDocumentation, expectedDocumentation, this.messageAtLastKnownMarker("quick info doc comment"));
}
@@ -838,6 +838,7 @@ module FourSlash {
if (expectedText !== undefined) {
assert.equal(actualQuickInfoText, expectedText, this.messageAtLastKnownMarker("quick info text"));
}
// TODO: should be '==='?
if (expectedDocumentation != undefined) {
assert.equal(actualQuickInfoDocumentation, expectedDocumentation, assertionMessage("quick info doc"));
}
@@ -883,8 +884,16 @@ module FourSlash {
this.activeFile.fileName, this.currentCaretPosition, findInStrings, findInComments);
var ranges = this.getRanges();
if (!references) {
if (ranges.length !== 0) {
this.raiseError(`Expected ${ranges.length} rename locations; got none.`);
}
return;
}
if (ranges.length !== references.length) {
this.raiseError(this.assertionMessage("Rename locations", references.length, ranges.length));
this.raiseError("Rename location count does not match result.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
}
ranges = ranges.sort((r1, r2) => r1.start - r2.start);
@@ -897,9 +906,7 @@ module FourSlash {
if (reference.textSpan.start !== range.start ||
ts.textSpanEnd(reference.textSpan) !== range.end) {
this.raiseError(this.assertionMessage("Rename location",
"[" + reference.textSpan.start + "," + ts.textSpanEnd(reference.textSpan) + ")",
"[" + range.start + "," + range.end + ")"));
this.raiseError("Rename location results do not match.\n\nExpected: " + JSON.stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
}
}
}
@@ -1820,7 +1827,7 @@ module FourSlash {
}
private verifyProjectInfo(expected: string[]) {
if (this.testType == FourSlashTestType.Server) {
if (this.testType === FourSlashTestType.Server) {
let actual = (<ts.server.SessionClient>this.languageService).getProjectInfo(
this.activeFile.fileName,
/* needFileNameList */ true
@@ -1937,7 +1944,7 @@ module FourSlash {
}
}
if (expected != actual) {
if (expected !== actual) {
this.raiseError('verifyNavigationItemsCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.');
}
}
@@ -1984,7 +1991,7 @@ module FourSlash {
var items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
var actual = this.getNavigationBarItemsCount(items);
if (expected != actual) {
if (expected !== actual) {
this.raiseError('verifyGetScriptLexicalStructureListCount failed - found: ' + actual + ' navigation items, expected: ' + expected + '.');
}
}
@@ -2402,6 +2409,7 @@ module FourSlash {
globalOptions[match[1]] = match[2];
}
}
// TODO: should be '==='?
} else if (line == '' || lineLength === 0) {
// Previously blank lines between fourslash content caused it to be considered as 2 files,
// Remove this behavior since it just causes errors now
+33 -7
View File
@@ -212,7 +212,7 @@ module Utils {
}
var result = "";
ts.forEach(Object.getOwnPropertyNames(flags),(v: any) => {
ts.forEach(Object.getOwnPropertyNames(flags), (v: any) => {
if (isFinite(v)) {
v = +v;
if (f === +v) {
@@ -410,7 +410,7 @@ module Harness {
deleteFile(fileName: string): void;
listFiles(path: string, filter: RegExp, options?: { recursive?: boolean }): string[];
log(text: string): void;
getMemoryUsage? (): number;
getMemoryUsage?(): number;
}
module IOImpl {
@@ -794,7 +794,7 @@ module Harness {
public reset() { this.fileCollection = {}; }
public toArray(): { fileName: string; file: WriterAggregator; }[]{
public toArray(): { fileName: string; file: WriterAggregator; }[] {
var result: { fileName: string; file: WriterAggregator; }[] = [];
for (var p in this.fileCollection) {
if (this.fileCollection.hasOwnProperty(p)) {
@@ -1170,6 +1170,12 @@ module Harness {
options.inlineSources = setting.value === 'true';
break;
case 'jsx':
options.jsx = setting.value.toLowerCase() === 'react' ? ts.JsxEmit.React :
setting.value.toLowerCase() === 'preserve' ? ts.JsxEmit.Preserve :
ts.JsxEmit.None;
break;
default:
throw new Error('Unsupported compiler setting ' + setting.flag);
}
@@ -1233,7 +1239,7 @@ module Harness {
}
var dTsFileName = ts.removeFileExtension(sourceFileName) + ".d.ts";
return ts.forEach(result.declFilesCode, declFile => declFile.fileName === dTsFileName ? declFile : undefined);
}
@@ -1432,6 +1438,10 @@ module Harness {
return stringEndsWith(fileName, '.ts');
}
export function isTSX(fileName: string) {
return stringEndsWith(fileName, '.tsx');
}
export function isDTS(fileName: string) {
return stringEndsWith(fileName, '.d.ts');
}
@@ -1439,6 +1449,9 @@ module Harness {
export function isJS(fileName: string) {
return stringEndsWith(fileName, '.js');
}
export function isJSX(fileName: string) {
return stringEndsWith(fileName, '.jsx');
}
export function isJSMap(fileName: string) {
return stringEndsWith(fileName, '.js.map');
@@ -1459,12 +1472,15 @@ module Harness {
if (isDTS(emittedFile.fileName)) {
// .d.ts file, add to declFiles emit
this.declFilesCode.push(emittedFile);
} else if (isJS(emittedFile.fileName)) {
}
else if (isJS(emittedFile.fileName) || isJSX(emittedFile.fileName)) {
// .js file, add to files
this.files.push(emittedFile);
} else if (isJSMap(emittedFile.fileName)) {
}
else if (isJSMap(emittedFile.fileName)) {
this.sourceMaps.push(emittedFile);
} else {
}
else {
throw new Error('Unrecognized file extension for file ' + emittedFile.fileName);
}
});
@@ -1499,6 +1515,16 @@ module Harness {
// Regex for parsing options in the format "@Alpha: Value of any sort"
var optionRegex = /^[\/]{2}\s*@(\w+)\s*:\s*(\S*)/gm; // multiple matches on multiple lines
// List of allowed metadata names
var fileMetadataNames = ["filename", "comments", "declaration", "module",
"nolib", "sourcemap", "target", "out", "outdir", "noemithelpers", "noemitonerror",
"noimplicitany", "noresolve", "newline", "normalizenewline", "emitbom",
"errortruncation", "usecasesensitivefilenames", "preserveconstenums",
"includebuiltfile", "suppressimplicitanyindexerrors", "stripinternal",
"isolatedmodules", "inlinesourcemap", "maproot", "sourceroot",
"inlinesources", "emitdecoratormetadata", "experimentaldecorators",
"skipdefaultlibcheck", "jsx"];
function extractCompilerSettings(content: string): CompilerSetting[] {
var opts: CompilerSetting[] = [];
+1 -1
View File
@@ -583,7 +583,7 @@ module Harness.LanguageService {
// This host is just a proxy for the clientHost, it uses the client
// host to answer server queries about files on disk
var serverHost = new SessionServerHost(clientHost);
var server = new ts.server.Session(serverHost, serverHost);
var server = new ts.server.Session(serverHost, Buffer.byteLength, process.hrtime, serverHost);
// Fake the connection between the client and the server
serverHost.writeMessage = client.onMessage.bind(client);
+2 -1
View File
@@ -110,6 +110,7 @@ class ProjectRunner extends RunnerBase {
else if (url.indexOf(diskProjectPath) === 0) {
// Replace the disk specific path into the project root path
url = url.substr(diskProjectPath.length);
// TODO: should be '!=='?
if (url.charCodeAt(0) != ts.CharacterCodes.slash) {
url = "/" + url;
}
@@ -240,7 +241,7 @@ class ProjectRunner extends RunnerBase {
if (Harness.Compiler.isJS(fileName)) {
// Make sure if there is URl we have it cleaned up
var indexOfSourceMapUrl = data.lastIndexOf("//# sourceMappingURL=");
if (indexOfSourceMapUrl != -1) {
if (indexOfSourceMapUrl !== -1) {
data = data.substring(0, indexOfSourceMapUrl + 21) + cleanProjectUrl(data.substring(indexOfSourceMapUrl + 21));
}
}
+1 -1
View File
@@ -27,7 +27,7 @@ class RunnerBase {
var fixedPath = path;
// full paths either start with a drive letter or / for *nix, shouldn't have \ in the path at this point
var fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.ts/g;
var fullPath = /(\w+:|\/)?([\w+\-\.]|\/)*\.tsx?/g;
var fullPathList = fixedPath.match(fullPath);
if (fullPathList) {
fullPathList.forEach((match: string) => fixedPath = fixedPath.replace(match, Harness.Path.getFileName(match)));
+15 -15
View File
@@ -46,7 +46,7 @@ module Harness.SourceMapRecoder {
}
function isSourceMappingSegmentEnd() {
if (decodingIndex == sourceMapMappings.length) {
if (decodingIndex === sourceMapMappings.length) {
return true;
}
@@ -95,7 +95,7 @@ module Harness.SourceMapRecoder {
var currentByte = base64FormatDecode();
// If msb is set, we still have more bits to continue
moreDigits = (currentByte & 32) != 0;
moreDigits = (currentByte & 32) !== 0;
// least significant 5 bits are the next msbs in the final value.
value = value | ((currentByte & 31) << shiftCount);
@@ -103,7 +103,7 @@ module Harness.SourceMapRecoder {
}
// Least significant bit if 1 represents negative and rest of the msb is actual absolute value
if ((value & 1) == 0) {
if ((value & 1) === 0) {
// + number
value = value >> 1;
}
@@ -182,7 +182,7 @@ module Harness.SourceMapRecoder {
}
}
// Dont support reading mappings that dont have information about original source and its line numbers
if (createErrorIfCondition(!isSourceMappingSegmentEnd(), "Unsupported Error Format: There are more entries after " + (decodeOfEncodedMapping.nameIndex == -1 ? "sourceColumn" : "nameIndex"))) {
if (createErrorIfCondition(!isSourceMappingSegmentEnd(), "Unsupported Error Format: There are more entries after " + (decodeOfEncodedMapping.nameIndex === -1 ? "sourceColumn" : "nameIndex"))) {
return { error: errorDecodeOfEncodedMapping, sourceMapSpan: decodeOfEncodedMapping };
}
@@ -249,7 +249,7 @@ module Harness.SourceMapRecoder {
mapString += " name (" + sourceMapNames[mapEntry.nameIndex] + ")";
}
else {
if (mapEntry.nameIndex != -1 || getAbsentNameIndex) {
if (mapEntry.nameIndex !== -1 || getAbsentNameIndex) {
mapString += " nameIndex (" + mapEntry.nameIndex + ")";
}
}
@@ -262,12 +262,12 @@ module Harness.SourceMapRecoder {
var decodeResult = SourceMapDecoder.decodeNextEncodedSourceMapSpan();
var decodedErrors: string[];
if (decodeResult.error
|| decodeResult.sourceMapSpan.emittedLine != sourceMapSpan.emittedLine
|| decodeResult.sourceMapSpan.emittedColumn != sourceMapSpan.emittedColumn
|| decodeResult.sourceMapSpan.sourceLine != sourceMapSpan.sourceLine
|| decodeResult.sourceMapSpan.sourceColumn != sourceMapSpan.sourceColumn
|| decodeResult.sourceMapSpan.sourceIndex != sourceMapSpan.sourceIndex
|| decodeResult.sourceMapSpan.nameIndex != sourceMapSpan.nameIndex) {
|| decodeResult.sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine
|| decodeResult.sourceMapSpan.emittedColumn !== sourceMapSpan.emittedColumn
|| decodeResult.sourceMapSpan.sourceLine !== sourceMapSpan.sourceLine
|| decodeResult.sourceMapSpan.sourceColumn !== sourceMapSpan.sourceColumn
|| decodeResult.sourceMapSpan.sourceIndex !== sourceMapSpan.sourceIndex
|| decodeResult.sourceMapSpan.nameIndex !== sourceMapSpan.nameIndex) {
if (decodeResult.error) {
decodedErrors = ["!!^^ !!^^ There was decoding error in the sourcemap at this location: " + decodeResult.error];
}
@@ -288,7 +288,7 @@ module Harness.SourceMapRecoder {
}
export function recordNewSourceFileSpan(sourceMapSpan: ts.SourceMapSpan, newSourceFileCode: string) {
assert.isTrue(spansOnSingleLine.length == 0 || spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine, "new file source map span should be on new line. We currently handle only that scenario");
assert.isTrue(spansOnSingleLine.length === 0 || spansOnSingleLine[0].sourceMapSpan.emittedLine !== sourceMapSpan.emittedLine, "new file source map span should be on new line. We currently handle only that scenario");
recordSourceMapSpan(sourceMapSpan);
assert.isTrue(spansOnSingleLine.length === 1);
@@ -395,9 +395,9 @@ module Harness.SourceMapRecoder {
var tsCodeLineMap = ts.computeLineStarts(sourceText);
for (var i = 0; i < tsCodeLineMap.length; i++) {
writeSourceMapIndent(prevEmittedCol, i == 0 ? markerIds[index] : " >");
writeSourceMapIndent(prevEmittedCol, i === 0 ? markerIds[index] : " >");
sourceMapRecoder.Write(getTextOfLine(i, tsCodeLineMap, sourceText));
if (i == tsCodeLineMap.length - 1) {
if (i === tsCodeLineMap.length - 1) {
sourceMapRecoder.WriteLine("");
}
}
@@ -447,7 +447,7 @@ module Harness.SourceMapRecoder {
for (var j = 0; j < sourceMapData.sourceMapDecodedMappings.length; j++) {
var decodedSourceMapping = sourceMapData.sourceMapDecodedMappings[j];
var currentSourceFile = program.getSourceFile(sourceMapData.inputSourceFileNames[decodedSourceMapping.sourceIndex]);
if (currentSourceFile != prevSourceFile) {
if (currentSourceFile !== prevSourceFile) {
SourceMapSpanWriter.recordNewSourceFileSpan(decodedSourceMapping, currentSourceFile.text);
prevSourceFile = currentSourceFile;
}
+4 -1
View File
@@ -41,7 +41,10 @@ class TypeWriterWalker {
var lineAndCharacter = this.currentSourceFile.getLineAndCharacterOfPosition(actualPos);
var sourceText = ts.getTextOfNodeFromSourceText(this.currentSourceFile.text, node);
var type = this.checker.getTypeAtLocation(node);
// Workaround to ensure we output 'C' instead of 'typeof C' for base class expressions
// var type = this.checker.getTypeAtLocation(node);
var type = node.parent && ts.isExpressionWithTypeArgumentsInClassExtendsClause(node.parent) && this.checker.getTypeAtLocation(node.parent) || this.checker.getTypeAtLocation(node);
ts.Debug.assert(type !== undefined, "type doesn't exist");
var symbol = this.checker.getSymbolAtLocation(node);
+4
View File
@@ -694,6 +694,7 @@ interface Map<K, V> {
}
interface MapConstructor {
new (): Map<any, any>;
new <K, V>(): Map<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): Map<K, V>;
prototype: Map<any, any>;
@@ -710,6 +711,7 @@ interface WeakMap<K, V> {
}
interface WeakMapConstructor {
new (): WeakMap<any, any>;
new <K, V>(): WeakMap<K, V>;
new <K, V>(iterable: Iterable<[K, V]>): WeakMap<K, V>;
prototype: WeakMap<any, any>;
@@ -731,6 +733,7 @@ interface Set<T> {
}
interface SetConstructor {
new (): Set<any>;
new <T>(): Set<T>;
new <T>(iterable: Iterable<T>): Set<T>;
prototype: Set<any>;
@@ -746,6 +749,7 @@ interface WeakSet<T> {
}
interface WeakSetConstructor {
new (): WeakSet<any>;
new <T>(): WeakSet<T>;
new <T>(iterable: Iterable<T>): WeakSet<T>;
prototype: WeakSet<any>;
+6 -1
View File
@@ -41,6 +41,11 @@ declare module Intl {
currency?: string;
currencyDisplay?: string;
useGrouping?: boolean;
minimumintegerDigits?: number;
minimumFractionDigits?: number;
maximumFractionDigits?: number;
minimumSignificantDigits?: number;
maximumSignificantDigits?: number;
}
interface ResolvedNumberFormatOptions {
@@ -103,7 +108,7 @@ declare module Intl {
}
interface DateTimeFormat {
format(date: number): string;
format(date?: Date | number): string;
resolvedOptions(): ResolvedDateTimeFormatOptions;
}
var DateTimeFormat: {
+3 -3
View File
@@ -219,7 +219,7 @@ namespace ts.server {
var request = this.processRequest<protocol.CompletionDetailsRequest>(CommandNames.CompletionDetails, args);
var response = this.processResponse<protocol.CompletionDetailsResponse>(request);
Debug.assert(response.body.length == 1, "Unexpected length of completion details response body.");
Debug.assert(response.body.length === 1, "Unexpected length of completion details response body.");
return response.body[0];
}
@@ -429,8 +429,8 @@ namespace ts.server {
if (!this.lastRenameEntry ||
this.lastRenameEntry.fileName !== fileName ||
this.lastRenameEntry.position !== position ||
this.lastRenameEntry.findInStrings != findInStrings ||
this.lastRenameEntry.findInComments != findInComments) {
this.lastRenameEntry.findInStrings !== findInStrings ||
this.lastRenameEntry.findInComments !== findInComments) {
this.getRenameInfo(fileName, position, findInStrings, findInComments);
}
+43 -42
View File
@@ -2,7 +2,6 @@
/// <reference path="..\services\services.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="session.ts" />
/// <reference path="node.d.ts" />
namespace ts.server {
export interface Logger {
@@ -28,7 +27,7 @@ namespace ts.server {
});
}
class ScriptInfo {
export class ScriptInfo {
svc: ScriptVersionCache;
children: ScriptInfo[] = []; // files referenced by this file
defaultProject: Project; // project to use by default for file
@@ -36,7 +35,7 @@ namespace ts.server {
formatCodeOptions = ts.clone(CompilerService.defaultFormatCodeOptions);
constructor(private host: ServerHost, public fileName: string, public content: string, public isOpen = false) {
this.svc = ScriptVersionCache.fromString(content);
this.svc = ScriptVersionCache.fromString(host, content);
}
setFormatOptions(formatOptions: protocol.FormatOptions): void {
@@ -80,7 +79,7 @@ namespace ts.server {
}
}
class LSHost implements ts.LanguageServiceHost {
export class LSHost implements ts.LanguageServiceHost {
ls: ts.LanguageService = null;
compilationSettings: ts.CompilerOptions;
filenameToScript: ts.Map<ScriptInfo> = {};
@@ -273,7 +272,7 @@ namespace ts.server {
}
}
interface ProjectOptions {
export interface ProjectOptions {
// these fields can be present in the project file
files?: string[];
compilerOptions?: ts.CompilerOptions;
@@ -376,7 +375,7 @@ namespace ts.server {
}
}
interface ProjectOpenResult {
export interface ProjectOpenResult {
success?: boolean;
errorMsg?: string;
project?: Project;
@@ -392,11 +391,11 @@ namespace ts.server {
return copiedList;
}
interface ProjectServiceEventHandler {
export interface ProjectServiceEventHandler {
(eventName: string, project: Project, fileName: string): void;
}
interface HostConfiguration {
export interface HostConfiguration {
formatCodeOptions: ts.FormatCodeOptions;
hostInfo: string;
}
@@ -629,7 +628,7 @@ namespace ts.server {
for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) {
var f = this.openFilesReferenced[i];
// if f was referenced by the removed project, remember it
if (f.defaultProject == removedProject) {
if (f.defaultProject === removedProject) {
f.defaultProject = undefined;
orphanFiles.push(f);
}
@@ -656,7 +655,7 @@ namespace ts.server {
for (var i = 0, len = this.inferredProjects.length; i < len; i++) {
var inferredProject = this.inferredProjects[i];
inferredProject.updateGraph();
if (inferredProject != excludedProject) {
if (inferredProject !== excludedProject) {
if (inferredProject.getSourceFile(info)) {
info.defaultProject = inferredProject;
referencingProjects.push(inferredProject);
@@ -710,7 +709,7 @@ namespace ts.server {
var rootFile = this.openFileRoots[i];
var rootedProject = rootFile.defaultProject;
var referencingProjects = this.findReferencingProjects(rootFile, rootedProject);
if (referencingProjects.length == 0) {
if (referencingProjects.length === 0) {
rootFile.defaultProject = rootedProject;
openFileRoots.push(rootFile);
}
@@ -916,7 +915,7 @@ namespace ts.server {
return rawConfig.error;
}
else {
var parsedCommandLine = ts.parseConfigFile(rawConfig.config, ts.sys, dirPath);
var parsedCommandLine = ts.parseConfigFile(rawConfig.config, this.host, dirPath);
if (parsedCommandLine.errors && (parsedCommandLine.errors.length > 0)) {
return { errorMsg: "tsconfig option errors" };
}
@@ -953,7 +952,7 @@ namespace ts.server {
}
class CompilerService {
export class CompilerService {
host: LSHost;
languageService: ts.LanguageService;
classifier: ts.Classifier;
@@ -985,7 +984,7 @@ namespace ts.server {
static defaultFormatCodeOptions: ts.FormatCodeOptions = {
IndentSize: 4,
TabSize: 4,
NewLineCharacter: ts.sys.newLine,
NewLineCharacter: ts.sys ? ts.sys.newLine : '\n',
ConvertTabsToSpaces: true,
InsertSpaceAfterCommaDelimiter: true,
InsertSpaceAfterSemicolonInForStatements: true,
@@ -999,7 +998,7 @@ namespace ts.server {
}
interface LineCollection {
export interface LineCollection {
charCount(): number;
lineCount(): number;
isLeaf(): boolean;
@@ -1013,7 +1012,7 @@ namespace ts.server {
leaf?: LineLeaf;
}
enum CharRangeSection {
export enum CharRangeSection {
PreStart,
Start,
Entire,
@@ -1022,7 +1021,7 @@ namespace ts.server {
PostEnd
}
interface ILineIndexWalker {
export interface ILineIndexWalker {
goSubtree: boolean;
done: boolean;
leaf(relativeStart: number, relativeLength: number, lineCollection: LineLeaf): void;
@@ -1082,7 +1081,7 @@ namespace ts.server {
for (var k = this.endBranch.length - 1; k >= 0; k--) {
(<LineNode>this.endBranch[k]).updateCounts();
if (this.endBranch[k].charCount() == 0) {
if (this.endBranch[k].charCount() === 0) {
lastZeroCount = this.endBranch[k];
if (k > 0) {
branchParent = <LineNode>this.endBranch[k - 1];
@@ -1147,7 +1146,7 @@ namespace ts.server {
post(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection): LineCollection {
// have visited the path for start of range, now looking for end
// if range is on single line, we will never make this state transition
if (lineCollection == this.lineCollectionAtBranch) {
if (lineCollection === this.lineCollectionAtBranch) {
this.state = CharRangeSection.End;
}
// always pop stack because post only called when child has been visited
@@ -1159,7 +1158,7 @@ namespace ts.server {
// currentNode corresponds to parent, but in the new tree
var currentNode = this.stack[this.stack.length - 1];
if ((this.state == CharRangeSection.Entire) && (nodeType == CharRangeSection.Start)) {
if ((this.state === CharRangeSection.Entire) && (nodeType === CharRangeSection.Start)) {
// if range is on single line, we will never make this state transition
this.state = CharRangeSection.Start;
this.branchNode = currentNode;
@@ -1176,12 +1175,12 @@ namespace ts.server {
switch (nodeType) {
case CharRangeSection.PreStart:
this.goSubtree = false;
if (this.state != CharRangeSection.End) {
if (this.state !== CharRangeSection.End) {
currentNode.add(lineCollection);
}
break;
case CharRangeSection.Start:
if (this.state == CharRangeSection.End) {
if (this.state === CharRangeSection.End) {
this.goSubtree = false;
}
else {
@@ -1191,7 +1190,7 @@ namespace ts.server {
}
break;
case CharRangeSection.Entire:
if (this.state != CharRangeSection.End) {
if (this.state !== CharRangeSection.End) {
child = fresh(lineCollection);
currentNode.add(child);
this.startPath[this.startPath.length] = child;
@@ -1208,7 +1207,7 @@ namespace ts.server {
this.goSubtree = false;
break;
case CharRangeSection.End:
if (this.state != CharRangeSection.End) {
if (this.state !== CharRangeSection.End) {
this.goSubtree = false;
}
else {
@@ -1221,7 +1220,7 @@ namespace ts.server {
break;
case CharRangeSection.PostEnd:
this.goSubtree = false;
if (this.state != CharRangeSection.Start) {
if (this.state !== CharRangeSection.Start) {
currentNode.add(lineCollection);
}
break;
@@ -1233,10 +1232,10 @@ namespace ts.server {
}
// just gather text from the leaves
leaf(relativeStart: number, relativeLength: number, ll: LineLeaf) {
if (this.state == CharRangeSection.Start) {
if (this.state === CharRangeSection.Start) {
this.initialText = ll.text.substring(0, relativeStart);
}
else if (this.state == CharRangeSection.Entire) {
else if (this.state === CharRangeSection.Entire) {
this.initialText = ll.text.substring(0, relativeStart);
this.trailingText = ll.text.substring(relativeStart + relativeLength);
}
@@ -1248,7 +1247,7 @@ namespace ts.server {
}
// text change information
class TextChange {
export class TextChange {
constructor(public pos: number, public deleteLen: number, public insertedText?: string) {
}
@@ -1263,6 +1262,7 @@ namespace ts.server {
versions: LineIndexSnapshot[] = [];
minVersion = 0; // no versions earlier than min version will maintain change history
private currentVersion = 0;
private host: ServerHost;
static changeNumberThreshold = 8;
static changeLengthThreshold = 256;
@@ -1290,7 +1290,7 @@ namespace ts.server {
}
reloadFromFile(filename: string, cb?: () => any) {
var content = ts.sys.readFile(filename);
var content = this.host.readFile(filename);
this.reload(content);
if (cb)
cb();
@@ -1360,10 +1360,11 @@ namespace ts.server {
}
}
static fromString(script: string) {
static fromString(host: ServerHost, script: string) {
var svc = new ScriptVersionCache();
var snap = new LineIndexSnapshot(0, svc);
svc.versions[svc.currentVersion] = snap;
svc.host = host;
snap.index = new LineIndex();
var lm = LineIndex.linesFromText(script);
snap.index.load(lm.lines);
@@ -1371,7 +1372,7 @@ namespace ts.server {
}
}
class LineIndexSnapshot implements ts.IScriptSnapshot {
export class LineIndexSnapshot implements ts.IScriptSnapshot {
index: LineIndex;
changesSincePreviousVersion: TextChange[] = [];
@@ -1499,8 +1500,8 @@ namespace ts.server {
function editFlat(source: string, s: number, dl: number, nt = "") {
return source.substring(0, s) + nt + source.substring(s + dl, source.length);
}
if (this.root.charCount() == 0) {
// TODO: assert deleteLength == 0
if (this.root.charCount() === 0) {
// TODO: assert deleteLength === 0
if (newText) {
this.load(LineIndex.linesFromText(newText).lines);
return this;
@@ -1528,7 +1529,7 @@ namespace ts.server {
// check whether last characters deleted are line break
var e = pos + deleteLength;
var lineInfo = this.charOffsetToLineNumberAndPos(e);
if ((lineInfo && (lineInfo.offset == 0))) {
if ((lineInfo && (lineInfo.offset === 0))) {
// move range end just past line that will merge with previous line
deleteLength += lineInfo.text.length;
// store text by appending to end of insertedText
@@ -1574,7 +1575,7 @@ namespace ts.server {
interiorNodes[i].totalChars = charCount;
interiorNodes[i].totalLines = lineCount;
}
if (interiorNodes.length == 1) {
if (interiorNodes.length === 1) {
return interiorNodes[0];
}
else {
@@ -1585,7 +1586,7 @@ namespace ts.server {
static linesFromText(text: string) {
var lineStarts = ts.computeLineStarts(text);
if (lineStarts.length == 0) {
if (lineStarts.length === 0) {
return { lines: <string[]>[], lineMap: lineStarts };
}
var lines = <string[]>new Array(lineStarts.length);
@@ -1605,7 +1606,7 @@ namespace ts.server {
}
}
class LineNode implements LineCollection {
export class LineNode implements LineCollection {
totalChars = 0;
totalLines = 0;
children: LineCollection[] = [];
@@ -1821,7 +1822,7 @@ namespace ts.server {
findChildIndex(child: LineCollection) {
var childIndex = 0;
var clen = this.children.length;
while ((this.children[childIndex] != child) && (childIndex < clen)) childIndex++;
while ((this.children[childIndex] !== child) && (childIndex < clen)) childIndex++;
return childIndex;
}
@@ -1830,7 +1831,7 @@ namespace ts.server {
var clen = this.children.length;
var nodeCount = nodes.length;
// if child is last and there is more room and only one node to place, place it
if ((clen < lineCollectionCapacity) && (childIndex == (clen - 1)) && (nodeCount == 1)) {
if ((clen < lineCollectionCapacity) && (childIndex === (clen - 1)) && (nodeCount === 1)) {
this.add(nodes[0]);
this.updateCounts();
return [];
@@ -1854,13 +1855,13 @@ namespace ts.server {
var splitNode = <LineNode>splitNodes[0];
while (nodeIndex < nodeCount) {
splitNode.add(nodes[nodeIndex++]);
if (splitNode.children.length == lineCollectionCapacity) {
if (splitNode.children.length === lineCollectionCapacity) {
splitNodeIndex++;
splitNode = <LineNode>splitNodes[splitNodeIndex];
}
}
for (i = splitNodes.length - 1; i >= 0; i--) {
if (splitNodes[i].children.length == 0) {
if (splitNodes[i].children.length === 0) {
splitNodes.length--;
}
}
@@ -1891,7 +1892,7 @@ namespace ts.server {
}
}
class LineLeaf implements LineCollection {
export class LineLeaf implements LineCollection {
udata: any;
constructor(public text: string) {
+2 -2
View File
@@ -584,9 +584,9 @@ declare module NodeJS {
export interface Response extends Message {
request_seq: number;
success: boolean;
/** Contains error message if success == false. */
/** Contains error message if success === false. */
message?: string;
/** Contains message body if success == true. */
/** Contains message body if success === true. */
body?: any;
}
+2 -2
View File
@@ -67,12 +67,12 @@ declare namespace ts.server.protocol {
command: string;
/**
* Contains error message if success == false.
* Contains error message if success === false.
*/
message?: string;
/**
* Contains message body if success == true.
* Contains message body if success === true.
*/
body?: any;
}
+5 -5
View File
@@ -11,7 +11,7 @@ namespace ts.server {
input: process.stdin,
output: process.stdout,
terminal: false,
});
});
class Logger implements ts.server.Logger {
fd = -1;
@@ -123,7 +123,7 @@ namespace ts.server {
if (err) {
watchedFile.callback(watchedFile.fileName);
}
else if (watchedFile.mtime.getTime() != stats.mtime.getTime()) {
else if (watchedFile.mtime.getTime() !== stats.mtime.getTime()) {
watchedFile.mtime = WatchedFileSet.getModifiedTime(watchedFile.fileName);
watchedFile.callback(watchedFile.fileName);
}
@@ -138,7 +138,7 @@ namespace ts.server {
var count = 0;
var nextToCheck = this.nextFileToCheck;
var firstCheck = -1;
while ((count < this.chunkSize) && (nextToCheck != firstCheck)) {
while ((count < this.chunkSize) && (nextToCheck !== firstCheck)) {
this.poll(nextToCheck);
if (firstCheck < 0) {
firstCheck = nextToCheck;
@@ -170,11 +170,11 @@ namespace ts.server {
removeFile(file: WatchedFile) {
this.watchedFiles = WatchedFileSet.copyListRemovingItem(file, this.watchedFiles);
}
}
}
class IOSession extends Session {
constructor(host: ServerHost, logger: ts.server.Logger) {
super(host, logger);
super(host, Buffer.byteLength, process.hrtime, logger);
}
exit() {
+20 -16
View File
@@ -1,6 +1,5 @@
/// <reference path="..\compiler\commandLineParser.ts" />
/// <reference path="..\services\services.ts" />
/// <reference path="node.d.ts" />
/// <reference path="protocol.d.ts" />
/// <reference path="editorServices.ts" />
@@ -31,7 +30,7 @@ namespace ts.server {
if (a < b) {
return -1;
}
else if (a == b) {
else if (a === b) {
return 0;
}
else return 1;
@@ -43,7 +42,7 @@ namespace ts.server {
}
else if (a.file == b.file) {
var n = compareNumber(a.start.line, b.start.line);
if (n == 0) {
if (n === 0) {
return compareNumber(a.start.offset, b.start.offset);
}
else return n;
@@ -61,7 +60,7 @@ namespace ts.server {
};
}
interface PendingErrorCheck {
export interface PendingErrorCheck {
fileName: string;
project: Project;
}
@@ -114,11 +113,16 @@ namespace ts.server {
pendingOperation = false;
fileHash: ts.Map<number> = {};
nextFileId = 1;
errorTimer: NodeJS.Timer;
errorTimer: any; /*NodeJS.Timer | number*/
immediateId: any;
changeSeq = 0;
constructor(private host: ServerHost, private logger: Logger) {
constructor(
private host: ServerHost,
private byteLength: (buf: string, encoding?: string) => number,
private hrtime: (start?: number[]) => number[],
private logger: Logger
) {
this.projectService =
new ProjectService(host, logger, (eventName,project,fileName) => {
this.handleEvent(eventName, project, fileName);
@@ -129,7 +133,7 @@ namespace ts.server {
if (eventName == "context") {
this.projectService.log("got context event, updating diagnostics for" + fileName, "Info");
this.updateErrorCheck([{ fileName, project }], this.changeSeq,
(n) => n == this.changeSeq, 100);
(n) => n === this.changeSeq, 100);
}
}
@@ -149,17 +153,17 @@ namespace ts.server {
this.host.write(line + this.host.newLine);
}
send(msg: NodeJS._debugger.Message) {
send(msg: protocol.Message) {
var json = JSON.stringify(msg);
if (this.logger.isVerbose()) {
this.logger.info(msg.type + ": " + json);
}
this.sendLineToClient('Content-Length: ' + (1 + Buffer.byteLength(json, 'utf8')) +
this.sendLineToClient('Content-Length: ' + (1 + this.byteLength(json, 'utf8')) +
'\r\n\r\n' + json);
}
event(info: any, eventName: string) {
var ev: NodeJS._debugger.Event = {
var ev: protocol.Event = {
seq: 0,
type: "event",
event: eventName,
@@ -546,7 +550,7 @@ namespace ts.server {
// getFormattingEditsAfterKeytroke either empty or pertaining
// only to the previous line. If all this is true, then
// add edits necessary to properly indent the current line.
if ((key == "\n") && ((!edits) || (edits.length == 0) || allEditsBeforePos(edits, position))) {
if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) {
var scriptInfo = compilerService.host.getScriptInfo(file);
if (scriptInfo) {
var lineInfo = scriptInfo.getLineInfo(line);
@@ -622,7 +626,7 @@ namespace ts.server {
}
return completions.entries.reduce((result: protocol.CompletionEntry[], entry: ts.CompletionEntry) => {
if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) == 0)) {
if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) {
result.push(entry);
}
return result;
@@ -689,7 +693,7 @@ namespace ts.server {
}, []);
if (checkList.length > 0) {
this.updateErrorCheck(checkList, this.changeSeq,(n) => n == this.changeSeq, delay)
this.updateErrorCheck(checkList, this.changeSeq,(n) => n === this.changeSeq, delay)
}
}
@@ -704,7 +708,7 @@ namespace ts.server {
compilerService.host.editScript(file, start, end, insertString);
this.changeSeq++;
}
this.updateProjectStructure(this.changeSeq, (n) => n == this.changeSeq);
this.updateProjectStructure(this.changeSeq, (n) => n === this.changeSeq);
}
}
@@ -838,7 +842,7 @@ namespace ts.server {
onMessage(message: string) {
if (this.logger.isVerbose()) {
this.logger.info("request: " + message);
var start = process.hrtime();
var start = this.hrtime();
}
try {
var request = <protocol.Request>JSON.parse(message);
@@ -980,7 +984,7 @@ namespace ts.server {
}
if (this.logger.isVerbose()) {
var elapsed = process.hrtime(start);
var elapsed = this.hrtime(start);
var seconds = elapsed[0]
var nanoseconds = elapsed[1];
var elapsedMs = ((1e9 * seconds) + nanoseconds)/1000000.0;
+1 -1
View File
@@ -75,7 +75,7 @@ namespace ts.BreakpointResolver {
return textSpan(node);
}
if (node.parent.kind == SyntaxKind.ArrowFunction && (<FunctionLikeDeclaration>node.parent).body == node) {
if (node.parent.kind === SyntaxKind.ArrowFunction && (<FunctionLikeDeclaration>node.parent).body === node) {
// If this is body of arrow function, it is allowed to have the breakpoint
return textSpan(node);
}
+2 -2
View File
@@ -59,7 +59,7 @@ namespace ts.formatting {
if (this.tokensAreOnSameLine === undefined) {
let startLine = this.sourceFile.getLineAndCharacterOfPosition(this.currentTokenSpan.pos).line;
let endLine = this.sourceFile.getLineAndCharacterOfPosition(this.nextTokenSpan.pos).line;
this.tokensAreOnSameLine = (startLine == endLine);
this.tokensAreOnSameLine = (startLine === endLine);
}
return this.tokensAreOnSameLine;
@@ -84,7 +84,7 @@ namespace ts.formatting {
private NodeIsOnOneLine(node: Node): boolean {
let startLine = this.sourceFile.getLineAndCharacterOfPosition(node.getStart(this.sourceFile)).line;
let endLine = this.sourceFile.getLineAndCharacterOfPosition(node.getEnd()).line;
return startLine == endLine;
return startLine === endLine;
}
private BlockIsOnOneLine(node: Node): boolean {
@@ -14,7 +14,7 @@ namespace ts.formatting {
public IsAny(): boolean {
return this == RuleOperationContext.Any;
return this === RuleOperationContext.Any;
}
public InContext(context: FormattingContext): boolean {
+3 -2
View File
@@ -318,7 +318,7 @@ namespace ts.formatting {
this.NoSpaceAfterModuleImport = new Rule(RuleDescriptor.create2(Shared.TokenRange.FromTokens([SyntaxKind.ModuleKeyword, SyntaxKind.RequireKeyword]), SyntaxKind.OpenParenToken), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Delete));
// Add a space around certain TypeScript keywords
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceAfterCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.FromTokens([SyntaxKind.ClassKeyword, SyntaxKind.DeclareKeyword, SyntaxKind.DefaultKeyword, SyntaxKind.EnumKeyword, SyntaxKind.ExportKeyword, SyntaxKind.ExtendsKeyword, SyntaxKind.GetKeyword, SyntaxKind.ImplementsKeyword, SyntaxKind.ImportKeyword, SyntaxKind.InterfaceKeyword, SyntaxKind.ModuleKeyword, SyntaxKind.NamespaceKeyword, SyntaxKind.PrivateKeyword, SyntaxKind.PublicKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.SetKeyword, SyntaxKind.StaticKeyword]), Shared.TokenRange.Any), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
this.SpaceBeforeCertainTypeScriptKeywords = new Rule(RuleDescriptor.create4(Shared.TokenRange.Any, Shared.TokenRange.FromTokens([SyntaxKind.ExtendsKeyword, SyntaxKind.ImplementsKeyword])), RuleOperation.create2(new RuleOperationContext(Rules.IsSameLineTokenContext), RuleAction.Space));
// Treat string literals in module names as identifiers, and add a space between the literal and the opening Brace braces, e.g.: module "m2" {
@@ -470,6 +470,7 @@ namespace ts.formatting {
switch (context.contextNode.kind) {
case SyntaxKind.BinaryExpression:
case SyntaxKind.ConditionalExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.TypePredicate:
return true;
@@ -692,7 +693,7 @@ namespace ts.formatting {
}
static IsNotFormatOnEnter(context: FormattingContext): boolean {
return context.formattingRequestKind != FormattingRequestKind.FormatOnEnter;
return context.formattingRequestKind !== FormattingRequestKind.FormatOnEnter;
}
static IsModuleDeclContext(context: FormattingContext): boolean {
+5 -5
View File
@@ -41,15 +41,15 @@ namespace ts.formatting {
}
private FillRule(rule: Rule, rulesBucketConstructionStateList: RulesBucketConstructionState[]): void {
let specificRule = rule.Descriptor.LeftTokenRange != Shared.TokenRange.Any &&
rule.Descriptor.RightTokenRange != Shared.TokenRange.Any;
let specificRule = rule.Descriptor.LeftTokenRange !== Shared.TokenRange.Any &&
rule.Descriptor.RightTokenRange !== Shared.TokenRange.Any;
rule.Descriptor.LeftTokenRange.GetTokens().forEach((left) => {
rule.Descriptor.RightTokenRange.GetTokens().forEach((right) => {
let rulesBucketIndex = this.GetRuleBucketIndex(left, right);
let rulesBucket = this.map[rulesBucketIndex];
if (rulesBucket == undefined) {
if (rulesBucket === undefined) {
rulesBucket = this.map[rulesBucketIndex] = new RulesBucket();
}
@@ -124,7 +124,7 @@ namespace ts.formatting {
public IncreaseInsertionIndex(maskPosition: RulesPosition): void {
let value = (this.rulesInsertionIndexBitmap >> maskPosition) & Mask;
value++;
Debug.assert((value & Mask) == value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
Debug.assert((value & Mask) === value, "Adding more rules into the sub-bucket than allowed. Maximum allowed is 32 rules.");
let temp = this.rulesInsertionIndexBitmap & ~(Mask << maskPosition);
temp |= value << maskPosition;
@@ -147,7 +147,7 @@ namespace ts.formatting {
public AddRule(rule: Rule, specificTokens: boolean, constructionState: RulesBucketConstructionState[], rulesBucketIndex: number): void {
let position: RulesPosition;
if (rule.Operation.Action == RuleAction.Ignore) {
if (rule.Operation.Action === RuleAction.Ignore) {
position = specificTokens ?
RulesPosition.IgnoreRulesSpecific :
RulesPosition.IgnoreRulesAny;
+1
View File
@@ -25,6 +25,7 @@ namespace ts.formatting {
}
public ensureUpToDate(options: ts.FormatCodeOptions) {
// TODO: Should this be '==='?
if (this.options == null || !ts.compareDataObjects(this.options, options)) {
let activeRules = this.createActiveRules(options);
let rulesMap = RulesMap.create(activeRules);
+58 -1
View File
@@ -26,7 +26,7 @@ namespace ts.formatting {
precedingToken.kind === SyntaxKind.TemplateHead ||
precedingToken.kind === SyntaxKind.TemplateMiddle ||
precedingToken.kind === SyntaxKind.TemplateTail;
if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) {
if (precedingTokenIsLiteral && precedingToken.getStart(sourceFile) <= position && precedingToken.end > position) {
return 0;
}
@@ -66,6 +66,10 @@ namespace ts.formatting {
if (actualIndentation !== Value.Unknown) {
return actualIndentation;
}
actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
if (actualIndentation !== Value.Unknown) {
return actualIndentation + options.IndentSize;
}
previous = current;
current = current.parent;
@@ -122,6 +126,10 @@ namespace ts.formatting {
if (actualIndentation !== Value.Unknown) {
return actualIndentation + indentationDelta;
}
actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options);
if (actualIndentation !== Value.Unknown) {
return actualIndentation + indentationDelta;
}
}
// increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line
@@ -287,6 +295,55 @@ namespace ts.formatting {
}
}
function getLineIndentationWhenExpressionIsInMultiLine(node: Node, sourceFile: SourceFile, options: EditorOptions): number {
// actual indentation should not be used when:
// - node is close parenthesis - this is the end of the expression
if (node.kind === SyntaxKind.CloseParenToken) {
return Value.Unknown;
}
if (node.parent && (
node.parent.kind === SyntaxKind.CallExpression ||
node.parent.kind === SyntaxKind.NewExpression) &&
(<CallExpression>node.parent).expression !== node) {
let fullCallOrNewExpression = (<CallExpression | NewExpression>node.parent).expression;
let startingExpression = getStartingExpression(<PropertyAccessExpression | CallExpression | ElementAccessExpression>fullCallOrNewExpression);
if (fullCallOrNewExpression === startingExpression) {
return Value.Unknown;
}
let fullCallOrNewExpressionEnd = sourceFile.getLineAndCharacterOfPosition(fullCallOrNewExpression.end);
let startingExpressionEnd = sourceFile.getLineAndCharacterOfPosition(startingExpression.end);
if (fullCallOrNewExpressionEnd.line === startingExpressionEnd.line) {
return Value.Unknown;
}
return findColumnForFirstNonWhitespaceCharacterInLine(fullCallOrNewExpressionEnd, sourceFile, options);
}
return Value.Unknown;
function getStartingExpression(node: PropertyAccessExpression | CallExpression | ElementAccessExpression) {
while (true) {
switch (node.kind) {
case SyntaxKind.CallExpression:
case SyntaxKind.NewExpression:
case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.ElementAccessExpression:
node = <PropertyAccessExpression | CallExpression | ElementAccessExpression | PropertyAccessExpression>node.expression;
break;
default:
return node;
}
}
return node;
}
}
function deriveActualIndentationFromList(list: Node[], index: number, sourceFile: SourceFile, options: EditorOptions): number {
Debug.assert(index >= 0 && index < list.length);
let node = list[index];
+2 -2
View File
@@ -54,7 +54,7 @@ namespace ts.formatting {
}
public Contains(tokenValue: SyntaxKind): boolean {
return tokenValue == this.token;
return tokenValue === this.token;
}
}
@@ -112,7 +112,7 @@ namespace ts.formatting {
static AnyIncludingMultilineComments = TokenRange.FromTokens(TokenRange.Any.GetTokens().concat([SyntaxKind.MultiLineCommentTrivia]));
static Keywords = TokenRange.FromRange(SyntaxKind.FirstKeyword, SyntaxKind.LastKeyword);
static BinaryOperators = TokenRange.FromRange(SyntaxKind.FirstBinaryOperator, SyntaxKind.LastBinaryOperator);
static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.IsKeyword]);
static BinaryKeywordOperators = TokenRange.FromTokens([SyntaxKind.InKeyword, SyntaxKind.InstanceOfKeyword, SyntaxKind.OfKeyword, SyntaxKind.AsKeyword, SyntaxKind.IsKeyword]);
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]);
+2 -2
View File
@@ -686,7 +686,7 @@ namespace ts {
if (charIsPunctuation(identifier.charCodeAt(i - 1)) ||
charIsPunctuation(identifier.charCodeAt(i)) ||
lastIsDigit != currentIsDigit ||
lastIsDigit !== currentIsDigit ||
hasTransitionFromLowerToUpper ||
hasTransitionFromUpperToLower) {
@@ -757,7 +757,7 @@ namespace ts {
// 3) HTMLDocument -> HTML, Document
//
// etc.
if (index != wordStart &&
if (index !== wordStart &&
index + 1 < identifier.length) {
let currentIsUpper = isUpperCaseLetter(identifier.charCodeAt(index));
let nextIsLower = isLowerCaseLetter(identifier.charCodeAt(index + 1));
+299 -241
View File
@@ -95,7 +95,6 @@ namespace ts {
export module ScriptSnapshot {
class StringScriptSnapshot implements IScriptSnapshot {
private _lineStartPositions: number[] = undefined;
constructor(private text: string) {
}
@@ -167,7 +166,7 @@ namespace ts {
}
public getFullWidth(): number {
return this.end - this.getFullStart();
return this.end - this.pos;
}
public getLeadingTriviaWidth(sourceFile?: SourceFile): number {
@@ -198,8 +197,8 @@ namespace ts {
list._children = [];
let pos = nodes.pos;
for (let node of nodes) {
if (pos < node.pos) {
pos = this.addSyntheticNodes(list._children, pos, node.pos);
@@ -751,6 +750,7 @@ namespace ts {
public symbolCount: number;
public version: string;
public languageVersion: ScriptTarget;
public languageVariant: LanguageVariant;
public identifiers: Map<string>;
public nameTable: Map<string>;
@@ -875,7 +875,7 @@ namespace ts {
case SyntaxKind.SetAccessor:
case SyntaxKind.TypeLiteral:
addDeclaration(<Declaration>node);
// fall through
// fall through
case SyntaxKind.Constructor:
case SyntaxKind.VariableStatement:
case SyntaxKind.VariableDeclarationList:
@@ -973,6 +973,9 @@ namespace ts {
getSyntacticDiagnostics(fileName: string): Diagnostic[];
getSemanticDiagnostics(fileName: string): Diagnostic[];
// TODO: Rename this to getProgramDiagnostics to better indicate that these are any
// diagnostics present for the program level, and not just 'options' diagnostics.
getCompilerOptionsDiagnostics(): Diagnostic[];
/**
@@ -1092,7 +1095,7 @@ namespace ts {
export const definition = "definition";
export const reference = "reference";
export const writtenReference = "writtenReference";
}
}
export interface HighlightSpan {
textSpan: TextSpan;
@@ -1607,6 +1610,7 @@ namespace ts {
return {
target: ScriptTarget.ES5,
module: ModuleKind.None,
jsx: JsxEmit.Preserve
};
}
@@ -1789,18 +1793,13 @@ namespace ts {
sourceFile.moduleName = moduleName;
}
// Store syntactic diagnostics
if (diagnostics && sourceFile.parseDiagnostics) {
diagnostics.push(...sourceFile.parseDiagnostics);
}
let newLine = getNewLineCharacter(options);
// Output
let outputText: string;
// Create a compilerHost object to allow the compiler to read and write files
var compilerHost: CompilerHost = {
let compilerHost: CompilerHost = {
getSourceFile: (fileName, target) => fileName === inputFileName ? sourceFile : undefined,
writeFile: (name, text, writeByteOrderMark) => {
Debug.assert(outputText === undefined, "Unexpected multiple outputs for the file: " + name);
@@ -1813,11 +1812,10 @@ namespace ts {
getNewLine: () => newLine
};
var program = createProgram([inputFileName], options, compilerHost);
let program = createProgram([inputFileName], options, compilerHost);
if (diagnostics) {
diagnostics.push(...program.getCompilerOptionsDiagnostics());
}
addRange(/*to*/ diagnostics, /*from*/ program.getSyntacticDiagnostics(sourceFile));
addRange(/*to*/ diagnostics, /*from*/ program.getOptionsDiagnostics());
// Emit
program.emit();
@@ -2796,7 +2794,7 @@ namespace ts {
function getCompilerOptionsDiagnostics() {
synchronizeHostData();
return program.getGlobalDiagnostics();
return program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics());
}
/// Completion
@@ -2898,22 +2896,33 @@ namespace ts {
return undefined;
}
let options = program.getCompilerOptions();
let jsx = options.jsx !== JsxEmit.None;
let target = options.target;
// Find the node where completion is requested on, in the case of a completion after
// a dot, it is the member access expression other wise, it is a request for all
// visible symbols in the scope, and the node is the current location.
let node = currentToken;
let isRightOfDot = false;
if (contextToken && contextToken.kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.PropertyAccessExpression) {
node = (<PropertyAccessExpression>contextToken.parent).expression;
isRightOfDot = true;
}
else if (contextToken && contextToken.kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.QualifiedName) {
node = (<QualifiedName>contextToken.parent).left;
isRightOfDot = true;
}
let isRightOfOpenTag = false;
let location = getTouchingPropertyName(sourceFile, position);
var target = program.getCompilerOptions().target;
if(contextToken) {
let kind = contextToken.kind;
if (kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.PropertyAccessExpression) {
node = (<PropertyAccessExpression>contextToken.parent).expression;
isRightOfDot = true;
}
else if (kind === SyntaxKind.DotToken && contextToken.parent.kind === SyntaxKind.QualifiedName) {
node = (<QualifiedName>contextToken.parent).left;
isRightOfDot = true;
}
else if (kind === SyntaxKind.LessThanToken && sourceFile.languageVariant === LanguageVariant.JSX) {
isRightOfOpenTag = true;
location = contextToken;
}
}
let semanticStart = new Date().getTime();
let isMemberCompletion: boolean;
@@ -2923,6 +2932,17 @@ namespace ts {
if (isRightOfDot) {
getTypeScriptMemberSymbols();
}
else if (isRightOfOpenTag) {
let tagSymbols = typeChecker.getJsxIntrinsicTagNames();
if (tryGetGlobalSymbols()) {
symbols = tagSymbols.concat(symbols.filter(s => !!(s.flags & SymbolFlags.Value)));
}
else {
symbols = tagSymbols;
}
isMemberCompletion = true;
isNewIdentifierLocation = false;
}
else {
// For JavaScript or TypeScript, if we're not after a dot, then just try to get the
// global symbols in scope. These results should be valid for either language as
@@ -2934,7 +2954,7 @@ namespace ts {
log("getCompletionData: Semantic work: " + (new Date().getTime() - semanticStart));
return { symbols, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot };
return { symbols, isMemberCompletion, isNewIdentifierLocation, location, isRightOfDot: (isRightOfDot || isRightOfOpenTag) };
function getTypeScriptMemberSymbols(): void {
// Right of dot member completion list
@@ -2988,22 +3008,34 @@ namespace ts {
}
function tryGetGlobalSymbols(): boolean {
let containingObjectLiteral = getContainingObjectLiteralApplicableForCompletion(contextToken);
if (containingObjectLiteral) {
let objectLikeContainer = tryGetObjectLikeCompletionContainer(contextToken);
if (objectLikeContainer) {
// Object literal expression, look up possible property names from contextual type
isMemberCompletion = true;
isNewIdentifierLocation = true;
let contextualType = typeChecker.getContextualType(containingObjectLiteral);
if (!contextualType) {
let typeForObject: Type;
let existingMembers: Declaration[];
if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) {
typeForObject = typeChecker.getContextualType(<ObjectLiteralExpression>objectLikeContainer);
existingMembers = (<ObjectLiteralExpression>objectLikeContainer).properties;
}
else {
typeForObject = typeChecker.getTypeAtLocation(objectLikeContainer);
existingMembers = (<BindingPattern>objectLikeContainer).elements;
}
if (!typeForObject) {
return false;
}
let contextualTypeMembers = typeChecker.getPropertiesOfType(contextualType);
if (contextualTypeMembers && contextualTypeMembers.length > 0) {
let typeMembers = typeChecker.getPropertiesOfType(typeForObject);
if (typeMembers && typeMembers.length > 0) {
// Add filtered items to the completion list
symbols = filterContextualMembersList(contextualTypeMembers, containingObjectLiteral.properties);
symbols = filterObjectMembersList(typeMembers, existingMembers);
}
return true;
}
else if (getAncestor(contextToken, SyntaxKind.ImportClause)) {
// cursor is in import clause
@@ -3025,51 +3057,77 @@ namespace ts {
//let exports = typeInfoResolver.getExportsOfImportDeclaration(importDeclaration);
symbols = exports ? filterModuleExports(exports, importDeclaration) : emptyArray;
}
return true;
}
else {
// Get all entities in the current scope.
isMemberCompletion = false;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
else if (getAncestor(contextToken, SyntaxKind.JsxElement) || getAncestor(contextToken, SyntaxKind.JsxSelfClosingElement)) {
// Go up until we hit either the element or expression
let jsxNode = contextToken;
if (previousToken !== contextToken) {
Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
while (jsxNode) {
if (jsxNode.kind === SyntaxKind.JsxExpression) {
// Defer to global completion if we're inside an {expression}
break;
} else if (jsxNode.kind === SyntaxKind.JsxSelfClosingElement || jsxNode.kind === SyntaxKind.JsxElement) {
let attrsType: Type;
if (jsxNode.kind === SyntaxKind.JsxSelfClosingElement) {
// Cursor is inside a JSX self-closing element
attrsType = typeChecker.getJsxElementAttributesType(<JsxSelfClosingElement>jsxNode);
}
else {
Debug.assert(jsxNode.kind === SyntaxKind.JsxElement);
// Cursor is inside a JSX element
attrsType = typeChecker.getJsxElementAttributesType((<JsxElement>jsxNode).openingElement);
}
symbols = typeChecker.getPropertiesOfType(attrsType);
isMemberCompletion = true;
return true;
}
jsxNode = jsxNode.parent;
}
// We need to find the node that will give us an appropriate scope to begin
// aggregating completion candidates. This is achieved in 'getScopeNode'
// by finding the first node that encompasses a position, accounting for whether a node
// is "complete" to decide whether a position belongs to the node.
//
// However, at the end of an identifier, we are interested in the scope of the identifier
// itself, but fall outside of the identifier. For instance:
//
// xyz => x$
//
// the cursor is outside of both the 'x' and the arrow function 'xyz => x',
// so 'xyz' is not returned in our results.
//
// We define 'adjustedPosition' so that we may appropriately account for
// being at the end of an identifier. The intention is that if requesting completion
// at the end of an identifier, it should be effectively equivalent to requesting completion
// anywhere inside/at the beginning of the identifier. So in the previous case, the
// 'adjustedPosition' will work as if requesting completion in the following:
//
// xyz => $x
//
// If previousToken !== contextToken, then
// - 'contextToken' was adjusted to the token prior to 'previousToken'
// because we were at the end of an identifier.
// - 'previousToken' is defined.
let adjustedPosition = previousToken !== contextToken ?
previousToken.getStart() :
position;
let scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
/// TODO filter meaning based on the current context
let symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias;
symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings);
}
// Get all entities in the current scope.
isMemberCompletion = false;
isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken);
if (previousToken !== contextToken) {
Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'.");
}
// We need to find the node that will give us an appropriate scope to begin
// aggregating completion candidates. This is achieved in 'getScopeNode'
// by finding the first node that encompasses a position, accounting for whether a node
// is "complete" to decide whether a position belongs to the node.
//
// However, at the end of an identifier, we are interested in the scope of the identifier
// itself, but fall outside of the identifier. For instance:
//
// xyz => x$
//
// the cursor is outside of both the 'x' and the arrow function 'xyz => x',
// so 'xyz' is not returned in our results.
//
// We define 'adjustedPosition' so that we may appropriately account for
// being at the end of an identifier. The intention is that if requesting completion
// at the end of an identifier, it should be effectively equivalent to requesting completion
// anywhere inside/at the beginning of the identifier. So in the previous case, the
// 'adjustedPosition' will work as if requesting completion in the following:
//
// xyz => $x
//
// If previousToken !== contextToken, then
// - 'contextToken' was adjusted to the token prior to 'previousToken'
// because we were at the end of an identifier.
// - 'previousToken' is defined.
let adjustedPosition = previousToken !== contextToken ?
previousToken.getStart() :
position;
let scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile;
/// TODO filter meaning based on the current context
let symbolMeanings = SymbolFlags.Type | SymbolFlags.Value | SymbolFlags.Namespace | SymbolFlags.Alias;
symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings);
return true;
}
@@ -3078,7 +3136,7 @@ namespace ts {
* accurately aggregate locals from the closest containing scope.
*/
function getScopeNode(initialToken: Node, position: number, sourceFile: SourceFile) {
var scope = initialToken;
let scope = initialToken;
while (scope && !positionBelongsToNode(scope, position, sourceFile)) {
scope = scope.parent;
}
@@ -3190,17 +3248,18 @@ namespace ts {
return false;
}
function getContainingObjectLiteralApplicableForCompletion(previousToken: Node): ObjectLiteralExpression {
// The locations in an object literal expression that are applicable for completion are property name definition locations.
if (previousToken) {
let parent = previousToken.parent;
switch (previousToken.kind) {
/**
* Returns the immediate owning object literal or binding pattern of a context token,
* on the condition that one exists and that the context implies completion should be given.
*/
function tryGetObjectLikeCompletionContainer(contextToken: Node): ObjectLiteralExpression | BindingPattern {
if (contextToken) {
switch (contextToken.kind) {
case SyntaxKind.OpenBraceToken: // let x = { |
case SyntaxKind.CommaToken: // let x = { a: 0, |
if (parent && parent.kind === SyntaxKind.ObjectLiteralExpression) {
return <ObjectLiteralExpression>parent;
let parent = contextToken.parent;
if (parent && (parent.kind === SyntaxKind.ObjectLiteralExpression || parent.kind === SyntaxKind.ObjectBindingPattern)) {
return <ObjectLiteralExpression | BindingPattern>parent;
}
break;
}
@@ -3239,8 +3298,7 @@ namespace ts {
containingNodeKind === SyntaxKind.ClassDeclaration || // class A<T, |
containingNodeKind === SyntaxKind.FunctionDeclaration || // function A<T, |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface A<T, |
containingNodeKind === SyntaxKind.ArrayBindingPattern || // var [x, y|
containingNodeKind === SyntaxKind.ObjectBindingPattern; // function func({ x, y|
containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [x, y|
case SyntaxKind.DotToken:
return containingNodeKind === SyntaxKind.ArrayBindingPattern; // var [.|
@@ -3258,8 +3316,7 @@ namespace ts {
case SyntaxKind.OpenBraceToken:
return containingNodeKind === SyntaxKind.EnumDeclaration || // enum a { |
containingNodeKind === SyntaxKind.InterfaceDeclaration || // interface a { |
containingNodeKind === SyntaxKind.TypeLiteral || // let x : { |
containingNodeKind === SyntaxKind.ObjectBindingPattern; // function func({ x|
containingNodeKind === SyntaxKind.TypeLiteral; // let x : { |
case SyntaxKind.SemicolonToken:
return containingNodeKind === SyntaxKind.PropertySignature &&
@@ -3351,26 +3408,39 @@ namespace ts {
return filter(exports, e => !lookUp(exisingImports, e.name));
}
function filterContextualMembersList(contextualMemberSymbols: Symbol[], existingMembers: Declaration[]): Symbol[] {
function filterObjectMembersList(contextualMemberSymbols: Symbol[], existingMembers: Declaration[]): Symbol[] {
if (!existingMembers || existingMembers.length === 0) {
return contextualMemberSymbols;
}
let existingMemberNames: Map<boolean> = {};
forEach(existingMembers, m => {
if (m.kind !== SyntaxKind.PropertyAssignment && m.kind !== SyntaxKind.ShorthandPropertyAssignment) {
// Ignore omitted expressions for missing members in the object literal
return;
for (let m of existingMembers) {
// Ignore omitted expressions for missing members
if (m.kind !== SyntaxKind.PropertyAssignment &&
m.kind !== SyntaxKind.ShorthandPropertyAssignment &&
m.kind !== SyntaxKind.BindingElement) {
continue;
}
// If this is the current item we are editing right now, do not filter it out
if (m.getStart() <= position && position <= m.getEnd()) {
// If this is the current item we are editing right now, do not filter it out
return;
continue;
}
// TODO(jfreeman): Account for computed property name
existingMemberNames[(<Identifier>m.name).text] = true;
});
let existingName: string;
if (m.kind === SyntaxKind.BindingElement && (<BindingElement>m).propertyName) {
existingName = (<BindingElement>m).propertyName.text;
}
else {
// TODO(jfreeman): Account for computed property name
// NOTE: if one only performs this step when m.name is an identifier,
// things like '__proto__' are not filtered out.
existingName = (<Identifier>m.name).text;
}
existingMemberNames[existingName] = true;
}
let filteredMembers: Symbol[] = [];
forEach(contextualMemberSymbols, s => {
@@ -3467,10 +3537,10 @@ namespace ts {
function getCompletionEntriesFromSymbols(symbols: Symbol[]): CompletionEntry[] {
let start = new Date().getTime();
var entries: CompletionEntry[] = [];
let entries: CompletionEntry[] = [];
if (symbols) {
var nameToSymbol: Map<Symbol> = {};
let nameToSymbol: Map<Symbol> = {};
for (let symbol of symbols) {
let entry = createCompletionEntry(symbol, location);
if (entry) {
@@ -3504,13 +3574,13 @@ namespace ts {
let symbol = forEach(symbols, s => getCompletionEntryDisplayNameForSymbol(s, target, /*performCharacterChecks:*/ false) === entryName ? s : undefined);
if (symbol) {
let displayPartsDocumentationsAndSymbolKind = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, location, SemanticMeaning.All);
let { displayParts, documentation, symbolKind } = getSymbolDisplayPartsDocumentationAndSymbolKind(symbol, getValidSourceFile(fileName), location, location, SemanticMeaning.All);
return {
name: entryName,
kind: displayPartsDocumentationsAndSymbolKind.symbolKind,
kindModifiers: getSymbolModifiers(symbol),
displayParts: displayPartsDocumentationsAndSymbolKind.displayParts,
documentation: displayPartsDocumentationsAndSymbolKind.documentation
kind: symbolKind,
displayParts,
documentation
};
}
}
@@ -4185,10 +4255,10 @@ namespace ts {
}
if (type.flags & TypeFlags.Union) {
var result: DefinitionInfo[] = [];
let result: DefinitionInfo[] = [];
forEach((<UnionType>type).types, t => {
if (t.symbol) {
result.push(...getDefinitionFromSymbol(t.symbol, node));
addRange(/*to*/ result, /*from*/ getDefinitionFromSymbol(t.symbol, node));
}
});
return result;
@@ -4203,7 +4273,7 @@ namespace ts {
function getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
let results = getOccurrencesAtPositionCore(fileName, position);
if (results) {
let sourceFile = getCanonicalFileName(normalizeSlashes(fileName));
@@ -4247,7 +4317,7 @@ namespace ts {
isLiteralNameOfPropertyDeclarationOrIndexAccess(node) ||
isNameOfExternalModuleImportOrDeclaration(node)) {
let referencedSymbols = getReferencedSymbolsForNodes(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false);
let referencedSymbols = getReferencedSymbolsForNode(node, sourceFilesToSearch, /*findInStrings:*/ false, /*findInComments:*/ false);
return convertReferencedSymbols(referencedSymbols);
}
@@ -4285,7 +4355,7 @@ namespace ts {
function getSyntacticDocumentHighlights(node: Node): DocumentHighlights[] {
let fileName = sourceFile.fileName;
var highlightSpans = getHighlightSpans(node);
let highlightSpans = getHighlightSpans(node);
if (!highlightSpans || highlightSpans.length === 0) {
return undefined;
}
@@ -4863,17 +4933,17 @@ namespace ts {
}
function findRenameLocations(fileName: string, position: number, findInStrings: boolean, findInComments: boolean): RenameLocation[] {
var referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments);
let referencedSymbols = findReferencedSymbols(fileName, position, findInStrings, findInComments);
return convertReferences(referencedSymbols);
}
function getReferencesAtPosition(fileName: string, position: number): ReferenceEntry[] {
var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false);
let referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false);
return convertReferences(referencedSymbols);
}
function findReferences(fileName: string, position: number): ReferencedSymbol[]{
var referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false);
let referencedSymbols = findReferencedSymbols(fileName, position, /*findInStrings:*/ false, /*findInComments:*/ false);
// Only include referenced symbols that have a valid definition.
return filter(referencedSymbols, rs => !!rs.definition);
@@ -4899,10 +4969,10 @@ namespace ts {
}
Debug.assert(node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.NumericLiteral || node.kind === SyntaxKind.StringLiteral);
return getReferencedSymbolsForNodes(node, program.getSourceFiles(), findInStrings, findInComments);
return getReferencedSymbolsForNode(node, program.getSourceFiles(), findInStrings, findInComments);
}
function getReferencedSymbolsForNodes(node: Node, sourceFiles: SourceFile[], findInStrings: boolean, findInComments: boolean): ReferencedSymbol[] {
function getReferencedSymbolsForNode(node: Node, sourceFiles: SourceFile[], findInStrings: boolean, findInComments: boolean): ReferencedSymbol[] {
let typeChecker = program.getTypeChecker();
// Labels
@@ -4937,7 +5007,7 @@ namespace ts {
let declarations = symbol.declarations;
// The symbol was an internal symbol and does not have a declaration e.g.undefined symbol
// The symbol was an internal symbol and does not have a declaration e.g. undefined symbol
if (!declarations || !declarations.length) {
return undefined;
}
@@ -4947,8 +5017,9 @@ namespace ts {
// Compute the meaning from the location and the symbol it references
let searchMeaning = getIntersectingMeaningFromDeclarations(getMeaningFromLocation(node), declarations);
// Get the text to search for, we need to normalize it as external module names will have quote
let declaredName = getDeclaredName(symbol, node);
// Get the text to search for.
// Note: if this is an external module symbol, the name doesn't include quotes.
let declaredName = getDeclaredName(typeChecker, symbol, node);
// Try to get the smallest valid scope that we can limit our search to;
// otherwise we'll need to search globally (i.e. include each file).
@@ -4995,76 +5066,43 @@ namespace ts {
};
}
function isImportOrExportSpecifierName(location: Node): boolean {
return location.parent &&
(location.parent.kind === SyntaxKind.ImportSpecifier || location.parent.kind === SyntaxKind.ExportSpecifier) &&
(<ImportOrExportSpecifier>location.parent).propertyName === location;
}
function isImportOrExportSpecifierImportSymbol(symbol: Symbol) {
return (symbol.flags & SymbolFlags.Alias) && forEach(symbol.declarations, declaration => {
return declaration.kind === SyntaxKind.ImportSpecifier || declaration.kind === SyntaxKind.ExportSpecifier;
});
}
function getDeclaredName(symbol: Symbol, location: Node) {
// Special case for function expressions, whose names are solely local to their bodies.
let functionExpression = forEach(symbol.declarations, d => d.kind === SyntaxKind.FunctionExpression ? <FunctionExpression>d : undefined);
// When a name gets interned into a SourceFile's 'identifiers' Map,
// its name is escaped and stored in the same way its symbol name/identifier
// name should be stored. Function expressions, however, are a special case,
// because despite sometimes having a name, the binder unconditionally binds them
// to a symbol with the name "__function".
let name: string;
if (functionExpression && functionExpression.name) {
name = functionExpression.name.text;
}
// If this is an export or import specifier it could have been renamed using the as syntax.
// if so we want to search for whatever under the cursor, the symbol is pointing to the alias (name)
// so check for the propertyName.
if (isImportOrExportSpecifierName(location)) {
return location.getText();
}
name = typeChecker.symbolToString(symbol);
return stripQuotes(name);
}
function getInternedName(symbol: Symbol, location: Node, declarations: Declaration[]): string {
// If this is an export or import specifier it could have been renamed using the as syntax.
// if so we want to search for whatever under the cursor, the symbol is pointing to the alias (name)
// so check for the propertyName.
// If this is an export or import specifier it could have been renamed using the 'as' syntax.
// If so we want to search for whatever under the cursor.
if (isImportOrExportSpecifierName(location)) {
return location.getText();
}
// Special case for function expressions, whose names are solely local to their bodies.
let functionExpression = forEach(declarations, d => d.kind === SyntaxKind.FunctionExpression ? <FunctionExpression>d : undefined);
// Try to get the local symbol if we're dealing with an 'export default'
// since that symbol has the "true" name.
let localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol);
symbol = localExportDefaultSymbol || symbol;
// When a name gets interned into a SourceFile's 'identifiers' Map,
// its name is escaped and stored in the same way its symbol name/identifier
// name should be stored. Function expressions, however, are a special case,
// because despite sometimes having a name, the binder unconditionally binds them
// to a symbol with the name "__function".
let name = functionExpression && functionExpression.name
? functionExpression.name.text
: symbol.name;
return stripQuotes(name);
}
function stripQuotes(name: string) {
let length = name.length;
if (length >= 2 && name.charCodeAt(0) === CharacterCodes.doubleQuote && name.charCodeAt(length - 1) === CharacterCodes.doubleQuote) {
return name.substring(1, length - 1);
};
return name;
return stripQuotes(symbol.name);
}
/**
* Determines the smallest scope in which a symbol may have named references.
* Note that not every construct has been accounted for. This function can
* probably be improved.
*
* @returns undefined if the scope cannot be determined, implying that
* a reference to a symbol can occur anywhere.
*/
function getSymbolScope(symbol: Symbol): Node {
// If this is the symbol of a function expression, then named references
// are limited to its own scope.
let valueDeclaration = symbol.valueDeclaration;
if (valueDeclaration && valueDeclaration.kind === SyntaxKind.FunctionExpression) {
return valueDeclaration;
}
// If this is private property or method, the scope is the containing class
if (symbol.flags & (SymbolFlags.Property | SymbolFlags.Method)) {
let privateDeclaration = forEach(symbol.getDeclarations(), d => (d.flags & NodeFlags.Private) ? d : undefined);
@@ -5172,7 +5210,7 @@ namespace ts {
}
});
var definition: DefinitionInfo = {
let definition: DefinitionInfo = {
containerKind: "",
containerName: "",
fileName: targetLabel.getSourceFile().fileName,
@@ -5268,10 +5306,10 @@ namespace ts {
if (referenceSymbol) {
let referenceSymbolDeclaration = referenceSymbol.valueDeclaration;
let shorthandValueSymbol = typeChecker.getShorthandAssignmentValueSymbol(referenceSymbolDeclaration);
var relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation);
let relatedSymbol = getRelatedSymbol(searchSymbols, referenceSymbol, referenceLocation);
if (relatedSymbol) {
var referencedSymbol = getReferencedSymbol(relatedSymbol);
let referencedSymbol = getReferencedSymbol(relatedSymbol);
referencedSymbol.references.push(getReferenceEntryFromNode(referenceLocation));
}
/* Because in short-hand property assignment, an identifier which stored as name of the short-hand property assignment
@@ -5281,7 +5319,7 @@ namespace ts {
* position of property accessing, the referenceEntry of such position will be handled in the first case.
*/
else if (!(referenceSymbol.flags & SymbolFlags.Transient) && searchSymbols.indexOf(shorthandValueSymbol) >= 0) {
var referencedSymbol = getReferencedSymbol(shorthandValueSymbol);
let referencedSymbol = getReferencedSymbol(shorthandValueSymbol);
referencedSymbol.references.push(getReferenceEntryFromNode(referenceSymbolDeclaration.name));
}
}
@@ -5291,8 +5329,8 @@ namespace ts {
return;
function getReferencedSymbol(symbol: Symbol): ReferencedSymbol {
var symbolId = getSymbolId(symbol);
var index = symbolToIndex[symbolId];
let symbolId = getSymbolId(symbol);
let index = symbolToIndex[symbolId];
if (index === undefined) {
index = result.length;
symbolToIndex[symbolId] = index;
@@ -5379,7 +5417,7 @@ namespace ts {
}
});
var definition = getDefinition(searchSpaceNode.symbol);
let definition = getDefinition(searchSpaceNode.symbol);
return [{ definition, references }];
}
@@ -5574,7 +5612,7 @@ namespace ts {
// If the reference symbol is an alias, check if what it is aliasing is one of the search
// symbols.
if (isImportOrExportSpecifierImportSymbol(referenceSymbol)) {
var aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol);
let aliasedSymbol = typeChecker.getAliasedSymbol(referenceSymbol);
if (searchSymbols.indexOf(aliasedSymbol) >= 0) {
return aliasedSymbol;
}
@@ -5807,11 +5845,12 @@ namespace ts {
}
function isTypeReference(node: Node): boolean {
if (isRightSideOfQualifiedNameOrPropertyAccess(node) ) {
if (isRightSideOfQualifiedNameOrPropertyAccess(node)) {
node = node.parent;
}
return node.parent.kind === SyntaxKind.TypeReference || node.parent.kind === SyntaxKind.ExpressionWithTypeArguments;
return node.parent.kind === SyntaxKind.TypeReference ||
(node.parent.kind === SyntaxKind.ExpressionWithTypeArguments && !isExpressionWithTypeArgumentsInClassExtendsClause(<ExpressionWithTypeArguments>node.parent));
}
function isNamespaceReference(node: Node): boolean {
@@ -5975,13 +6014,13 @@ namespace ts {
return BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position);
}
function getNavigationBarItems(fileName: string): NavigationBarItem[]{
function getNavigationBarItems(fileName: string): NavigationBarItem[] {
let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
return NavigationBar.getNavigationBarItems(sourceFile);
}
function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]{
function getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] {
return convertClassifications(getEncodedSemanticClassifications(fileName, span));
}
@@ -6043,7 +6082,8 @@ namespace ts {
*/
function hasValueSideModule(symbol: Symbol): boolean {
return forEach(symbol.declarations, declaration => {
return declaration.kind === SyntaxKind.ModuleDeclaration && getModuleInstanceState(declaration) == ModuleInstanceState.Instantiated;
return declaration.kind === SyntaxKind.ModuleDeclaration &&
getModuleInstanceState(declaration) === ModuleInstanceState.Instantiated;
});
}
}
@@ -6109,17 +6149,19 @@ namespace ts {
return result;
}
function getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[]{
function getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] {
return convertClassifications(getEncodedSyntacticClassifications(fileName, span));
}
function getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications {
// doesn't use compiler - no need to synchronize with host
let sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
let spanStart = span.start;
let spanLength = span.length;
// Make a scanner we can get trivia from.
let triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text);
let mergeConflictScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.text);
let triviaScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text);
let mergeConflictScanner = createScanner(ScriptTarget.Latest, /*skipTrivia:*/ false, sourceFile.languageVariant, sourceFile.text);
let result: number[] = [];
processElement(sourceFile);
@@ -6132,48 +6174,55 @@ namespace ts {
result.push(type);
}
function classifyLeadingTrivia(token: Node): void {
let tokenStart = skipTrivia(sourceFile.text, token.pos, /*stopAfterLineBreak:*/ false);
if (tokenStart === token.pos) {
return;
}
// token has trivia. Classify them appropriately.
function classifyLeadingTriviaAndGetTokenStart(token: Node): number {
triviaScanner.setTextPos(token.pos);
while (true) {
let start = triviaScanner.getTextPos();
// only bother scanning if we have something that could be trivia.
if (!couldStartTrivia(sourceFile.text, start)) {
return start;
}
let kind = triviaScanner.scan();
let end = triviaScanner.getTextPos();
let width = end - start;
// The moment we get something that isn't trivia, then stop processing.
if (!isTrivia(kind)) {
return;
return start;
}
// Don't bother with newlines/whitespace.
if (kind === SyntaxKind.NewLineTrivia || kind === SyntaxKind.WhitespaceTrivia) {
continue;
}
// Only bother with the trivia if it at least intersects the span of interest.
if (textSpanIntersectsWith(span, start, width)) {
if (isComment(kind)) {
classifyComment(token, kind, start, width);
if (isComment(kind)) {
classifyComment(token, kind, start, width);
// Classifying a comment might cause us to reuse the trivia scanner
// (because of jsdoc comments). So after we classify the comment make
// sure we set the scanner position back to where it needs to be.
triviaScanner.setTextPos(end);
continue;
}
if (kind === SyntaxKind.ConflictMarkerTrivia) {
let text = sourceFile.text;
let ch = text.charCodeAt(start);
// for the <<<<<<< and >>>>>>> markers, we just add them in as comments
// in the classification stream.
if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) {
pushClassification(start, width, ClassificationType.comment);
continue;
}
if (kind === SyntaxKind.ConflictMarkerTrivia) {
let text = sourceFile.text;
let ch = text.charCodeAt(start);
// for the <<<<<<< and >>>>>>> markers, we just add them in as comments
// in the classification stream.
if (ch === CharacterCodes.lessThan || ch === CharacterCodes.greaterThan) {
pushClassification(start, width, ClassificationType.comment);
continue;
}
// for the ======== add a comment for the first line, and then lex all
// subsequent lines up until the end of the conflict marker.
Debug.assert(ch === CharacterCodes.equals);
classifyDisabledMergeCode(text, start, end);
}
// for the ======== add a comment for the first line, and then lex all
// subsequent lines up until the end of the conflict marker.
Debug.assert(ch === CharacterCodes.equals);
classifyDisabledMergeCode(text, start, end);
}
}
}
@@ -6292,12 +6341,18 @@ namespace ts {
}
function classifyToken(token: Node): void {
classifyLeadingTrivia(token);
if (nodeIsMissing(token)) {
return;
}
if (token.getWidth() > 0) {
let tokenStart = classifyLeadingTriviaAndGetTokenStart(token);
let tokenWidth = token.end - tokenStart;
Debug.assert(tokenWidth >= 0);
if (tokenWidth > 0) {
let type = classifyTokenType(token.kind, token);
if (type) {
pushClassification(token.getStart(), token.getWidth(), type);
pushClassification(tokenStart, tokenWidth, type);
}
}
}
@@ -6402,9 +6457,10 @@ namespace ts {
}
// Ignore nodes that don't intersect the original span to classify.
if (textSpanIntersectsWith(span, element.getFullStart(), element.getFullWidth())) {
if (decodedTextSpanIntersectsWith(spanStart, spanLength, element.pos, element.getFullWidth())) {
let children = element.getChildren(sourceFile);
for (let child of children) {
for (let i = 0, n = children.length; i < n; i++) {
let child = children[i];
if (isToken(child)) {
classifyToken(child);
}
@@ -6460,14 +6516,14 @@ namespace ts {
function getMatchingTokenKind(token: Node): ts.SyntaxKind {
switch (token.kind) {
case ts.SyntaxKind.OpenBraceToken: return ts.SyntaxKind.CloseBraceToken
case ts.SyntaxKind.OpenParenToken: return ts.SyntaxKind.CloseParenToken;
case ts.SyntaxKind.OpenBracketToken: return ts.SyntaxKind.CloseBracketToken;
case ts.SyntaxKind.LessThanToken: return ts.SyntaxKind.GreaterThanToken;
case ts.SyntaxKind.CloseBraceToken: return ts.SyntaxKind.OpenBraceToken
case ts.SyntaxKind.CloseParenToken: return ts.SyntaxKind.OpenParenToken;
case ts.SyntaxKind.CloseBracketToken: return ts.SyntaxKind.OpenBracketToken;
case ts.SyntaxKind.GreaterThanToken: return ts.SyntaxKind.LessThanToken;
case ts.SyntaxKind.OpenBraceToken: return ts.SyntaxKind.CloseBraceToken
case ts.SyntaxKind.OpenParenToken: return ts.SyntaxKind.CloseParenToken;
case ts.SyntaxKind.OpenBracketToken: return ts.SyntaxKind.CloseBracketToken;
case ts.SyntaxKind.LessThanToken: return ts.SyntaxKind.GreaterThanToken;
case ts.SyntaxKind.CloseBraceToken: return ts.SyntaxKind.OpenBraceToken
case ts.SyntaxKind.CloseParenToken: return ts.SyntaxKind.OpenParenToken;
case ts.SyntaxKind.CloseBracketToken: return ts.SyntaxKind.OpenBracketToken;
case ts.SyntaxKind.GreaterThanToken: return ts.SyntaxKind.LessThanToken;
}
return undefined;
@@ -6682,18 +6738,20 @@ namespace ts {
if (defaultLibFileName) {
for (let current of declarations) {
let sourceFile = current.getSourceFile();
var canonicalName = getCanonicalFileName(ts.normalizePath(sourceFile.fileName));
if (sourceFile && getCanonicalFileName(ts.normalizePath(sourceFile.fileName)) === getCanonicalFileName(ts.normalizePath(defaultLibFileName))) {
return getRenameInfoError(getLocaleSpecificMessage(Diagnostics.You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library.key));
}
}
}
let displayName = getDeclaredName(typeChecker, symbol, node);
let kind = getSymbolKind(symbol, node);
if (kind) {
return {
canRename: true,
localizedErrorMessage: undefined,
displayName: symbol.name,
displayName,
fullDisplayName: typeChecker.getFullyQualifiedName(symbol),
kind: kind,
kindModifiers: getSymbolModifiers(symbol),
@@ -6872,7 +6930,7 @@ namespace ts {
}
function convertClassifications(classifications: Classifications, text: string): ClassificationResult {
var entries: ClassificationInfo[] = [];
let entries: ClassificationInfo[] = [];
let dense = classifications.spans;
let lastEnd = 0;
@@ -6910,7 +6968,7 @@ namespace ts {
case ClassificationType.stringLiteral: return TokenClass.StringLiteral;
case ClassificationType.whiteSpace: return TokenClass.Whitespace;
case ClassificationType.punctuation: return TokenClass.Punctuation;
case ClassificationType.identifier:
case ClassificationType.identifier:
case ClassificationType.className:
case ClassificationType.enumName:
case ClassificationType.interfaceName:
@@ -6965,7 +7023,7 @@ namespace ts {
case EndOfLineState.InTemplateMiddleOrTail:
text = "}\n" + text;
offset = 2;
// fallthrough
// fallthrough
case EndOfLineState.InTemplateSubstitutionPosition:
templateStack.push(SyntaxKind.TemplateHead);
break;
@@ -7004,9 +7062,9 @@ namespace ts {
if (!isTrivia(token)) {
if ((token === SyntaxKind.SlashToken || token === SyntaxKind.SlashEqualsToken) && !noRegexTable[lastNonTriviaToken]) {
if (scanner.reScanSlashToken() === SyntaxKind.RegularExpressionLiteral) {
token = SyntaxKind.RegularExpressionLiteral;
}
if (scanner.reScanSlashToken() === SyntaxKind.RegularExpressionLiteral) {
token = SyntaxKind.RegularExpressionLiteral;
}
}
else if (lastNonTriviaToken === SyntaxKind.DotToken && isKeyword(token)) {
token = SyntaxKind.Identifier;
@@ -7019,7 +7077,7 @@ namespace ts {
token = SyntaxKind.Identifier;
}
else if (lastNonTriviaToken === SyntaxKind.Identifier &&
token === SyntaxKind.LessThanToken) {
token === SyntaxKind.LessThanToken) {
// Could be the start of something generic. Keep track of that by bumping
// up the current count of generic contexts we may be in.
angleBracketStack++;
@@ -7030,10 +7088,10 @@ namespace ts {
angleBracketStack--;
}
else if (token === SyntaxKind.AnyKeyword ||
token === SyntaxKind.StringKeyword ||
token === SyntaxKind.NumberKeyword ||
token === SyntaxKind.BooleanKeyword ||
token === SyntaxKind.SymbolKeyword) {
token === SyntaxKind.StringKeyword ||
token === SyntaxKind.NumberKeyword ||
token === SyntaxKind.BooleanKeyword ||
token === SyntaxKind.SymbolKeyword) {
if (angleBracketStack > 0 && !syntacticClassifierAbsent) {
// If it looks like we're could be in something generic, don't classify this
// as a keyword. We may just get overwritten by the syntactic classifier,
@@ -7269,7 +7327,7 @@ namespace ts {
declare let __dirname: string;
/**
* Get the path of the default library file (lib.d.ts) as distributed with the typescript
* Get the path of the default library files (lib.d.ts) as distributed with the typescript
* node package.
* The functionality is not supported if the ts module is consumed outside of a node module.
*/
+2
View File
@@ -234,6 +234,7 @@ namespace ts {
public getChangeRange(oldSnapshot: IScriptSnapshot): TextChangeRange {
var oldSnapshotShim = <ScriptSnapshotShimAdapter>oldSnapshot;
var encoded = this.scriptSnapshotShim.getChangeRange(oldSnapshotShim.scriptSnapshotShim);
// TODO: should this be '==='?
if (encoded == null) {
return null;
}
@@ -283,6 +284,7 @@ namespace ts {
public getCompilationSettings(): CompilerOptions {
var settingsJson = this.shimHost.getCompilationSettings();
// TODO: should this be '==='?
if (settingsJson == null || settingsJson == "") {
throw Error("LanguageServiceShimHostAdapter.getCompilationSettings: empty compilationSettings");
return null;
+30
View File
@@ -652,4 +652,34 @@ namespace ts {
typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags);
});
}
export function getDeclaredName(typeChecker: TypeChecker, symbol: Symbol, location: Node): string {
// If this is an export or import specifier it could have been renamed using the 'as' syntax.
// If so we want to search for whatever is under the cursor.
if (isImportOrExportSpecifierName(location)) {
return location.getText();
}
// Try to get the local symbol if we're dealing with an 'export default'
// since that symbol has the "true" name.
let localExportDefaultSymbol = getLocalSymbolForExportDefault(symbol);
let name = typeChecker.symbolToString(localExportDefaultSymbol || symbol);
return stripQuotes(name);
}
export function isImportOrExportSpecifierName(location: Node): boolean {
return location.parent &&
(location.parent.kind === SyntaxKind.ImportSpecifier || location.parent.kind === SyntaxKind.ExportSpecifier) &&
(<ImportOrExportSpecifier>location.parent).propertyName === location;
}
export function stripQuotes(name: string) {
let length = name.length;
if (length >= 2 && name.charCodeAt(0) === CharacterCodes.doubleQuote && name.charCodeAt(length - 1) === CharacterCodes.doubleQuote) {
return name.substring(1, length - 1);
};
return name;
}
}
+11 -11
View File
@@ -75,28 +75,28 @@ function delint(sourceFile) {
delintNode(sourceFile);
function delintNode(node) {
switch (node.kind) {
case 192 /* ForStatement */:
case 193 /* ForInStatement */:
case 191 /* WhileStatement */:
case 190 /* DoStatement */:
if (node.statement.kind !== 185 /* Block */) {
case 194 /* ForStatement */:
case 195 /* ForInStatement */:
case 193 /* WhileStatement */:
case 192 /* DoStatement */:
if (node.statement.kind !== 187 /* Block */) {
report(node, "A looping statement's contents should be wrapped in a block body.");
}
break;
case 189 /* IfStatement */:
case 191 /* IfStatement */:
var ifStatement = node;
if (ifStatement.thenStatement.kind !== 185 /* Block */) {
if (ifStatement.thenStatement.kind !== 187 /* Block */) {
report(ifStatement.thenStatement, "An if statement's contents should be wrapped in a block body.");
}
if (ifStatement.elseStatement &&
ifStatement.elseStatement.kind !== 185 /* Block */ &&
ifStatement.elseStatement.kind !== 189 /* IfStatement */) {
ifStatement.elseStatement.kind !== 187 /* Block */ &&
ifStatement.elseStatement.kind !== 191 /* IfStatement */) {
report(ifStatement.elseStatement, "An else statement's contents should be wrapped in a block body.");
}
break;
case 175 /* BinaryExpression */:
case 176 /* BinaryExpression */:
var op = node.operatorToken.kind;
if (op === 28 /* EqualsEqualsToken */ || op == 29 /* ExclamationEqualsToken */) {
if (op === 29 /* EqualsEqualsToken */ || op == 30 /* ExclamationEqualsToken */) {
report(node, "Use '===' and '!=='.");
}
break;
@@ -24,8 +24,7 @@ module A {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A;
(function (A) {
@@ -28,8 +28,7 @@ module A {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A;
(function (A) {
@@ -19,8 +19,7 @@ class ColoredPoint extends Point {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Point = (function () {
function Point(x, y) {
@@ -28,8 +28,7 @@ class LanguageSpec_section_4_5_inference {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A() {
@@ -38,8 +38,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsage1_backbone");
var VisualizationModel = (function (_super) {
@@ -53,9 +53,9 @@ import Backbone = require("aliasUsage1_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -32,8 +32,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInArray_backbone");
var VisualizationModel = (function (_super) {
@@ -41,9 +41,9 @@ import Backbone = require("aliasUsageInArray_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -31,8 +31,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInFunctionExpression_backbone");
var VisualizationModel = (function (_super) {
@@ -42,9 +42,9 @@ import Backbone = require("aliasUsageInFunctionExpression_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -35,8 +35,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInGenericFunction_backbone");
var VisualizationModel = (function (_super) {
@@ -57,9 +57,9 @@ import Backbone = require("aliasUsageInGenericFunction_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -37,8 +37,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInIndexerOfClass_backbone");
var VisualizationModel = (function (_super) {
@@ -50,9 +50,9 @@ import Backbone = require("aliasUsageInIndexerOfClass_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -32,8 +32,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInObjectLiteral_backbone");
var VisualizationModel = (function (_super) {
@@ -55,9 +55,9 @@ import Backbone = require("aliasUsageInObjectLiteral_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -35,8 +35,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInOrExpression_backbone");
var VisualizationModel = (function (_super) {
@@ -79,9 +79,9 @@ import Backbone = require("aliasUsageInOrExpression_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -35,8 +35,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInTypeArgumentOfExtendsClause_backbone");
var VisualizationModel = (function (_super) {
@@ -51,8 +50,7 @@ exports.VisualizationModel = VisualizationModel;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var moduleA = require("aliasUsageInTypeArgumentOfExtendsClause_moduleA");
var C = (function () {
@@ -25,7 +25,7 @@ class C<T extends IHasVisualizationModel> {
}
class D extends C<IHasVisualizationModel> {
>D : D
>C : C<T>
>C : C<IHasVisualizationModel>
>IHasVisualizationModel : IHasVisualizationModel
x = moduleA;
@@ -46,9 +46,9 @@ import Backbone = require("aliasUsageInTypeArgumentOfExtendsClause_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -31,8 +31,7 @@ exports.Model = Model;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("aliasUsageInVarAssignment_backbone");
var VisualizationModel = (function (_super) {
@@ -37,9 +37,9 @@ import Backbone = require("aliasUsageInVarAssignment_backbone");
export class VisualizationModel extends Backbone.Model {
>VisualizationModel : VisualizationModel
>Backbone.Model : any
>Backbone.Model : Backbone.Model
>Backbone : typeof Backbone
>Model : Backbone.Model
>Model : typeof Backbone.Model
// interesting stuff here
}
@@ -12,8 +12,7 @@ var t: number = f(x, x); // Not an error
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function () {
function A() {
@@ -1,9 +0,0 @@
tests/cases/compiler/anonymousClassExpression1.ts(2,19): error TS9003: 'class' expressions are not currently supported.
==== tests/cases/compiler/anonymousClassExpression1.ts (1 errors) ====
function f() {
return typeof class {} === "function";
~~~~~
!!! error TS9003: 'class' expressions are not currently supported.
}
@@ -6,8 +6,8 @@ function f() {
//// [anonymousClassExpression1.js]
function f() {
return typeof (function () {
function default_1() {
function class_1() {
}
return default_1;
return class_1;
})() === "function";
}
@@ -0,0 +1,6 @@
=== tests/cases/compiler/anonymousClassExpression1.ts ===
function f() {
>f : Symbol(f, Decl(anonymousClassExpression1.ts, 0, 0))
return typeof class {} === "function";
}
@@ -0,0 +1,10 @@
=== tests/cases/compiler/anonymousClassExpression1.ts ===
function f() {
>f : () => boolean
return typeof class {} === "function";
>typeof class {} === "function" : boolean
>typeof class {} : string
>class {} : typeof (Anonymous class)
>"function" : string
}
@@ -27,8 +27,7 @@ class Derived2<U extends String> extends Base2 { // error because of the prototy
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Base = (function () {
function Base() {
@@ -17,8 +17,7 @@ class Derived<U extends String> extends Base { // error
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Base = (function () {
function Base() {
@@ -89,8 +89,7 @@ arr_any = i1; // should be an error - is
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var C1 = (function () {
function C1() {
@@ -63,8 +63,7 @@ arr_any = i1; // should be an error - is
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var C1 = (function () {
function C1() {
@@ -111,8 +111,7 @@ module NonEmptyTypes {
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var EmptyTypes;
(function (EmptyTypes) {
@@ -55,8 +55,7 @@ var z3: { id: number }[] =
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Action = (function () {
function Action() {
+1 -2
View File
@@ -41,8 +41,7 @@ var context4: Base[] = [new Derived1(), new Derived1()];
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var arr1 = [[], [1], ['']];
var arr2 = [[null], [1], ['']];
@@ -29,8 +29,7 @@ var as = [list, myDerivedList]; // List<number>[]
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var List = (function () {
function List() {
@@ -17,7 +17,7 @@ class List<T> {
class DerivedList<U> extends List<U> {
>DerivedList : DerivedList<U>
>U : U
>List : List<T>
>List : List<U>
>U : U
foo: U;
@@ -100,8 +100,7 @@ var asserted2: any;
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
// Arrow function used in with statement
with (window) {
+19
View File
@@ -0,0 +1,19 @@
//// [asOperator1.ts]
var as = 43;
var x = undefined as number;
var y = (null as string).length;
var z = Date as any as string;
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
j = '';
//// [asOperator1.js]
var as = 43;
var x = undefined;
var y = null.length;
var z = Date;
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32;
j = '';
@@ -0,0 +1,24 @@
=== tests/cases/conformance/expressions/asOperator/asOperator1.ts ===
var as = 43;
>as : Symbol(as, Decl(asOperator1.ts, 0, 3))
var x = undefined as number;
>x : Symbol(x, Decl(asOperator1.ts, 1, 3))
>undefined : Symbol(undefined)
var y = (null as string).length;
>y : Symbol(y, Decl(asOperator1.ts, 2, 3))
>(null as string).length : Symbol(String.length, Decl(lib.d.ts, 414, 19))
>length : Symbol(String.length, Decl(lib.d.ts, 414, 19))
var z = Date as any as string;
>z : Symbol(z, Decl(asOperator1.ts, 3, 3))
>Date : Symbol(Date, Decl(lib.d.ts, 633, 23), Decl(lib.d.ts, 815, 11))
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
>j : Symbol(j, Decl(asOperator1.ts, 6, 3))
j = '';
>j : Symbol(j, Decl(asOperator1.ts, 6, 3))
@@ -0,0 +1,35 @@
=== tests/cases/conformance/expressions/asOperator/asOperator1.ts ===
var as = 43;
>as : number
>43 : number
var x = undefined as number;
>x : number
>undefined as number : number
>undefined : undefined
var y = (null as string).length;
>y : number
>(null as string).length : number
>(null as string) : string
>null as string : string
>null : null
>length : number
var z = Date as any as string;
>z : string
>Date as any as string : string
>Date as any : any
>Date : DateConstructor
// Should parse as a union type, not a bitwise 'or' of (32 as number) and 'string'
var j = 32 as number|string;
>j : string | number
>32 as number|string : string | number
>32 : number
j = '';
>j = '' : string
>j : string | number
>'' : string
@@ -0,0 +1,8 @@
tests/cases/conformance/expressions/asOperator/asOperator2.ts(1,9): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
==== tests/cases/conformance/expressions/asOperator/asOperator2.ts (1 errors) ====
var x = 23 as string;
~~~~~~~~~~~~
!!! error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
+6
View File
@@ -0,0 +1,6 @@
//// [asOperator2.ts]
var x = 23 as string;
//// [asOperator2.js]
var x = 23;
+22
View File
@@ -0,0 +1,22 @@
//// [asOperator3.ts]
declare function tag(...x: any[]): any;
var a = `${123 + 456 as number}`;
var b = `leading ${123 + 456 as number}`;
var c = `${123 + 456 as number} trailing`;
var d = `Hello ${123} World` as string;
var e = `Hello` as string;
var f = 1 + `${1} end of string` as string;
var g = tag `Hello ${123} World` as string;
var h = tag `Hello` as string;
//// [asOperator3.js]
var a = "" + 123 + 456;
var b = "leading " + 123 + 456;
var c = 123 + 456 + " trailing";
var d = ("Hello " + 123 + " World");
var e = "Hello";
var f = 1 + (1 + " end of string");
var g = (_a = ["Hello ", " World"], _a.raw = ["Hello ", " World"], tag(_a, 123));
var h = (_b = ["Hello"], _b.raw = ["Hello"], tag(_b));
var _a, _b;

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