Merge branch 'master' into refactor_module_resolution

This commit is contained in:
Andy Hanson
2016-10-26 08:27:34 -07:00
190 changed files with 64442 additions and 60127 deletions
+1 -1
View File
@@ -15,7 +15,7 @@ matrix:
branches:
only:
- master
- release-2.0
- release-2.1
install:
- npm uninstall typescript
+1 -1
View File
@@ -448,7 +448,7 @@ function compileFile(outFile, sources, prereqs, prefixes, useBuiltCompiler, opts
options += " --stripInternal";
}
options += " --target es5";
options += " --target es5 --noUnusedLocals --noUnusedParameters";
var cmd = host + " " + compilerPath + " " + options + " ";
cmd = cmd + sources.join(" ");
Executable
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Set up NVM
export NVM_DIR="/home/dotnet-bot/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh"
nvm install $1
npm uninstall typescript
npm uninstall tslint
npm install
npm update
npm test
+2
View File
@@ -39,3 +39,5 @@ function createCancellationToken(args) {
};
}
module.exports = createCancellationToken;
//# sourceMappingURL=cancellationToken.js.map
+11 -1
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// ECMAScript APIs
/////////////////////////////
@@ -4149,6 +4153,8 @@ interface Date {
*/
toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;
}
/////////////////////////////
/// IE DOM APIs
@@ -18774,12 +18780,16 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
type ScrollRestoration = "auto" | "manual";
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
// These are only available in a Web Worker
declare function importScripts(...urls: string[]): void;
/////////////////////////////
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// IE DOM APIs
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.dom.d.ts" />
interface DOMTokenList {
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare type PropertyKey = string | number | symbol;
interface Array<T> {
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.core.d.ts" />
/// <reference path="lib.es2015.collection.d.ts" />
/// <reference path="lib.es2015.generator.d.ts" />
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/**
* Represents the completion of an asynchronous operation
*/
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface Array<T> {
/**
* Determines whether an array includes a certain element, returning true or false as appropriate.
+4
View File
@@ -13,6 +13,10 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.d.ts" />
/// <reference path="lib.es2016.array.include.d.ts" />
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2016.d.ts" />
/// <reference path="lib.es2017.object.d.ts" />
/// <reference path="lib.es2017.sharedmemory.d.ts" />
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable properties of an object
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/// <reference path="lib.es2015.symbol.d.ts" />
/// <reference path="lib.es2015.symbol.wellknown.d.ts" />
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// ECMAScript APIs
/////////////////////////////
+37 -7
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// ECMAScript APIs
/////////////////////////////
@@ -4149,6 +4153,8 @@ interface Date {
*/
toLocaleTimeString(locales?: string | string[], options?: Intl.DateTimeFormatOptions): string;
}
declare type PropertyKey = string | number | symbol;
interface Array<T> {
@@ -4673,6 +4679,8 @@ interface StringConstructor {
*/
raw(template: TemplateStringsArray, ...substitutions: any[]): string;
}
interface Map<K, V> {
clear(): void;
delete(key: K): boolean;
@@ -4745,6 +4753,8 @@ interface WeakSetConstructor {
readonly prototype: WeakSet<any>;
}
declare var WeakSet: WeakSetConstructor;
interface GeneratorFunction extends Function { }
interface GeneratorFunctionConstructor {
@@ -4757,6 +4767,8 @@ interface GeneratorFunctionConstructor {
readonly prototype: GeneratorFunction;
}
declare var GeneratorFunction: GeneratorFunctionConstructor;
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
@@ -5201,7 +5213,9 @@ interface Float64ArrayConstructor {
* @param thisArg Value of 'this' used to invoke the mapfn.
*/
from(arrayLike: Iterable<number>, mapfn?: (v: number, k: number) => number, thisArg?: any): Float64Array;
}/**
}
/**
* Represents the completion of an asynchronous operation
*/
interface Promise<T> {
@@ -5454,7 +5468,9 @@ interface PromiseConstructor {
resolve(): Promise<void>;
}
declare var Promise: PromiseConstructor;interface ProxyHandler<T> {
declare var Promise: PromiseConstructor;
interface ProxyHandler<T> {
getPrototypeOf? (target: T): any;
setPrototypeOf? (target: T, v: any): boolean;
isExtensible? (target: T): boolean;
@@ -5475,7 +5491,9 @@ interface ProxyConstructor {
revocable<T>(target: T, handler: ProxyHandler<T>): { proxy: T; revoke: () => void; };
new <T>(target: T, handler: ProxyHandler<T>): T
}
declare var Proxy: ProxyConstructor;declare namespace Reflect {
declare var Proxy: ProxyConstructor;
declare namespace Reflect {
function apply(target: Function, thisArgument: any, argumentsList: ArrayLike<any>): any;
function construct(target: Function, argumentsList: ArrayLike<any>, newTarget?: any): any;
function defineProperty(target: any, propertyKey: PropertyKey, attributes: PropertyDescriptor): boolean;
@@ -5489,7 +5507,9 @@ declare var Proxy: ProxyConstructor;declare namespace Reflect {
function preventExtensions(target: any): boolean;
function set(target: any, propertyKey: PropertyKey, value: any, receiver?: any): boolean;
function setPrototypeOf(target: any, proto: any): boolean;
}interface Symbol {
}
interface Symbol {
/** Returns a string representation of an object. */
toString(): string;
@@ -5524,7 +5544,9 @@ interface SymbolConstructor {
keyFor(sym: symbol): string | undefined;
}
declare var Symbol: SymbolConstructor;/// <reference path="lib.es2015.symbol.d.ts" />
declare var Symbol: SymbolConstructor;
/// <reference path="lib.es2015.symbol.d.ts" />
interface SymbolConstructor {
/**
@@ -5850,7 +5872,9 @@ interface Float32Array {
*/
interface Float64Array {
readonly [Symbol.toStringTag]: "Float64Array";
}
}
/////////////////////////////
/// IE DOM APIs
/////////////////////////////
@@ -20475,12 +20499,16 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest";
type IDBValidKey = number | string | Date | IDBArrayKey;
type BufferSource = ArrayBuffer | ArrayBufferView;
type MouseWheelEvent = WheelEvent;
type ScrollRestoration = "auto" | "manual";
type ScrollRestoration = "auto" | "manual";
/////////////////////////////
/// WorkerGlobalScope APIs
/////////////////////////////
// These are only available in a Web Worker
declare function importScripts(...urls: string[]): void;
/////////////////////////////
@@ -20772,6 +20800,8 @@ interface DateConstructor {
interface Date {
getVarDate: () => VarDate;
}
/// <reference path="lib.dom.d.ts" />
interface DOMTokenList {
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
+4
View File
@@ -13,7 +13,11 @@ See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
/////////////////////////////
/// IE Worker APIs
+9355 -7693
View File
File diff suppressed because it is too large Load Diff
+11868 -10039
View File
File diff suppressed because one or more lines are too long
+1180 -8158
View File
File diff suppressed because one or more lines are too long
+11861 -10034
View File
File diff suppressed because one or more lines are too long
+267 -261
View File
@@ -47,241 +47,241 @@ declare namespace ts {
ConflictMarkerTrivia = 7,
NumericLiteral = 8,
StringLiteral = 9,
RegularExpressionLiteral = 10,
NoSubstitutionTemplateLiteral = 11,
TemplateHead = 12,
TemplateMiddle = 13,
TemplateTail = 14,
OpenBraceToken = 15,
CloseBraceToken = 16,
OpenParenToken = 17,
CloseParenToken = 18,
OpenBracketToken = 19,
CloseBracketToken = 20,
DotToken = 21,
DotDotDotToken = 22,
SemicolonToken = 23,
CommaToken = 24,
LessThanToken = 25,
LessThanSlashToken = 26,
GreaterThanToken = 27,
LessThanEqualsToken = 28,
GreaterThanEqualsToken = 29,
EqualsEqualsToken = 30,
ExclamationEqualsToken = 31,
EqualsEqualsEqualsToken = 32,
ExclamationEqualsEqualsToken = 33,
EqualsGreaterThanToken = 34,
PlusToken = 35,
MinusToken = 36,
AsteriskToken = 37,
AsteriskAsteriskToken = 38,
SlashToken = 39,
PercentToken = 40,
PlusPlusToken = 41,
MinusMinusToken = 42,
LessThanLessThanToken = 43,
GreaterThanGreaterThanToken = 44,
GreaterThanGreaterThanGreaterThanToken = 45,
AmpersandToken = 46,
BarToken = 47,
CaretToken = 48,
ExclamationToken = 49,
TildeToken = 50,
AmpersandAmpersandToken = 51,
BarBarToken = 52,
QuestionToken = 53,
ColonToken = 54,
AtToken = 55,
EqualsToken = 56,
PlusEqualsToken = 57,
MinusEqualsToken = 58,
AsteriskEqualsToken = 59,
AsteriskAsteriskEqualsToken = 60,
SlashEqualsToken = 61,
PercentEqualsToken = 62,
LessThanLessThanEqualsToken = 63,
GreaterThanGreaterThanEqualsToken = 64,
GreaterThanGreaterThanGreaterThanEqualsToken = 65,
AmpersandEqualsToken = 66,
BarEqualsToken = 67,
CaretEqualsToken = 68,
Identifier = 69,
BreakKeyword = 70,
CaseKeyword = 71,
CatchKeyword = 72,
ClassKeyword = 73,
ConstKeyword = 74,
ContinueKeyword = 75,
DebuggerKeyword = 76,
DefaultKeyword = 77,
DeleteKeyword = 78,
DoKeyword = 79,
ElseKeyword = 80,
EnumKeyword = 81,
ExportKeyword = 82,
ExtendsKeyword = 83,
FalseKeyword = 84,
FinallyKeyword = 85,
ForKeyword = 86,
FunctionKeyword = 87,
IfKeyword = 88,
ImportKeyword = 89,
InKeyword = 90,
InstanceOfKeyword = 91,
NewKeyword = 92,
NullKeyword = 93,
ReturnKeyword = 94,
SuperKeyword = 95,
SwitchKeyword = 96,
ThisKeyword = 97,
ThrowKeyword = 98,
TrueKeyword = 99,
TryKeyword = 100,
TypeOfKeyword = 101,
VarKeyword = 102,
VoidKeyword = 103,
WhileKeyword = 104,
WithKeyword = 105,
ImplementsKeyword = 106,
InterfaceKeyword = 107,
LetKeyword = 108,
PackageKeyword = 109,
PrivateKeyword = 110,
ProtectedKeyword = 111,
PublicKeyword = 112,
StaticKeyword = 113,
YieldKeyword = 114,
AbstractKeyword = 115,
AsKeyword = 116,
AnyKeyword = 117,
AsyncKeyword = 118,
AwaitKeyword = 119,
BooleanKeyword = 120,
ConstructorKeyword = 121,
DeclareKeyword = 122,
GetKeyword = 123,
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
NeverKeyword = 127,
ReadonlyKeyword = 128,
RequireKeyword = 129,
NumberKeyword = 130,
SetKeyword = 131,
StringKeyword = 132,
SymbolKeyword = 133,
TypeKeyword = 134,
UndefinedKeyword = 135,
FromKeyword = 136,
GlobalKeyword = 137,
OfKeyword = 138,
QualifiedName = 139,
ComputedPropertyName = 140,
TypeParameter = 141,
Parameter = 142,
Decorator = 143,
PropertySignature = 144,
PropertyDeclaration = 145,
MethodSignature = 146,
MethodDeclaration = 147,
Constructor = 148,
GetAccessor = 149,
SetAccessor = 150,
CallSignature = 151,
ConstructSignature = 152,
IndexSignature = 153,
TypePredicate = 154,
TypeReference = 155,
FunctionType = 156,
ConstructorType = 157,
TypeQuery = 158,
TypeLiteral = 159,
ArrayType = 160,
TupleType = 161,
UnionType = 162,
IntersectionType = 163,
ParenthesizedType = 164,
ThisType = 165,
LiteralType = 166,
ObjectBindingPattern = 167,
ArrayBindingPattern = 168,
BindingElement = 169,
ArrayLiteralExpression = 170,
ObjectLiteralExpression = 171,
PropertyAccessExpression = 172,
ElementAccessExpression = 173,
CallExpression = 174,
NewExpression = 175,
TaggedTemplateExpression = 176,
TypeAssertionExpression = 177,
ParenthesizedExpression = 178,
FunctionExpression = 179,
ArrowFunction = 180,
DeleteExpression = 181,
TypeOfExpression = 182,
VoidExpression = 183,
AwaitExpression = 184,
PrefixUnaryExpression = 185,
PostfixUnaryExpression = 186,
BinaryExpression = 187,
ConditionalExpression = 188,
TemplateExpression = 189,
YieldExpression = 190,
SpreadElementExpression = 191,
ClassExpression = 192,
OmittedExpression = 193,
ExpressionWithTypeArguments = 194,
AsExpression = 195,
NonNullExpression = 196,
TemplateSpan = 197,
SemicolonClassElement = 198,
Block = 199,
VariableStatement = 200,
EmptyStatement = 201,
ExpressionStatement = 202,
IfStatement = 203,
DoStatement = 204,
WhileStatement = 205,
ForStatement = 206,
ForInStatement = 207,
ForOfStatement = 208,
ContinueStatement = 209,
BreakStatement = 210,
ReturnStatement = 211,
WithStatement = 212,
SwitchStatement = 213,
LabeledStatement = 214,
ThrowStatement = 215,
TryStatement = 216,
DebuggerStatement = 217,
VariableDeclaration = 218,
VariableDeclarationList = 219,
FunctionDeclaration = 220,
ClassDeclaration = 221,
InterfaceDeclaration = 222,
TypeAliasDeclaration = 223,
EnumDeclaration = 224,
ModuleDeclaration = 225,
ModuleBlock = 226,
CaseBlock = 227,
NamespaceExportDeclaration = 228,
ImportEqualsDeclaration = 229,
ImportDeclaration = 230,
ImportClause = 231,
NamespaceImport = 232,
NamedImports = 233,
ImportSpecifier = 234,
ExportAssignment = 235,
ExportDeclaration = 236,
NamedExports = 237,
ExportSpecifier = 238,
MissingDeclaration = 239,
ExternalModuleReference = 240,
JsxElement = 241,
JsxSelfClosingElement = 242,
JsxOpeningElement = 243,
JsxText = 244,
JsxText = 10,
RegularExpressionLiteral = 11,
NoSubstitutionTemplateLiteral = 12,
TemplateHead = 13,
TemplateMiddle = 14,
TemplateTail = 15,
OpenBraceToken = 16,
CloseBraceToken = 17,
OpenParenToken = 18,
CloseParenToken = 19,
OpenBracketToken = 20,
CloseBracketToken = 21,
DotToken = 22,
DotDotDotToken = 23,
SemicolonToken = 24,
CommaToken = 25,
LessThanToken = 26,
LessThanSlashToken = 27,
GreaterThanToken = 28,
LessThanEqualsToken = 29,
GreaterThanEqualsToken = 30,
EqualsEqualsToken = 31,
ExclamationEqualsToken = 32,
EqualsEqualsEqualsToken = 33,
ExclamationEqualsEqualsToken = 34,
EqualsGreaterThanToken = 35,
PlusToken = 36,
MinusToken = 37,
AsteriskToken = 38,
AsteriskAsteriskToken = 39,
SlashToken = 40,
PercentToken = 41,
PlusPlusToken = 42,
MinusMinusToken = 43,
LessThanLessThanToken = 44,
GreaterThanGreaterThanToken = 45,
GreaterThanGreaterThanGreaterThanToken = 46,
AmpersandToken = 47,
BarToken = 48,
CaretToken = 49,
ExclamationToken = 50,
TildeToken = 51,
AmpersandAmpersandToken = 52,
BarBarToken = 53,
QuestionToken = 54,
ColonToken = 55,
AtToken = 56,
EqualsToken = 57,
PlusEqualsToken = 58,
MinusEqualsToken = 59,
AsteriskEqualsToken = 60,
AsteriskAsteriskEqualsToken = 61,
SlashEqualsToken = 62,
PercentEqualsToken = 63,
LessThanLessThanEqualsToken = 64,
GreaterThanGreaterThanEqualsToken = 65,
GreaterThanGreaterThanGreaterThanEqualsToken = 66,
AmpersandEqualsToken = 67,
BarEqualsToken = 68,
CaretEqualsToken = 69,
Identifier = 70,
BreakKeyword = 71,
CaseKeyword = 72,
CatchKeyword = 73,
ClassKeyword = 74,
ConstKeyword = 75,
ContinueKeyword = 76,
DebuggerKeyword = 77,
DefaultKeyword = 78,
DeleteKeyword = 79,
DoKeyword = 80,
ElseKeyword = 81,
EnumKeyword = 82,
ExportKeyword = 83,
ExtendsKeyword = 84,
FalseKeyword = 85,
FinallyKeyword = 86,
ForKeyword = 87,
FunctionKeyword = 88,
IfKeyword = 89,
ImportKeyword = 90,
InKeyword = 91,
InstanceOfKeyword = 92,
NewKeyword = 93,
NullKeyword = 94,
ReturnKeyword = 95,
SuperKeyword = 96,
SwitchKeyword = 97,
ThisKeyword = 98,
ThrowKeyword = 99,
TrueKeyword = 100,
TryKeyword = 101,
TypeOfKeyword = 102,
VarKeyword = 103,
VoidKeyword = 104,
WhileKeyword = 105,
WithKeyword = 106,
ImplementsKeyword = 107,
InterfaceKeyword = 108,
LetKeyword = 109,
PackageKeyword = 110,
PrivateKeyword = 111,
ProtectedKeyword = 112,
PublicKeyword = 113,
StaticKeyword = 114,
YieldKeyword = 115,
AbstractKeyword = 116,
AsKeyword = 117,
AnyKeyword = 118,
AsyncKeyword = 119,
AwaitKeyword = 120,
BooleanKeyword = 121,
ConstructorKeyword = 122,
DeclareKeyword = 123,
GetKeyword = 124,
IsKeyword = 125,
ModuleKeyword = 126,
NamespaceKeyword = 127,
NeverKeyword = 128,
ReadonlyKeyword = 129,
RequireKeyword = 130,
NumberKeyword = 131,
SetKeyword = 132,
StringKeyword = 133,
SymbolKeyword = 134,
TypeKeyword = 135,
UndefinedKeyword = 136,
FromKeyword = 137,
GlobalKeyword = 138,
OfKeyword = 139,
QualifiedName = 140,
ComputedPropertyName = 141,
TypeParameter = 142,
Parameter = 143,
Decorator = 144,
PropertySignature = 145,
PropertyDeclaration = 146,
MethodSignature = 147,
MethodDeclaration = 148,
Constructor = 149,
GetAccessor = 150,
SetAccessor = 151,
CallSignature = 152,
ConstructSignature = 153,
IndexSignature = 154,
TypePredicate = 155,
TypeReference = 156,
FunctionType = 157,
ConstructorType = 158,
TypeQuery = 159,
TypeLiteral = 160,
ArrayType = 161,
TupleType = 162,
UnionType = 163,
IntersectionType = 164,
ParenthesizedType = 165,
ThisType = 166,
LiteralType = 167,
ObjectBindingPattern = 168,
ArrayBindingPattern = 169,
BindingElement = 170,
ArrayLiteralExpression = 171,
ObjectLiteralExpression = 172,
PropertyAccessExpression = 173,
ElementAccessExpression = 174,
CallExpression = 175,
NewExpression = 176,
TaggedTemplateExpression = 177,
TypeAssertionExpression = 178,
ParenthesizedExpression = 179,
FunctionExpression = 180,
ArrowFunction = 181,
DeleteExpression = 182,
TypeOfExpression = 183,
VoidExpression = 184,
AwaitExpression = 185,
PrefixUnaryExpression = 186,
PostfixUnaryExpression = 187,
BinaryExpression = 188,
ConditionalExpression = 189,
TemplateExpression = 190,
YieldExpression = 191,
SpreadElementExpression = 192,
ClassExpression = 193,
OmittedExpression = 194,
ExpressionWithTypeArguments = 195,
AsExpression = 196,
NonNullExpression = 197,
TemplateSpan = 198,
SemicolonClassElement = 199,
Block = 200,
VariableStatement = 201,
EmptyStatement = 202,
ExpressionStatement = 203,
IfStatement = 204,
DoStatement = 205,
WhileStatement = 206,
ForStatement = 207,
ForInStatement = 208,
ForOfStatement = 209,
ContinueStatement = 210,
BreakStatement = 211,
ReturnStatement = 212,
WithStatement = 213,
SwitchStatement = 214,
LabeledStatement = 215,
ThrowStatement = 216,
TryStatement = 217,
DebuggerStatement = 218,
VariableDeclaration = 219,
VariableDeclarationList = 220,
FunctionDeclaration = 221,
ClassDeclaration = 222,
InterfaceDeclaration = 223,
TypeAliasDeclaration = 224,
EnumDeclaration = 225,
ModuleDeclaration = 226,
ModuleBlock = 227,
CaseBlock = 228,
NamespaceExportDeclaration = 229,
ImportEqualsDeclaration = 230,
ImportDeclaration = 231,
ImportClause = 232,
NamespaceImport = 233,
NamedImports = 234,
ImportSpecifier = 235,
ExportAssignment = 236,
ExportDeclaration = 237,
NamedExports = 238,
ExportSpecifier = 239,
MissingDeclaration = 240,
ExternalModuleReference = 241,
JsxElement = 242,
JsxSelfClosingElement = 243,
JsxOpeningElement = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
@@ -327,31 +327,31 @@ declare namespace ts {
NotEmittedStatement = 287,
PartiallyEmittedExpression = 288,
Count = 289,
FirstAssignment = 56,
LastAssignment = 68,
FirstCompoundAssignment = 57,
LastCompoundAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 138,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 154,
LastTypeNode = 166,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstAssignment = 57,
LastAssignment = 69,
FirstCompoundAssignment = 58,
LastCompoundAssignment = 69,
FirstReservedWord = 71,
LastReservedWord = 106,
FirstKeyword = 71,
LastKeyword = 139,
FirstFutureReservedWord = 107,
LastFutureReservedWord = 115,
FirstTypeNode = 155,
LastTypeNode = 167,
FirstPunctuation = 16,
LastPunctuation = 69,
FirstToken = 0,
LastToken = 138,
LastToken = 139,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
LastLiteralToken = 11,
FirstTemplateToken = 11,
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 139,
LastLiteralToken = 12,
FirstTemplateToken = 12,
LastTemplateToken = 15,
FirstBinaryOperator = 26,
LastBinaryOperator = 69,
FirstNode = 140,
FirstJSDocNode = 257,
LastJSDocNode = 282,
FirstJSDocTagNode = 273,
@@ -406,6 +406,7 @@ declare namespace ts {
AccessibilityModifier = 28,
ParameterPropertyModifier = 92,
NonPublicAccessibilityModifier = 24,
TypeScriptModifier = 2270,
}
enum JsxFlags {
None = 0,
@@ -1351,8 +1352,9 @@ declare namespace ts {
TrueCondition = 32,
FalseCondition = 64,
SwitchClause = 128,
Referenced = 256,
Shared = 512,
ArrayMutation = 256,
Referenced = 512,
Shared = 1024,
Label = 12,
Condition = 96,
}
@@ -1380,6 +1382,10 @@ declare namespace ts {
clauseEnd: number;
antecedent: FlowNode;
}
interface FlowArrayMutation extends FlowNode {
node: CallExpression | BinaryExpression;
antecedent: FlowNode;
}
type FlowType = Type | IncompleteType;
interface IncompleteType {
flags: TypeFlags;
@@ -1913,7 +1919,6 @@ declare namespace ts {
AMD = 2,
UMD = 3,
System = 4,
ES6 = 5,
ES2015 = 5,
}
enum JsxEmit {
@@ -1939,9 +1944,10 @@ declare namespace ts {
enum ScriptTarget {
ES3 = 0,
ES5 = 1,
ES6 = 2,
ES2015 = 2,
Latest = 2,
ES2016 = 3,
ES2017 = 4,
Latest = 4,
}
enum LanguageVariant {
Standard = 0,
+11950 -11233
View File
File diff suppressed because it is too large Load Diff
+267 -261
View File
@@ -47,241 +47,241 @@ declare namespace ts {
ConflictMarkerTrivia = 7,
NumericLiteral = 8,
StringLiteral = 9,
RegularExpressionLiteral = 10,
NoSubstitutionTemplateLiteral = 11,
TemplateHead = 12,
TemplateMiddle = 13,
TemplateTail = 14,
OpenBraceToken = 15,
CloseBraceToken = 16,
OpenParenToken = 17,
CloseParenToken = 18,
OpenBracketToken = 19,
CloseBracketToken = 20,
DotToken = 21,
DotDotDotToken = 22,
SemicolonToken = 23,
CommaToken = 24,
LessThanToken = 25,
LessThanSlashToken = 26,
GreaterThanToken = 27,
LessThanEqualsToken = 28,
GreaterThanEqualsToken = 29,
EqualsEqualsToken = 30,
ExclamationEqualsToken = 31,
EqualsEqualsEqualsToken = 32,
ExclamationEqualsEqualsToken = 33,
EqualsGreaterThanToken = 34,
PlusToken = 35,
MinusToken = 36,
AsteriskToken = 37,
AsteriskAsteriskToken = 38,
SlashToken = 39,
PercentToken = 40,
PlusPlusToken = 41,
MinusMinusToken = 42,
LessThanLessThanToken = 43,
GreaterThanGreaterThanToken = 44,
GreaterThanGreaterThanGreaterThanToken = 45,
AmpersandToken = 46,
BarToken = 47,
CaretToken = 48,
ExclamationToken = 49,
TildeToken = 50,
AmpersandAmpersandToken = 51,
BarBarToken = 52,
QuestionToken = 53,
ColonToken = 54,
AtToken = 55,
EqualsToken = 56,
PlusEqualsToken = 57,
MinusEqualsToken = 58,
AsteriskEqualsToken = 59,
AsteriskAsteriskEqualsToken = 60,
SlashEqualsToken = 61,
PercentEqualsToken = 62,
LessThanLessThanEqualsToken = 63,
GreaterThanGreaterThanEqualsToken = 64,
GreaterThanGreaterThanGreaterThanEqualsToken = 65,
AmpersandEqualsToken = 66,
BarEqualsToken = 67,
CaretEqualsToken = 68,
Identifier = 69,
BreakKeyword = 70,
CaseKeyword = 71,
CatchKeyword = 72,
ClassKeyword = 73,
ConstKeyword = 74,
ContinueKeyword = 75,
DebuggerKeyword = 76,
DefaultKeyword = 77,
DeleteKeyword = 78,
DoKeyword = 79,
ElseKeyword = 80,
EnumKeyword = 81,
ExportKeyword = 82,
ExtendsKeyword = 83,
FalseKeyword = 84,
FinallyKeyword = 85,
ForKeyword = 86,
FunctionKeyword = 87,
IfKeyword = 88,
ImportKeyword = 89,
InKeyword = 90,
InstanceOfKeyword = 91,
NewKeyword = 92,
NullKeyword = 93,
ReturnKeyword = 94,
SuperKeyword = 95,
SwitchKeyword = 96,
ThisKeyword = 97,
ThrowKeyword = 98,
TrueKeyword = 99,
TryKeyword = 100,
TypeOfKeyword = 101,
VarKeyword = 102,
VoidKeyword = 103,
WhileKeyword = 104,
WithKeyword = 105,
ImplementsKeyword = 106,
InterfaceKeyword = 107,
LetKeyword = 108,
PackageKeyword = 109,
PrivateKeyword = 110,
ProtectedKeyword = 111,
PublicKeyword = 112,
StaticKeyword = 113,
YieldKeyword = 114,
AbstractKeyword = 115,
AsKeyword = 116,
AnyKeyword = 117,
AsyncKeyword = 118,
AwaitKeyword = 119,
BooleanKeyword = 120,
ConstructorKeyword = 121,
DeclareKeyword = 122,
GetKeyword = 123,
IsKeyword = 124,
ModuleKeyword = 125,
NamespaceKeyword = 126,
NeverKeyword = 127,
ReadonlyKeyword = 128,
RequireKeyword = 129,
NumberKeyword = 130,
SetKeyword = 131,
StringKeyword = 132,
SymbolKeyword = 133,
TypeKeyword = 134,
UndefinedKeyword = 135,
FromKeyword = 136,
GlobalKeyword = 137,
OfKeyword = 138,
QualifiedName = 139,
ComputedPropertyName = 140,
TypeParameter = 141,
Parameter = 142,
Decorator = 143,
PropertySignature = 144,
PropertyDeclaration = 145,
MethodSignature = 146,
MethodDeclaration = 147,
Constructor = 148,
GetAccessor = 149,
SetAccessor = 150,
CallSignature = 151,
ConstructSignature = 152,
IndexSignature = 153,
TypePredicate = 154,
TypeReference = 155,
FunctionType = 156,
ConstructorType = 157,
TypeQuery = 158,
TypeLiteral = 159,
ArrayType = 160,
TupleType = 161,
UnionType = 162,
IntersectionType = 163,
ParenthesizedType = 164,
ThisType = 165,
LiteralType = 166,
ObjectBindingPattern = 167,
ArrayBindingPattern = 168,
BindingElement = 169,
ArrayLiteralExpression = 170,
ObjectLiteralExpression = 171,
PropertyAccessExpression = 172,
ElementAccessExpression = 173,
CallExpression = 174,
NewExpression = 175,
TaggedTemplateExpression = 176,
TypeAssertionExpression = 177,
ParenthesizedExpression = 178,
FunctionExpression = 179,
ArrowFunction = 180,
DeleteExpression = 181,
TypeOfExpression = 182,
VoidExpression = 183,
AwaitExpression = 184,
PrefixUnaryExpression = 185,
PostfixUnaryExpression = 186,
BinaryExpression = 187,
ConditionalExpression = 188,
TemplateExpression = 189,
YieldExpression = 190,
SpreadElementExpression = 191,
ClassExpression = 192,
OmittedExpression = 193,
ExpressionWithTypeArguments = 194,
AsExpression = 195,
NonNullExpression = 196,
TemplateSpan = 197,
SemicolonClassElement = 198,
Block = 199,
VariableStatement = 200,
EmptyStatement = 201,
ExpressionStatement = 202,
IfStatement = 203,
DoStatement = 204,
WhileStatement = 205,
ForStatement = 206,
ForInStatement = 207,
ForOfStatement = 208,
ContinueStatement = 209,
BreakStatement = 210,
ReturnStatement = 211,
WithStatement = 212,
SwitchStatement = 213,
LabeledStatement = 214,
ThrowStatement = 215,
TryStatement = 216,
DebuggerStatement = 217,
VariableDeclaration = 218,
VariableDeclarationList = 219,
FunctionDeclaration = 220,
ClassDeclaration = 221,
InterfaceDeclaration = 222,
TypeAliasDeclaration = 223,
EnumDeclaration = 224,
ModuleDeclaration = 225,
ModuleBlock = 226,
CaseBlock = 227,
NamespaceExportDeclaration = 228,
ImportEqualsDeclaration = 229,
ImportDeclaration = 230,
ImportClause = 231,
NamespaceImport = 232,
NamedImports = 233,
ImportSpecifier = 234,
ExportAssignment = 235,
ExportDeclaration = 236,
NamedExports = 237,
ExportSpecifier = 238,
MissingDeclaration = 239,
ExternalModuleReference = 240,
JsxElement = 241,
JsxSelfClosingElement = 242,
JsxOpeningElement = 243,
JsxText = 244,
JsxText = 10,
RegularExpressionLiteral = 11,
NoSubstitutionTemplateLiteral = 12,
TemplateHead = 13,
TemplateMiddle = 14,
TemplateTail = 15,
OpenBraceToken = 16,
CloseBraceToken = 17,
OpenParenToken = 18,
CloseParenToken = 19,
OpenBracketToken = 20,
CloseBracketToken = 21,
DotToken = 22,
DotDotDotToken = 23,
SemicolonToken = 24,
CommaToken = 25,
LessThanToken = 26,
LessThanSlashToken = 27,
GreaterThanToken = 28,
LessThanEqualsToken = 29,
GreaterThanEqualsToken = 30,
EqualsEqualsToken = 31,
ExclamationEqualsToken = 32,
EqualsEqualsEqualsToken = 33,
ExclamationEqualsEqualsToken = 34,
EqualsGreaterThanToken = 35,
PlusToken = 36,
MinusToken = 37,
AsteriskToken = 38,
AsteriskAsteriskToken = 39,
SlashToken = 40,
PercentToken = 41,
PlusPlusToken = 42,
MinusMinusToken = 43,
LessThanLessThanToken = 44,
GreaterThanGreaterThanToken = 45,
GreaterThanGreaterThanGreaterThanToken = 46,
AmpersandToken = 47,
BarToken = 48,
CaretToken = 49,
ExclamationToken = 50,
TildeToken = 51,
AmpersandAmpersandToken = 52,
BarBarToken = 53,
QuestionToken = 54,
ColonToken = 55,
AtToken = 56,
EqualsToken = 57,
PlusEqualsToken = 58,
MinusEqualsToken = 59,
AsteriskEqualsToken = 60,
AsteriskAsteriskEqualsToken = 61,
SlashEqualsToken = 62,
PercentEqualsToken = 63,
LessThanLessThanEqualsToken = 64,
GreaterThanGreaterThanEqualsToken = 65,
GreaterThanGreaterThanGreaterThanEqualsToken = 66,
AmpersandEqualsToken = 67,
BarEqualsToken = 68,
CaretEqualsToken = 69,
Identifier = 70,
BreakKeyword = 71,
CaseKeyword = 72,
CatchKeyword = 73,
ClassKeyword = 74,
ConstKeyword = 75,
ContinueKeyword = 76,
DebuggerKeyword = 77,
DefaultKeyword = 78,
DeleteKeyword = 79,
DoKeyword = 80,
ElseKeyword = 81,
EnumKeyword = 82,
ExportKeyword = 83,
ExtendsKeyword = 84,
FalseKeyword = 85,
FinallyKeyword = 86,
ForKeyword = 87,
FunctionKeyword = 88,
IfKeyword = 89,
ImportKeyword = 90,
InKeyword = 91,
InstanceOfKeyword = 92,
NewKeyword = 93,
NullKeyword = 94,
ReturnKeyword = 95,
SuperKeyword = 96,
SwitchKeyword = 97,
ThisKeyword = 98,
ThrowKeyword = 99,
TrueKeyword = 100,
TryKeyword = 101,
TypeOfKeyword = 102,
VarKeyword = 103,
VoidKeyword = 104,
WhileKeyword = 105,
WithKeyword = 106,
ImplementsKeyword = 107,
InterfaceKeyword = 108,
LetKeyword = 109,
PackageKeyword = 110,
PrivateKeyword = 111,
ProtectedKeyword = 112,
PublicKeyword = 113,
StaticKeyword = 114,
YieldKeyword = 115,
AbstractKeyword = 116,
AsKeyword = 117,
AnyKeyword = 118,
AsyncKeyword = 119,
AwaitKeyword = 120,
BooleanKeyword = 121,
ConstructorKeyword = 122,
DeclareKeyword = 123,
GetKeyword = 124,
IsKeyword = 125,
ModuleKeyword = 126,
NamespaceKeyword = 127,
NeverKeyword = 128,
ReadonlyKeyword = 129,
RequireKeyword = 130,
NumberKeyword = 131,
SetKeyword = 132,
StringKeyword = 133,
SymbolKeyword = 134,
TypeKeyword = 135,
UndefinedKeyword = 136,
FromKeyword = 137,
GlobalKeyword = 138,
OfKeyword = 139,
QualifiedName = 140,
ComputedPropertyName = 141,
TypeParameter = 142,
Parameter = 143,
Decorator = 144,
PropertySignature = 145,
PropertyDeclaration = 146,
MethodSignature = 147,
MethodDeclaration = 148,
Constructor = 149,
GetAccessor = 150,
SetAccessor = 151,
CallSignature = 152,
ConstructSignature = 153,
IndexSignature = 154,
TypePredicate = 155,
TypeReference = 156,
FunctionType = 157,
ConstructorType = 158,
TypeQuery = 159,
TypeLiteral = 160,
ArrayType = 161,
TupleType = 162,
UnionType = 163,
IntersectionType = 164,
ParenthesizedType = 165,
ThisType = 166,
LiteralType = 167,
ObjectBindingPattern = 168,
ArrayBindingPattern = 169,
BindingElement = 170,
ArrayLiteralExpression = 171,
ObjectLiteralExpression = 172,
PropertyAccessExpression = 173,
ElementAccessExpression = 174,
CallExpression = 175,
NewExpression = 176,
TaggedTemplateExpression = 177,
TypeAssertionExpression = 178,
ParenthesizedExpression = 179,
FunctionExpression = 180,
ArrowFunction = 181,
DeleteExpression = 182,
TypeOfExpression = 183,
VoidExpression = 184,
AwaitExpression = 185,
PrefixUnaryExpression = 186,
PostfixUnaryExpression = 187,
BinaryExpression = 188,
ConditionalExpression = 189,
TemplateExpression = 190,
YieldExpression = 191,
SpreadElementExpression = 192,
ClassExpression = 193,
OmittedExpression = 194,
ExpressionWithTypeArguments = 195,
AsExpression = 196,
NonNullExpression = 197,
TemplateSpan = 198,
SemicolonClassElement = 199,
Block = 200,
VariableStatement = 201,
EmptyStatement = 202,
ExpressionStatement = 203,
IfStatement = 204,
DoStatement = 205,
WhileStatement = 206,
ForStatement = 207,
ForInStatement = 208,
ForOfStatement = 209,
ContinueStatement = 210,
BreakStatement = 211,
ReturnStatement = 212,
WithStatement = 213,
SwitchStatement = 214,
LabeledStatement = 215,
ThrowStatement = 216,
TryStatement = 217,
DebuggerStatement = 218,
VariableDeclaration = 219,
VariableDeclarationList = 220,
FunctionDeclaration = 221,
ClassDeclaration = 222,
InterfaceDeclaration = 223,
TypeAliasDeclaration = 224,
EnumDeclaration = 225,
ModuleDeclaration = 226,
ModuleBlock = 227,
CaseBlock = 228,
NamespaceExportDeclaration = 229,
ImportEqualsDeclaration = 230,
ImportDeclaration = 231,
ImportClause = 232,
NamespaceImport = 233,
NamedImports = 234,
ImportSpecifier = 235,
ExportAssignment = 236,
ExportDeclaration = 237,
NamedExports = 238,
ExportSpecifier = 239,
MissingDeclaration = 240,
ExternalModuleReference = 241,
JsxElement = 242,
JsxSelfClosingElement = 243,
JsxOpeningElement = 244,
JsxClosingElement = 245,
JsxAttribute = 246,
JsxSpreadAttribute = 247,
@@ -327,31 +327,31 @@ declare namespace ts {
NotEmittedStatement = 287,
PartiallyEmittedExpression = 288,
Count = 289,
FirstAssignment = 56,
LastAssignment = 68,
FirstCompoundAssignment = 57,
LastCompoundAssignment = 68,
FirstReservedWord = 70,
LastReservedWord = 105,
FirstKeyword = 70,
LastKeyword = 138,
FirstFutureReservedWord = 106,
LastFutureReservedWord = 114,
FirstTypeNode = 154,
LastTypeNode = 166,
FirstPunctuation = 15,
LastPunctuation = 68,
FirstAssignment = 57,
LastAssignment = 69,
FirstCompoundAssignment = 58,
LastCompoundAssignment = 69,
FirstReservedWord = 71,
LastReservedWord = 106,
FirstKeyword = 71,
LastKeyword = 139,
FirstFutureReservedWord = 107,
LastFutureReservedWord = 115,
FirstTypeNode = 155,
LastTypeNode = 167,
FirstPunctuation = 16,
LastPunctuation = 69,
FirstToken = 0,
LastToken = 138,
LastToken = 139,
FirstTriviaToken = 2,
LastTriviaToken = 7,
FirstLiteralToken = 8,
LastLiteralToken = 11,
FirstTemplateToken = 11,
LastTemplateToken = 14,
FirstBinaryOperator = 25,
LastBinaryOperator = 68,
FirstNode = 139,
LastLiteralToken = 12,
FirstTemplateToken = 12,
LastTemplateToken = 15,
FirstBinaryOperator = 26,
LastBinaryOperator = 69,
FirstNode = 140,
FirstJSDocNode = 257,
LastJSDocNode = 282,
FirstJSDocTagNode = 273,
@@ -406,6 +406,7 @@ declare namespace ts {
AccessibilityModifier = 28,
ParameterPropertyModifier = 92,
NonPublicAccessibilityModifier = 24,
TypeScriptModifier = 2270,
}
enum JsxFlags {
None = 0,
@@ -1351,8 +1352,9 @@ declare namespace ts {
TrueCondition = 32,
FalseCondition = 64,
SwitchClause = 128,
Referenced = 256,
Shared = 512,
ArrayMutation = 256,
Referenced = 512,
Shared = 1024,
Label = 12,
Condition = 96,
}
@@ -1380,6 +1382,10 @@ declare namespace ts {
clauseEnd: number;
antecedent: FlowNode;
}
interface FlowArrayMutation extends FlowNode {
node: CallExpression | BinaryExpression;
antecedent: FlowNode;
}
type FlowType = Type | IncompleteType;
interface IncompleteType {
flags: TypeFlags;
@@ -1913,7 +1919,6 @@ declare namespace ts {
AMD = 2,
UMD = 3,
System = 4,
ES6 = 5,
ES2015 = 5,
}
enum JsxEmit {
@@ -1939,9 +1944,10 @@ declare namespace ts {
enum ScriptTarget {
ES3 = 0,
ES5 = 1,
ES6 = 2,
ES2015 = 2,
Latest = 2,
ES2016 = 3,
ES2017 = 4,
Latest = 4,
}
enum LanguageVariant {
Standard = 0,
+11950 -11233
View File
File diff suppressed because it is too large Load Diff
+1280 -320
View File
File diff suppressed because it is too large Load Diff
+22
View File
@@ -0,0 +1,22 @@
// Import the utility functionality.
import jobs.generation.Utilities;
// Defines a the new of the repo, used elsewhere in the file
def project = GithubProject
def branch = GithubBranchName
def nodeVersions = ['stable', '4']
nodeVersions.each { nodeVer ->
def newJobName = "typescript_node.${nodeVer}"
def newJob = job(Utilities.getFullJobName(project, newJobName, true)) {
steps {
shell("./jenkins.sh ${nodeVer}")
}
}
Utilities.standardJobSetup(newJob, project, true, "*/${branch}")
Utilities.setMachineAffinity(newJob, 'Ubuntu', '20161020')
Utilities.addGithubPRTriggerForBranch(newJob, branch, "TypeScript Test Run ${newJobName}")
}
+40 -2
View File
@@ -54,6 +54,11 @@ namespace ts {
const body = (<ModuleDeclaration>node).body;
return body ? getModuleInstanceState(body) : ModuleInstanceState.Instantiated;
}
// Only jsdoc typedef definition can exist in jsdoc namespace, and it should
// be considered the same as type alias
else if (node.kind === SyntaxKind.Identifier && (<Identifier>node).isInJSDocNamespace) {
return ModuleInstanceState.NonInstantiated;
}
else {
return ModuleInstanceState.Instantiated;
}
@@ -429,7 +434,11 @@ namespace ts {
// during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
// and this case is specially handled. Module augmentations should only be merged with original module definition
// and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
if (!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) {
const isJSDocTypedefInJSDocNamespace = node.kind === SyntaxKind.JSDocTypedefTag &&
node.name &&
node.name.kind === SyntaxKind.Identifier &&
(<Identifier>node.name).isInJSDocNamespace;
if ((!isAmbientModule(node) && (hasExportModifier || container.flags & NodeFlags.ExportContext)) || isJSDocTypedefInJSDocNamespace) {
const exportKind =
(symbolFlags & SymbolFlags.Value ? SymbolFlags.ExportValue : 0) |
(symbolFlags & SymbolFlags.Type ? SymbolFlags.ExportType : 0) |
@@ -1007,7 +1016,7 @@ namespace ts {
currentFlow = finishFlowLabel(preFinallyLabel);
bind(node.finallyBlock);
// if flow after finally is unreachable - keep it
// otherwise check if flows after try and after catch are unreachable
// otherwise check if flows after try and after catch are unreachable
// if yes - convert current flow to unreachable
// i.e.
// try { return "1" } finally { console.log(1); }
@@ -1828,6 +1837,17 @@ namespace ts {
switch (node.kind) {
/* Strict mode checks */
case SyntaxKind.Identifier:
// for typedef type names with namespaces, bind the new jsdoc type symbol here
// because it requires all containing namespaces to be in effect, namely the
// current "blockScopeContainer" needs to be set to its immediate namespace parent.
if ((<Identifier>node).isInJSDocNamespace) {
let parentNode = node.parent;
while (parentNode && parentNode.kind !== SyntaxKind.JSDocTypedefTag) {
parentNode = parentNode.parent;
}
bindBlockScopedDeclaration(<Declaration>parentNode, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
break;
}
case SyntaxKind.ThisKeyword:
if (currentFlow && (isExpression(node) || parent.kind === SyntaxKind.ShorthandPropertyAssignment)) {
node.flowNode = currentFlow;
@@ -1951,6 +1971,10 @@ namespace ts {
case SyntaxKind.InterfaceDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.Interface, SymbolFlags.InterfaceExcludes);
case SyntaxKind.JSDocTypedefTag:
if (!(<JSDocTypedefTag>node).fullName || (<JSDocTypedefTag>node).fullName.kind === SyntaxKind.Identifier) {
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
}
break;
case SyntaxKind.TypeAliasDeclaration:
return bindBlockScopedDeclaration(<Declaration>node, SymbolFlags.TypeAlias, SymbolFlags.TypeAliasExcludes);
case SyntaxKind.EnumDeclaration:
@@ -2421,6 +2445,9 @@ namespace ts {
case SyntaxKind.HeritageClause:
return computeHeritageClause(<HeritageClause>node, subtreeFlags);
case SyntaxKind.CatchClause:
return computeCatchClause(<CatchClause>node, subtreeFlags);
case SyntaxKind.ExpressionWithTypeArguments:
return computeExpressionWithTypeArguments(<ExpressionWithTypeArguments>node, subtreeFlags);
@@ -2650,6 +2677,17 @@ namespace ts {
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeCatchClause(node: CatchClause, subtreeFlags: TransformFlags) {
let transformFlags = subtreeFlags;
if (node.variableDeclaration && isBindingPattern(node.variableDeclaration.name)) {
transformFlags |= TransformFlags.AssertES2015;
}
node.transformFlags = transformFlags | TransformFlags.HasComputedFlags;
return transformFlags & ~TransformFlags.NodeExcludes;
}
function computeExpressionWithTypeArguments(node: ExpressionWithTypeArguments, subtreeFlags: TransformFlags) {
// An ExpressionWithTypeArguments is ES6 syntax, as it is used in the
// extends clause of a class.
+284 -218
View File
File diff suppressed because it is too large Load Diff
+22 -2
View File
@@ -599,7 +599,13 @@ namespace ts {
i++;
break;
case "boolean":
options[opt.name] = true;
// boolean flag has optional value true, false, others
let optValue = args[i];
options[opt.name] = optValue !== "false";
// consume next argument as boolean flag value
if (optValue === "false" || optValue === "true") {
i++;
}
break;
case "string":
options[opt.name] = args[i] || "";
@@ -906,6 +912,9 @@ namespace ts {
if (hasProperty(json, "files")) {
if (isArray(json["files"])) {
fileNames = <string[]>json["files"];
if (fileNames.length === 0) {
errors.push(createCompilerDiagnostic(Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json"));
}
}
else {
errors.push(createCompilerDiagnostic(Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "files", "Array"));
@@ -948,7 +957,18 @@ namespace ts {
includeSpecs = ["**/*"];
}
return matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
const result = matchFileNames(fileNames, includeSpecs, excludeSpecs, basePath, options, host, errors);
if (result.fileNames.length === 0 && !hasProperty(json, "files") && resolutionStack.length === 0) {
errors.push(
createCompilerDiagnostic(
Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
configFileName || "tsconfig.json",
JSON.stringify(includeSpecs || []),
JSON.stringify(excludeSpecs || [])));
}
return result;
}
}
+57 -5
View File
@@ -456,6 +456,44 @@ namespace ts {
return result;
}
export function arrayIsEqualTo<T>(array1: ReadonlyArray<T>, array2: ReadonlyArray<T>, equaler?: (a: T, b: T) => boolean): boolean {
if (!array1 || !array2) {
return array1 === array2;
}
if (array1.length !== array2.length) {
return false;
}
for (let i = 0; i < array1.length; i++) {
const equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i];
if (!equals) {
return false;
}
}
return true;
}
export function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean {
return !oldOptions ||
(oldOptions.module !== newOptions.module) ||
(oldOptions.moduleResolution !== newOptions.moduleResolution) ||
(oldOptions.noResolve !== newOptions.noResolve) ||
(oldOptions.target !== newOptions.target) ||
(oldOptions.noLib !== newOptions.noLib) ||
(oldOptions.jsx !== newOptions.jsx) ||
(oldOptions.allowJs !== newOptions.allowJs) ||
(oldOptions.rootDir !== newOptions.rootDir) ||
(oldOptions.configFilePath !== newOptions.configFilePath) ||
(oldOptions.baseUrl !== newOptions.baseUrl) ||
(oldOptions.maxNodeModuleJsDepth !== newOptions.maxNodeModuleJsDepth) ||
!arrayIsEqualTo(oldOptions.lib, newOptions.lib) ||
!arrayIsEqualTo(oldOptions.typeRoots, newOptions.typeRoots) ||
!arrayIsEqualTo(oldOptions.rootDirs, newOptions.rootDirs) ||
!equalOwnProperties(oldOptions.paths, newOptions.paths);
}
/**
* Compacts an array, removing any falsey elements.
*/
@@ -532,6 +570,12 @@ namespace ts {
: undefined;
}
export function replaceElement<T>(array: T[], index: number, value: T): T[] {
const result = array.slice(0);
result[index] = value;
return result;
}
/**
* Performs a binary search, finding the index at which 'value' occurs in 'array'.
* If no such index is found, returns the 2's-complement of first index at which
@@ -815,7 +859,7 @@ namespace ts {
return result;
}
export function extend<T1, T2>(first: T1 , second: T2): T1 & T2 {
export function extend<T1, T2>(first: T1, second: T2): T1 & T2 {
const result: T1 & T2 = <any>{};
for (const id in second) if (hasOwnProperty.call(second, id)) {
(result as any)[id] = (second as any)[id];
@@ -863,6 +907,14 @@ namespace ts {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
/** Does nothing. */
export function noop(): void {}
/** Throws an error because a function is not implemented. */
export function notImplemented(): never {
throw new Error("Not implemented");
}
export function memoize<T>(callback: () => T): () => T {
let value: T;
return () => {
@@ -960,8 +1012,8 @@ namespace ts {
Debug.assert(length >= 0, "length must be non-negative, is " + length);
if (file) {
Debug.assert(start <= file.text.length, `start must be within the bounds of the file. ${ start } > ${ file.text.length }`);
Debug.assert(end <= file.text.length, `end must be the bounds of the file. ${ end } > ${ file.text.length }`);
Debug.assert(start <= file.text.length, `start must be within the bounds of the file. ${start} > ${file.text.length}`);
Debug.assert(end <= file.text.length, `end must be the bounds of the file. ${end} > ${file.text.length}`);
}
let text = getLocaleSpecificMessage(message);
@@ -1511,7 +1563,7 @@ namespace ts {
return undefined;
}
const replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther;
const replaceWildcardCharacter = usage === "files" ? replaceWildCardCharacterFiles : replaceWildCardCharacterOther;
const singleAsteriskRegexFragment = usage === "files" ? singleAsteriskRegexFragmentFiles : singleAsteriskRegexFragmentOther;
/**
@@ -1753,7 +1805,7 @@ namespace ts {
/** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
export const supportedTypescriptExtensionsForExtractExtension = [".d.ts", ".ts", ".tsx"];
export const supportedJavascriptExtensions = [".js", ".jsx"];
export const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);
const allSupportedExtensions = supportedTypeScriptExtensions.concat(supportedJavascriptExtensions);
export function getSupportedExtensions(options?: CompilerOptions): string[] {
return options && options.allowJs ? allSupportedExtensions : supportedTypeScriptExtensions;
+1 -1
View File
@@ -63,7 +63,7 @@ namespace ts {
let isCurrentFileExternalModule: boolean;
let reportedDeclarationError = false;
let errorNameNode: DeclarationName;
const emitJsDocComments = compilerOptions.removeComments ? () => {} : writeJsDocComments;
const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments;
const emit = compilerOptions.stripInternal ? stripInternal : emitNode;
let noDeclare: boolean;
+10 -4
View File
@@ -603,10 +603,6 @@
"category": "Error",
"code": 1194
},
"Catch clause variable name must be an identifier.": {
"category": "Error",
"code": 1195
},
"Catch clause variable cannot have a type annotation.": {
"category": "Error",
"code": 1196
@@ -3085,6 +3081,7 @@
"category": "Error",
"code": 17010
},
"Circularity detected while resolving configuration: {0}": {
"category": "Error",
"code": 18000
@@ -3093,6 +3090,15 @@
"category": "Error",
"code": 18001
},
"The 'files' list in config file '{0}' is empty.": {
"category": "Error",
"code": 18002
},
"No inputs were found in config file '{0}'. Specified 'include' paths were '{1}' and 'exclude' paths were '{2}'.": {
"category": "Error",
"code": 18003
},
"Add missing 'super()' call.": {
"category": "Message",
"code": 90001
+3 -1
View File
@@ -1625,7 +1625,9 @@ namespace ts {
// flag and setting a parent node.
const react = createIdentifier(reactNamespace || "React");
react.flags &= ~NodeFlags.Synthesized;
react.parent = parent;
// Set the parent that is in parse tree
// this makes sure that parent chain is intact for checker to traverse complete scope tree
react.parent = getParseTreeNode(parent);
return react;
}
+38 -7
View File
@@ -411,6 +411,7 @@ namespace ts {
return visitNodes(cbNodes, (<JSDocTemplateTag>node).typeParameters);
case SyntaxKind.JSDocTypedefTag:
return visitNode(cbNode, (<JSDocTypedefTag>node).typeExpression) ||
visitNode(cbNode, (<JSDocTypedefTag>node).fullName) ||
visitNode(cbNode, (<JSDocTypedefTag>node).name) ||
visitNode(cbNode, (<JSDocTypedefTag>node).jsDocTypeLiteral);
case SyntaxKind.JSDocTypeLiteral:
@@ -5472,7 +5473,7 @@ namespace ts {
exportDeclaration.name = parseIdentifier();
parseExpected(SyntaxKind.SemicolonToken);
parseSemicolon();
return finishNode(exportDeclaration);
}
@@ -6552,7 +6553,14 @@ namespace ts {
const typedefTag = <JSDocTypedefTag>createNode(SyntaxKind.JSDocTypedefTag, atToken.pos);
typedefTag.atToken = atToken;
typedefTag.tagName = tagName;
typedefTag.name = parseJSDocIdentifierName();
typedefTag.fullName = parseJSDocTypeNameWithNamespace(/*flags*/ 0);
if (typedefTag.fullName) {
let rightNode = typedefTag.fullName;
while (rightNode.kind !== SyntaxKind.Identifier) {
rightNode = rightNode.body;
}
typedefTag.name = rightNode;
}
typedefTag.typeExpression = typeExpression;
skipWhitespace();
@@ -6615,8 +6623,27 @@ namespace ts {
scanner.setTextPos(resumePos);
return finishNode(jsDocTypeLiteral);
}
function parseJSDocTypeNameWithNamespace(flags: NodeFlags) {
const pos = scanner.getTokenPos();
const typeNameOrNamespaceName = parseJSDocIdentifierName();
if (typeNameOrNamespaceName && parseOptional(SyntaxKind.DotToken)) {
const jsDocNamespaceNode = <JSDocNamespaceDeclaration>createNode(SyntaxKind.ModuleDeclaration, pos);
jsDocNamespaceNode.flags |= flags;
jsDocNamespaceNode.name = typeNameOrNamespaceName;
jsDocNamespaceNode.body = parseJSDocTypeNameWithNamespace(NodeFlags.NestedNamespace);
return jsDocNamespaceNode;
}
if (typeNameOrNamespaceName && flags & NodeFlags.NestedNamespace) {
typeNameOrNamespaceName.isInJSDocNamespace = true;
}
return typeNameOrNamespaceName;
}
}
function tryParseChildTag(parentTag: JSDocTypeLiteral): boolean {
Debug.assert(token() === SyntaxKind.AtToken);
const atToken = <AtToken>createNode(SyntaxKind.AtToken, scanner.getStartPos());
@@ -6639,12 +6666,16 @@ namespace ts {
return true;
case "prop":
case "property":
if (!parentTag.jsDocPropertyTags) {
parentTag.jsDocPropertyTags = <NodeArray<JSDocPropertyTag>>[];
}
const propertyTag = parsePropertyTag(atToken, tagName);
parentTag.jsDocPropertyTags.push(propertyTag);
return true;
if (propertyTag) {
if (!parentTag.jsDocPropertyTags) {
parentTag.jsDocPropertyTags = <NodeArray<JSDocPropertyTag>>[];
}
parentTag.jsDocPropertyTags.push(propertyTag);
return true;
}
// Error parsing property tag
return false;
}
return false;
}
+2 -17
View File
@@ -470,21 +470,7 @@ namespace ts {
// check properties that can affect structure of the program or module resolution strategy
// if any of these properties has changed - structure cannot be reused
const oldOptions = oldProgram.getCompilerOptions();
if ((oldOptions.module !== options.module) ||
(oldOptions.moduleResolution !== options.moduleResolution) ||
(oldOptions.noResolve !== options.noResolve) ||
(oldOptions.target !== options.target) ||
(oldOptions.noLib !== options.noLib) ||
(oldOptions.jsx !== options.jsx) ||
(oldOptions.allowJs !== options.allowJs) ||
(oldOptions.rootDir !== options.rootDir) ||
(oldOptions.configFilePath !== options.configFilePath) ||
(oldOptions.baseUrl !== options.baseUrl) ||
(oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) ||
!arrayIsEqualTo(oldOptions.lib, options.lib) ||
!arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) ||
!arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) ||
!equalOwnProperties(oldOptions.paths, options.paths)) {
if (changesAffectModuleResolution(oldOptions, options)) {
return false;
}
@@ -958,8 +944,7 @@ namespace ts {
return runWithCancellationToken(() => {
const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
const writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
return ts.getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile);
});
}
+3
View File
@@ -1799,6 +1799,9 @@ namespace ts {
case CharacterCodes.comma:
pos++;
return token = SyntaxKind.CommaToken;
case CharacterCodes.dot:
pos++;
return token = SyntaxKind.DotToken;
}
if (isIdentifierStart(ch, ScriptTarget.Latest)) {
+5 -1
View File
@@ -34,6 +34,8 @@ namespace ts {
realpath?(path: string): string;
/*@internal*/ getEnvironmentVariable(name: string): string;
/*@internal*/ tryEnableSourceMapsForHost?(): void;
setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any;
clearTimeout?(timeoutId: any): void;
}
export interface FileWatcher {
@@ -560,7 +562,9 @@ namespace ts {
catch (e) {
// Could not enable source maps.
}
}
},
setTimeout,
clearTimeout
};
return nodeSystem;
}
+21
View File
@@ -362,6 +362,9 @@ namespace ts {
case SyntaxKind.ObjectLiteralExpression:
return visitObjectLiteralExpression(<ObjectLiteralExpression>node);
case SyntaxKind.CatchClause:
return visitCatchClause(<CatchClause>node);
case SyntaxKind.ShorthandPropertyAssignment:
return visitShorthandPropertyAssignment(<ShorthandPropertyAssignment>node);
@@ -2622,6 +2625,24 @@ namespace ts {
return expression;
}
function visitCatchClause(node: CatchClause): CatchClause {
Debug.assert(isBindingPattern(node.variableDeclaration.name));
const temp = createTempVariable(undefined);
const newVariableDeclaration = createVariableDeclaration(temp, undefined, undefined, node.variableDeclaration);
const vars = flattenVariableDestructuring(node.variableDeclaration, temp, visitor);
const list = createVariableDeclarationList(vars, /*location*/node.variableDeclaration, /*flags*/node.variableDeclaration.flags);
const destructure = createVariableStatement(undefined, list);
return updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
}
function addStatementToStartOfBlock(block: Block, statement: Statement): Block {
const transformedStatements = visitNodes(block.statements, visitor, isStatement);
return updateBlock(block, [statement].concat(transformedStatements));
}
/**
* Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
* PropertyAssignment.
+16 -8
View File
@@ -250,8 +250,8 @@ namespace ts {
let compilerOptions: CompilerOptions; // Compiler options for compilation
let compilerHost: CompilerHost; // Compiler host
let hostGetSourceFile: typeof compilerHost.getSourceFile; // getSourceFile method from default host
let timerHandleForRecompilation: number; // Handle for 0.25s wait timer to trigger recompilation
let timerHandleForDirectoryChanges: number; // Handle for 0.25s wait timer to trigger directory change handler
let timerHandleForRecompilation: any; // Handle for 0.25s wait timer to trigger recompilation
let timerHandleForDirectoryChanges: any; // Handle for 0.25s wait timer to trigger directory change handler
// This map stores and reuses results of fileExists check that happen inside 'createProgram'
// This allows to save time in module resolution heavy scenarios when existence of the same file might be checked multiple times.
@@ -503,10 +503,14 @@ namespace ts {
}
function startTimerForHandlingDirectoryChanges() {
if (timerHandleForDirectoryChanges) {
clearTimeout(timerHandleForDirectoryChanges);
if (!sys.setTimeout || !sys.clearTimeout) {
return;
}
timerHandleForDirectoryChanges = setTimeout(directoryChangeHandler, 250);
if (timerHandleForDirectoryChanges) {
sys.clearTimeout(timerHandleForDirectoryChanges);
}
timerHandleForDirectoryChanges = sys.setTimeout(directoryChangeHandler, 250);
}
function directoryChangeHandler() {
@@ -525,10 +529,14 @@ namespace ts {
// operations (such as saving all modified files in an editor) a chance to complete before we kick
// off a new compilation.
function startTimerForRecompilation() {
if (timerHandleForRecompilation) {
clearTimeout(timerHandleForRecompilation);
if (!sys.setTimeout || !sys.clearTimeout) {
return;
}
timerHandleForRecompilation = setTimeout(recompile, 250);
if (timerHandleForRecompilation) {
sys.clearTimeout(timerHandleForRecompilation);
}
timerHandleForRecompilation = sys.setTimeout(recompile, 250);
}
function recompile() {
+40 -22
View File
@@ -421,7 +421,7 @@ namespace ts {
ThisNodeHasError = 1 << 19, // If the parser encountered an error when parsing the code that created this node
JavaScriptFile = 1 << 20, // If node was parsed in a JavaScript
ThisNodeOrAnySubNodesHasError = 1 << 21, // If this node or any of its children had an error
HasAggregatedChildData = 1 << 22, // If we've computed data from children and cached it in this node
HasAggregatedChildData = 1 << 22, // If we've computed data from children and cached it in this node
BlockScoped = Let | Const,
@@ -545,6 +545,7 @@ namespace ts {
originalKeywordKind?: SyntaxKind; // Original syntaxKind which get set so that we can report an error later
/*@internal*/ autoGenerateKind?: GeneratedIdentifierKind; // Specifies whether to auto-generate the text for an identifier.
/*@internal*/ autoGenerateId?: number; // Ensures unique generated identifiers get unique names, but clones get the same name.
isInJSDocNamespace?: boolean; // if the node is a member in a JSDoc namespace
}
// Transient identifier node (marked by id === -1)
@@ -1634,7 +1635,7 @@ namespace ts {
export interface ModuleDeclaration extends DeclarationStatement {
kind: SyntaxKind.ModuleDeclaration;
name: Identifier | LiteralExpression;
body?: ModuleBlock | NamespaceDeclaration;
body?: ModuleBlock | NamespaceDeclaration | JSDocNamespaceDeclaration | Identifier;
}
export interface NamespaceDeclaration extends ModuleDeclaration {
@@ -1642,6 +1643,11 @@ namespace ts {
body: ModuleBlock | NamespaceDeclaration;
}
export interface JSDocNamespaceDeclaration extends ModuleDeclaration {
name: Identifier;
body: JSDocNamespaceDeclaration | Identifier;
}
export interface ModuleBlock extends Node, Statement {
kind: SyntaxKind.ModuleBlock;
statements: NodeArray<Statement>;
@@ -1871,6 +1877,7 @@ namespace ts {
export interface JSDocTypedefTag extends JSDocTag, Declaration {
kind: SyntaxKind.JSDocTypedefTag;
fullName?: JSDocNamespaceDeclaration | Identifier;
name?: Identifier;
typeExpression?: JSDocTypeExpression;
jsDocTypeLiteral?: JSDocTypeLiteral;
@@ -2612,24 +2619,17 @@ namespace ts {
Null = 1 << 12,
Never = 1 << 13, // Never type
TypeParameter = 1 << 14, // Type parameter
Class = 1 << 15, // Class
Interface = 1 << 16, // Interface
Reference = 1 << 17, // Generic type reference
Tuple = 1 << 18, // Synthesized generic tuple type
Union = 1 << 19, // Union (T | U)
Intersection = 1 << 20, // Intersection (T & U)
Anonymous = 1 << 21, // Anonymous
Instantiated = 1 << 22, // Instantiated anonymous type
Object = 1 << 15, // Object type
Union = 1 << 16, // Union (T | U)
Intersection = 1 << 17, // Intersection (T & U)
/* @internal */
ObjectLiteral = 1 << 23, // Originates in an object literal
FreshLiteral = 1 << 18, // Fresh literal type
/* @internal */
FreshLiteral = 1 << 24, // Fresh literal type
ContainsWideningType = 1 << 19, // Type is or contains undefined or null widening type
/* @internal */
ContainsWideningType = 1 << 25, // Type is or contains undefined or null widening type
ContainsObjectLiteral = 1 << 20, // Type is or contains object literal type
/* @internal */
ContainsObjectLiteral = 1 << 26, // Type is or contains object literal type
/* @internal */
ContainsAnyFunctionType = 1 << 27, // Type is or contains object literal type
ContainsAnyFunctionType = 1 << 21, // Type is or contains object literal type
/* @internal */
Nullable = Undefined | Null,
@@ -2646,15 +2646,14 @@ namespace ts {
NumberLike = Number | NumberLiteral | Enum | EnumLiteral,
BooleanLike = Boolean | BooleanLiteral,
EnumLike = Enum | EnumLiteral,
ObjectType = Class | Interface | Reference | Tuple | Anonymous,
UnionOrIntersection = Union | Intersection,
StructuredType = ObjectType | Union | Intersection,
StructuredType = Object | Union | Intersection,
StructuredOrTypeParameter = StructuredType | TypeParameter,
// 'Narrowable' types are types where narrowing actually narrows.
// This *should* be every type other than null, undefined, void, and never
Narrowable = Any | StructuredType | TypeParameter | StringLike | NumberLike | BooleanLike | ESSymbol,
NotUnionOrUnit = Any | ESSymbol | ObjectType,
NotUnionOrUnit = Any | ESSymbol | Object,
/* @internal */
RequiresWidening = ContainsWideningType | ContainsObjectLiteral,
/* @internal */
@@ -2697,9 +2696,22 @@ namespace ts {
baseType: EnumType & UnionType; // Base enum type
}
export const enum ObjectFlags {
Class = 1 << 0, // Class
Interface = 1 << 1, // Interface
Reference = 1 << 2, // Generic type reference
Tuple = 1 << 3, // Synthesized generic tuple type
Anonymous = 1 << 4, // Anonymous
Instantiated = 1 << 5, // Instantiated anonymous type
ObjectLiteral = 1 << 6, // Originates in an object literal
EvolvingArray = 1 << 7, // Evolving array type
ObjectLiteralPatternWithComputedProperties = 1 << 8, // Object literal pattern with computed properties
ClassOrInterface = Class | Interface
}
// Object types (TypeFlags.ObjectType)
export interface ObjectType extends Type {
isObjectLiteralPatternWithComputedProperties?: boolean;
objectFlags: ObjectFlags;
}
// Class and interface types (TypeFlags.Class and TypeFlags.Interface)
@@ -2753,13 +2765,18 @@ namespace ts {
export interface IntersectionType extends UnionOrIntersectionType { }
export type StructuredType = ObjectType | UnionType | IntersectionType;
/* @internal */
// An instantiated anonymous type has a target and a mapper
export interface AnonymousType extends ObjectType {
target?: AnonymousType; // Instantiation target
mapper?: TypeMapper; // Instantiation mapper
elementType?: Type; // Element expressions of evolving array type
finalArrayType?: Type; // Final array type of evolving array type
}
export interface EvolvingArrayType extends ObjectType {
elementType: Type; // Element expressions of evolving array type
finalArrayType?: Type; // Final array type of evolving array type
}
/* @internal */
@@ -3024,6 +3041,7 @@ namespace ts {
packageNameToTypingLocation: Map<string>; // The map of package names to their cached typing locations
typingOptions: TypingOptions; // Used to customize the typing inference process
compilerOptions: CompilerOptions; // Used as a source for typing inference
unresolvedImports: ReadonlyArray<string>; // List of unresolved module ids from imports
}
export enum ModuleKind {
+11 -32
View File
@@ -63,11 +63,11 @@ namespace ts {
// Completely ignore indentation for string writers. And map newlines to
// a single space.
writeLine: () => str += " ",
increaseIndent: () => { },
decreaseIndent: () => { },
increaseIndent: noop,
decreaseIndent: noop,
clear: () => str = "",
trackSymbol: () => { },
reportInaccessibleThisError: () => { }
trackSymbol: noop,
reportInaccessibleThisError: noop
};
}
@@ -83,25 +83,6 @@ namespace ts {
return node.end - node.pos;
}
export function arrayIsEqualTo<T>(array1: ReadonlyArray<T>, array2: ReadonlyArray<T>, equaler?: (a: T, b: T) => boolean): boolean {
if (!array1 || !array2) {
return array1 === array2;
}
if (array1.length !== array2.length) {
return false;
}
for (let i = 0; i < array1.length; i++) {
const equals = equaler ? equaler(array1[i], array2[i]) : array1[i] === array2[i];
if (!equals) {
return false;
}
}
return true;
}
export function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean {
return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]);
}
@@ -441,7 +422,12 @@ namespace ts {
export function isBlockOrCatchScoped(declaration: Declaration) {
return (getCombinedNodeFlags(declaration) & NodeFlags.BlockScoped) !== 0 ||
isCatchClauseVariableDeclaration(declaration);
isCatchClauseVariableDeclarationOrBindingElement(declaration);
}
export function isCatchClauseVariableDeclarationOrBindingElement(declaration: Declaration) {
const node = getRootDeclaration(declaration);
return node.kind === SyntaxKind.VariableDeclaration && node.parent.kind === SyntaxKind.CatchClause;
}
export function isAmbientModule(node: Node): boolean {
@@ -524,13 +510,6 @@ namespace ts {
}
}
export function isCatchClauseVariableDeclaration(declaration: Declaration) {
return declaration &&
declaration.kind === SyntaxKind.VariableDeclaration &&
declaration.parent &&
declaration.parent.kind === SyntaxKind.CatchClause;
}
// Return display name of an identifier
// Computed property names will just be emitted as "[<expr>]", where <expr> is the source
// text of the expression in the computed property.
@@ -3073,7 +3052,7 @@ namespace ts {
}
}
if (node.flags & NodeFlags.NestedNamespace) {
if (node.flags & NodeFlags.NestedNamespace || (node.kind === SyntaxKind.Identifier && (<Identifier>node).isInJSDocNamespace)) {
flags |= ModifierFlags.Export;
}
+3 -3
View File
@@ -1331,18 +1331,18 @@ namespace ts {
export namespace Debug {
export const failNotOptional = shouldAssert(AssertionLevel.Normal)
? (message?: string) => assert(false, message || "Node not optional.")
: () => {};
: noop;
export const failBadSyntaxKind = shouldAssert(AssertionLevel.Normal)
? (node: Node, message?: string) => assert(false, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} was unexpected.`)
: () => {};
: noop;
export const assertNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
test === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
: () => {};
: noop;
function getFunctionName(func: Function) {
if (typeof func !== "function") {
+16 -38
View File
@@ -47,19 +47,6 @@ namespace FourSlash {
ranges: Range[];
}
interface MemberListData {
result: {
maybeInaccurate: boolean;
isMemberCompletion: boolean;
entries: {
name: string;
type: string;
kind: string;
kindModifiers: string;
}[];
};
}
export interface Marker {
fileName: string;
position: number;
@@ -178,15 +165,9 @@ namespace FourSlash {
// Return object may lack some functionalities for other purposes.
function createScriptSnapShot(sourceText: string): ts.IScriptSnapshot {
return {
getText: (start: number, end: number) => {
return sourceText.substr(start, end - start);
},
getLength: () => {
return sourceText.length;
},
getChangeRange: (oldSnapshot: ts.IScriptSnapshot) => {
return <ts.TextChangeRange>undefined;
}
getText: (start: number, end: number) => sourceText.substr(start, end - start),
getLength: () => sourceText.length,
getChangeRange: () => undefined
};
}
@@ -419,9 +400,8 @@ namespace FourSlash {
public verifyErrorExistsBetweenMarkers(startMarkerName: string, endMarkerName: string, negative: boolean) {
const startMarker = this.getMarkerByName(startMarkerName);
const endMarker = this.getMarkerByName(endMarkerName);
const predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
};
const predicate = (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) =>
((errorMinChar === startPos) && (errorLimChar === endPos)) ? true : false;
const exists = this.anyErrorInRange(predicate, startMarker, endMarker);
@@ -471,14 +451,12 @@ namespace FourSlash {
let predicate: (errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) => boolean;
if (after) {
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
};
predicate = (errorMinChar: number, errorLimChar: number, startPos: number) =>
((errorMinChar >= startPos) && (errorLimChar >= startPos)) ? true : false;
}
else {
predicate = function(errorMinChar: number, errorLimChar: number, startPos: number, endPos: number) {
return ((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
};
predicate = (errorMinChar: number, errorLimChar: number, startPos: number) =>
((errorMinChar <= startPos) && (errorLimChar <= startPos)) ? true : false;
}
const exists = this.anyErrorInRange(predicate, marker);
@@ -1179,7 +1157,7 @@ namespace FourSlash {
private alignmentForExtraInfo = 50;
private spanInfoToString(pos: number, spanInfo: ts.TextSpan, prefixString: string) {
private spanInfoToString(spanInfo: ts.TextSpan, prefixString: string) {
let resultString = "SpanInfo: " + JSON.stringify(spanInfo);
if (spanInfo) {
const spanString = this.activeFile.content.substr(spanInfo.start, spanInfo.length);
@@ -1230,7 +1208,7 @@ namespace FourSlash {
startColumn = 0;
length = 0;
}
const spanInfo = this.spanInfoToString(pos, getSpanAtPos(pos), prefixString);
const spanInfo = this.spanInfoToString(getSpanAtPos(pos), prefixString);
if (previousSpanInfo && previousSpanInfo !== spanInfo) {
addSpanInfoString();
previousSpanInfo = spanInfo;
@@ -1300,10 +1278,10 @@ namespace FourSlash {
}
}
emitOutput.outputFiles.forEach((outputFile, idx, array) => {
for (const outputFile of emitOutput.outputFiles) {
const fileName = "FileName : " + outputFile.name + Harness.IO.newLine();
resultString = resultString + fileName + outputFile.text;
});
}
resultString += Harness.IO.newLine();
});
@@ -1328,7 +1306,7 @@ namespace FourSlash {
}
public printBreakpointLocation(pos: number) {
Harness.IO.log("\n**Pos: " + pos + " " + this.spanInfoToString(pos, this.getBreakpointStatementLocation(pos), " "));
Harness.IO.log("\n**Pos: " + pos + " " + this.spanInfoToString(this.getBreakpointStatementLocation(pos), " "));
}
public printBreakpointAtCurrentLocation() {
@@ -1830,7 +1808,7 @@ namespace FourSlash {
return result;
}
private rangeText({fileName, start, end}: Range, more = false): string {
private rangeText({fileName, start, end}: Range): string {
return this.getFileContent(fileName).slice(start, end);
}
@@ -1925,7 +1903,7 @@ namespace FourSlash {
}
public printNameOrDottedNameSpans(pos: number) {
Harness.IO.log(this.spanInfoToString(pos, this.getNameOrDottedNameSpan(pos), "**"));
Harness.IO.log(this.spanInfoToString(this.getNameOrDottedNameSpan(pos), "**"));
}
private verifyClassifications(expected: { classificationType: string; text: string; textSpan?: TextSpan }[], actual: ts.ClassifiedSpan[]) {
+12 -15
View File
@@ -220,9 +220,7 @@ namespace Utils {
}
export function sourceFileToJSON(file: ts.Node): string {
return JSON.stringify(file, (k, v) => {
return isNodeOrArray(v) ? serializeNode(v) : v;
}, " ");
return JSON.stringify(file, (_, v) => isNodeOrArray(v) ? serializeNode(v) : v, " ");
function getKindName(k: number | string): string {
if (typeof k === "string") {
@@ -692,7 +690,7 @@ namespace Harness {
export const getCurrentDirectory = () => "";
export const args = () => <string[]>[];
export const getExecutingFilePath = () => "";
export const exit = (exitCode: number) => { };
export const exit = ts.noop;
export const getDirectories = () => <string[]>[];
export let log = (s: string) => console.log(s);
@@ -742,7 +740,7 @@ namespace Harness {
}
}
export function createDirectory(path: string) {
export function createDirectory() {
// Do nothing (?)
}
@@ -750,7 +748,7 @@ namespace Harness {
Http.writeToServerSync(serverRoot + path, "DELETE");
}
export function directoryExists(path: string): boolean {
export function directoryExists(): boolean {
return false;
}
@@ -792,7 +790,7 @@ namespace Harness {
return response.status === 200;
}
export function _listFilesImpl(path: string, spec?: RegExp, options?: any) {
export let listFiles = Utils.memoize((path: string, spec?: RegExp): string[] => {
const response = Http.getFileFromServerSync(serverRoot + path);
if (response.status === 200) {
const results = response.responseText.split(",");
@@ -806,8 +804,7 @@ namespace Harness {
else {
return [""];
}
};
export let listFiles = Utils.memoize(_listFilesImpl);
});
export function readFile(file: string) {
const response = Http.getFileFromServerSync(serverRoot + file);
@@ -991,7 +988,7 @@ namespace Harness {
}
}
function getSourceFile(fileName: string, languageVersion: ts.ScriptTarget) {
function getSourceFile(fileName: string) {
fileName = ts.normalizePath(fileName);
const path = ts.toPath(fileName, currentDirectory, getCanonicalFileName);
if (fileMap.contains(path)) {
@@ -1051,7 +1048,7 @@ namespace Harness {
getDirectories: d => {
const path = ts.toPath(d, currentDirectory, getCanonicalFileName);
const result: string[] = [];
fileMap.forEachValue((key, value) => {
fileMap.forEachValue(key => {
if (key.indexOf(path) === 0 && key.lastIndexOf("/") > path.length) {
let dirName = key.substr(path.length, key.indexOf("/", path.length + 1) - path.length);
if (dirName[0] === "/") {
@@ -1669,9 +1666,9 @@ namespace Harness {
}
// This does not need to exist strictly speaking, but many tests will need to be updated if it's removed
export function compileString(code: string, unitName: string, callback: (result: CompilerResult) => void) {
export function compileString(_code: string, _unitName: string, _callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
throw new Error("compileString NYI");
return ts.notImplemented();
}
export interface GeneratedFile {
@@ -1853,8 +1850,8 @@ namespace Harness {
// unit tests always list files explicitly
const parseConfigHost: ts.ParseConfigHost = {
useCaseSensitiveFileNames: false,
readDirectory: (name) => [],
fileExists: (name) => true,
readDirectory: () => [],
fileExists: () => true,
readFile: (name) => ts.forEach(testUnitData, data => data.name.toLowerCase() === name.toLowerCase() ? data.content : undefined)
};
+36 -40
View File
@@ -165,7 +165,7 @@ namespace Harness.LanguageService {
throw new Error("No script with name '" + fileName + "'");
}
public openFile(fileName: string, content?: string, scriptKindName?: string): void {
public openFile(_fileName: string, _content?: string, _scriptKindName?: string): void {
}
/**
@@ -198,7 +198,7 @@ namespace Harness.LanguageService {
const script = this.getScriptInfo(fileName);
return script ? new ScriptSnapshot(script) : undefined;
}
getScriptKind(fileName: string): ts.ScriptKind { return ts.ScriptKind.Unknown; }
getScriptKind(): ts.ScriptKind { return ts.ScriptKind.Unknown; }
getScriptVersion(fileName: string): string {
const script = this.getScriptInfo(fileName);
return script ? script.version.toString() : undefined;
@@ -214,7 +214,7 @@ namespace Harness.LanguageService {
this.getCurrentDirectory(),
(p) => this.virtualFileSystem.getAccessibleFileSystemEntries(p));
}
readFile(path: string, encoding?: string): string {
readFile(path: string): string {
const snapshot = this.getScriptSnapshot(path);
return snapshot.getText(0, snapshot.getLength());
}
@@ -223,9 +223,9 @@ namespace Harness.LanguageService {
}
log(s: string): void { }
trace(s: string): void { }
error(s: string): void { }
log(_: string): void { }
trace(_: string): void { }
error(_: string): void { }
}
export class NativeLanguageServiceAdapter implements LanguageServiceAdapter {
@@ -308,19 +308,15 @@ namespace Harness.LanguageService {
const nativeScriptSnapshot = this.nativeHost.getScriptSnapshot(fileName);
return nativeScriptSnapshot && new ScriptSnapshotProxy(nativeScriptSnapshot);
}
getScriptKind(fileName: string): ts.ScriptKind { return this.nativeHost.getScriptKind(fileName); }
getScriptKind(): ts.ScriptKind { return this.nativeHost.getScriptKind(); }
getScriptVersion(fileName: string): string { return this.nativeHost.getScriptVersion(fileName); }
getLocalizedDiagnosticMessages(): string { return JSON.stringify({}); }
readDirectory(rootDir: string, extension: string): string {
throw new Error("NYI");
}
readDirectoryNames(path: string): string {
throw new Error("Not implemented.");
}
readFileNames(path: string): string {
throw new Error("Not implemented.");
readDirectory(_rootDir: string, _extension: string): string {
return ts.notImplemented();
}
readDirectoryNames = ts.notImplemented;
readFileNames = ts.notImplemented;
fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; }
readFile(fileName: string) {
const snapshot = this.nativeHost.getScriptSnapshot(fileName);
@@ -329,7 +325,7 @@ namespace Harness.LanguageService {
log(s: string): void { this.nativeHost.log(s); }
trace(s: string): void { this.nativeHost.trace(s); }
error(s: string): void { this.nativeHost.error(s); }
directoryExists(directoryName: string): boolean {
directoryExists(): boolean {
// for tests pessimistically assume that directory always exists
return true;
}
@@ -338,8 +334,8 @@ namespace Harness.LanguageService {
class ClassifierShimProxy implements ts.Classifier {
constructor(private shim: ts.ClassifierShim) {
}
getEncodedLexicalClassifications(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.Classifications {
throw new Error("NYI");
getEncodedLexicalClassifications(_text: string, _lexState: ts.EndOfLineState, _classifyKeywordsInGenerics?: boolean): ts.Classifications {
return ts.notImplemented();
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
const result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split("\n");
@@ -411,7 +407,7 @@ namespace Harness.LanguageService {
getCompletionEntryDetails(fileName: string, position: number, entryName: string): ts.CompletionEntryDetails {
return unwrapJSONCallResult(this.shim.getCompletionEntryDetails(fileName, position, entryName));
}
getCompletionEntrySymbol(fileName: string, position: number, entryName: string): ts.Symbol {
getCompletionEntrySymbol(): ts.Symbol {
throw new Error("getCompletionEntrySymbol not implemented across the shim layer.");
}
getQuickInfoAtPosition(fileName: string, position: number): ts.QuickInfo {
@@ -490,7 +486,7 @@ namespace Harness.LanguageService {
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean {
return unwrapJSONCallResult(this.shim.isValidBraceCompletionAtPosition(fileName, position, openingBrace));
}
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): ts.CodeAction[] {
getCodeFixesAtPosition(): ts.CodeAction[] {
throw new Error("Not supported on the shim.");
}
getEmitOutput(fileName: string): ts.EmitOutput {
@@ -499,10 +495,10 @@ namespace Harness.LanguageService {
getProgram(): ts.Program {
throw new Error("Program can not be marshaled across the shim layer.");
}
getNonBoundSourceFile(fileName: string): ts.SourceFile {
getNonBoundSourceFile(): ts.SourceFile {
throw new Error("SourceFile can not be marshaled across the shim layer.");
}
getSourceFile(fileName: string): ts.SourceFile {
getSourceFile(): ts.SourceFile {
throw new Error("SourceFile can not be marshaled across the shim layer.");
}
dispose(): void { this.shim.dispose({}); }
@@ -572,11 +568,11 @@ namespace Harness.LanguageService {
super(cancellationToken, settings);
}
onMessage(message: string): void {
onMessage(): void {
}
writeMessage(message: string): void {
writeMessage(): void {
}
@@ -604,11 +600,11 @@ namespace Harness.LanguageService {
this.newLine = this.host.getNewLine();
}
onMessage(message: string): void {
onMessage(): void {
}
writeMessage(message: string): void {
writeMessage(_message: string): void {
}
write(message: string): void {
@@ -624,7 +620,7 @@ namespace Harness.LanguageService {
return snapshot && snapshot.getText(0, snapshot.getLength());
}
writeFile(name: string, text: string, writeByteOrderMark: boolean): void {
writeFile(): void {
}
resolvePath(path: string): string {
@@ -635,7 +631,7 @@ namespace Harness.LanguageService {
return !!this.host.getScriptSnapshot(path);
}
directoryExists(path: string): boolean {
directoryExists(): boolean {
// for tests assume that directory exists
return true;
}
@@ -644,18 +640,18 @@ namespace Harness.LanguageService {
return "";
}
exit(exitCode: number): void {
exit(): void {
}
createDirectory(directoryName: string): void {
throw new Error("Not Implemented Yet.");
createDirectory(_directoryName: string): void {
return ts.notImplemented();
}
getCurrentDirectory(): string {
return this.host.getCurrentDirectory();
}
getDirectories(path: string): string[] {
getDirectories(): string[] {
return [];
}
@@ -663,16 +659,16 @@ namespace Harness.LanguageService {
return ts.sys.getEnvironmentVariable(name);
}
readDirectory(path: string, extension?: string[], exclude?: string[], include?: string[]): string[] {
throw new Error("Not implemented Yet.");
readDirectory(_path: string, _extension?: string[], _exclude?: string[], _include?: string[]): string[] {
return ts.notImplemented();
}
watchFile(fileName: string, callback: (fileName: string) => void): ts.FileWatcher {
return { close() { } };
watchFile(): ts.FileWatcher {
return { close: ts.noop };
}
watchDirectory(path: string, callback: (path: string) => void, recursive?: boolean): ts.FileWatcher {
return { close() { } };
watchDirectory(): ts.FileWatcher {
return { close: ts.noop };
}
close(): void {
@@ -717,7 +713,7 @@ namespace Harness.LanguageService {
clearTimeout(timeoutId);
}
setImmediate(callback: (...args: any[]) => void, ms: number, ...args: any[]): any {
setImmediate(callback: (...args: any[]) => void, _ms: number, ...args: any[]): any {
return setImmediate(callback, args);
}
@@ -760,6 +756,6 @@ namespace Harness.LanguageService {
getHost() { return this.host; }
getLanguageService(): ts.LanguageService { return this.client; }
getClassifier(): ts.Classifier { throw new Error("getClassifier is not available using the server interface."); }
getPreProcessedFileInfo(fileName: string, fileContents: string): ts.PreProcessedFileInfo { throw new Error("getPreProcessedFileInfo is not available using the server interface."); }
getPreProcessedFileInfo(): ts.PreProcessedFileInfo { throw new Error("getPreProcessedFileInfo is not available using the server interface."); }
}
}
+15 -11
View File
@@ -173,7 +173,7 @@ namespace Playback {
path => callAndRecord(underlying.fileExists(path), recordLog.fileExists, { path }),
memoize(path => {
// If we read from the file, it must exist
if (findFileByPath(wrapper, replayLog.filesRead, path, /*throwFileNotFoundError*/ false)) {
if (findFileByPath(replayLog.filesRead, path, /*throwFileNotFoundError*/ false)) {
return true;
}
else {
@@ -217,7 +217,7 @@ namespace Playback {
recordLog.filesRead.push(logEntry);
return result;
},
memoize(path => findFileByPath(wrapper, replayLog.filesRead, path, /*throwFileNotFoundError*/ true).contents));
memoize(path => findFileByPath(replayLog.filesRead, path, /*throwFileNotFoundError*/ true).contents));
wrapper.readDirectory = recordReplay(wrapper.readDirectory, underlying)(
(path, extensions, exclude, include) => {
@@ -226,7 +226,7 @@ namespace Playback {
recordLog.directoriesRead.push(logEntry);
return result;
},
(path, extensions, exclude) => {
path => {
// Because extensions is an array of all allowed extension, we will want to merge each of the replayLog.directoriesRead into one
// if each of the directoriesRead has matched path with the given path (directory with same path but different extension will considered
// different entry).
@@ -244,7 +244,7 @@ namespace Playback {
wrapper.writeFile = recordReplay(wrapper.writeFile, underlying)(
(path: string, contents: string) => callAndRecord(underlying.writeFile(path, contents), recordLog.filesWritten, { path, contents, bom: false }),
(path: string, contents: string) => noOpReplay("writeFile"));
() => noOpReplay("writeFile"));
wrapper.exit = (exitCode) => {
if (recordLog !== undefined) {
@@ -295,7 +295,7 @@ namespace Playback {
return results[0].result;
}
function findFileByPath(wrapper: { resolvePath(s: string): string }, logArray: IOLogFile[],
function findFileByPath(logArray: IOLogFile[],
expectedPath: string, throwFileNotFoundError: boolean): FileInformation {
const normalizedName = ts.normalizePath(expectedPath).toLowerCase();
// Try to find the result through normal fileName
@@ -314,7 +314,7 @@ namespace Playback {
}
}
function noOpReplay(name: string) {
function noOpReplay(_name: string) {
// console.log("Swallowed write operation during replay: " + name);
}
@@ -322,13 +322,17 @@ namespace Playback {
const wrapper: PlaybackIO = <any>{};
initWrapper(wrapper, underlying);
wrapper.directoryName = (path): string => { throw new Error("NotSupported"); };
wrapper.createDirectory = (path): void => { throw new Error("NotSupported"); };
wrapper.directoryExists = (path): boolean => { throw new Error("NotSupported"); };
wrapper.deleteFile = (path): void => { throw new Error("NotSupported"); };
wrapper.listFiles = (path, filter, options): string[] => { throw new Error("NotSupported"); };
wrapper.directoryName = notSupported;
wrapper.createDirectory = notSupported;
wrapper.directoryExists = notSupported;
wrapper.deleteFile = notSupported;
wrapper.listFiles = notSupported;
return wrapper;
function notSupported(): never {
throw new Error("NotSupported");
}
}
export function wrapSystem(underlying: ts.System): PlaybackSystem {
+2 -2
View File
@@ -178,7 +178,7 @@ class ProjectRunner extends RunnerBase {
function createCompilerHost(): ts.CompilerHost {
return {
getSourceFile,
getDefaultLibFileName: options => Harness.Compiler.defaultLibFileName,
getDefaultLibFileName: () => Harness.Compiler.defaultLibFileName,
writeFile,
getCurrentDirectory,
getCanonicalFileName: Harness.Compiler.getCanonicalFileName,
@@ -421,7 +421,7 @@ class ProjectRunner extends RunnerBase {
return undefined;
}
function writeFile(fileName: string, data: string, writeByteOrderMark: boolean) {
function writeFile() {
}
}
+1 -1
View File
@@ -222,5 +222,5 @@ else {
}
if (!runUnitTests) {
// patch `describe` to skip unit tests
describe = <any>(function () { });
describe = ts.noop as any;
}
+3 -1
View File
@@ -11,7 +11,9 @@
"types": [
"node", "mocha", "chai"
],
"target": "es5"
"target": "es5",
"noUnusedLocals": true,
"noUnusedParameters": true
},
"files": [
"../compiler/core.ts",
+25 -35
View File
@@ -21,16 +21,15 @@ namespace ts {
args: <string[]>[],
newLine: "\r\n",
useCaseSensitiveFileNames: false,
write: (s: string) => {
},
readFile: (path: string, encoding?: string): string => {
write: noop,
readFile: (path: string): string => {
return path in fileMap ? fileMap[path].content : undefined;
},
writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => {
throw new Error("NYI");
writeFile: (_path: string, _data: string, _writeByteOrderMark?: boolean) => {
return ts.notImplemented();
},
resolvePath: (path: string): string => {
throw new Error("NYI");
resolvePath: (_path: string): string => {
return ts.notImplemented();
},
fileExists: (path: string): boolean => {
return path in fileMap;
@@ -38,31 +37,25 @@ namespace ts {
directoryExists: (path: string): boolean => {
return existingDirectories[path] || false;
},
createDirectory: (path: string) => {
},
createDirectory: noop,
getExecutingFilePath: (): string => {
return "";
},
getCurrentDirectory: (): string => {
return "";
},
getDirectories: (path: string) => [],
getEnvironmentVariable: (name: string) => "",
readDirectory: (path: string, extension?: string[], exclude?: string[], include?: string[]): string[] => {
throw new Error("NYI");
},
exit: (exitCode?: number) => {
},
watchFile: (path, callback) => {
return {
close: () => { }
};
},
watchDirectory: (path, callback, recursive?) => {
return {
close: () => { }
};
getDirectories: () => [],
getEnvironmentVariable: () => "",
readDirectory: (_path: string, _extension?: string[], _exclude?: string[], _include?: string[]): string[] => {
return ts.notImplemented();
},
exit: noop,
watchFile: () => ({
close: noop
}),
watchDirectory: () => ({
close: noop
}),
setTimeout,
clearTimeout,
setImmediate,
@@ -72,14 +65,14 @@ namespace ts {
function createProject(rootFile: string, serverHost: server.ServerHost): { project: server.Project, rootScriptInfo: server.ScriptInfo } {
const logger: server.Logger = {
close() { },
close: noop,
hasLevel: () => false,
loggingEnabled: () => false,
perftrc: (s: string) => { },
info: (s: string) => { },
startGroup: () => { },
endGroup: () => { },
msg: (s: string, type?: string) => { },
perftrc: noop,
info: noop,
startGroup: noop,
endGroup: noop,
msg: noop,
getLogFileName: (): string => undefined
};
@@ -116,10 +109,7 @@ namespace ts {
const originalFileExists = serverHost.fileExists;
{
// patch fileExists to make sure that disk is not touched
serverHost.fileExists = (fileName): boolean => {
assert.isTrue(false, "fileExists should not be called");
return false;
};
serverHost.fileExists = notImplemented;
const newContent = `import {x} from "f1"
var x: string = 1;`;
+34 -1
View File
@@ -1,4 +1,4 @@
/// <reference path="..\harness.ts" />
/// <reference path="..\harness.ts" />
/// <reference path="..\..\compiler\commandLineParser.ts" />
namespace ts {
@@ -338,5 +338,38 @@ namespace ts {
}
});
});
it("Parse explicit boolean flag value", () => {
assertParseResult(["--strictNullChecks", "false", "0.ts"],
{
errors: [],
fileNames: ["0.ts"],
options: {
strictNullChecks: false,
}
});
});
it("Parse non boolean argument after boolean flag", () => {
assertParseResult(["--noImplicitAny", "t", "0.ts"],
{
errors: [],
fileNames: ["t", "0.ts"],
options: {
noImplicitAny: true,
}
});
});
it("Parse implicit boolean flag value", () => {
assertParseResult(["--strictNullChecks"],
{
errors: [],
fileNames: [],
options: {
strictNullChecks: true,
}
});
});
});
}
+1 -1
View File
@@ -101,7 +101,7 @@ namespace ts {
Harness.Baseline.runBaseline("JSDocParsing/DocComments.parsesCorrectly." + name + ".json",
() => JSON.stringify(comment.jsDoc,
(k, v) => v && v.pos !== undefined ? JSON.parse(Utils.sourceFileToJSON(v)) : v, 4));
(_, v) => v && v.pos !== undefined ? JSON.parse(Utils.sourceFileToJSON(v)) : v, 4));
});
}
+56 -24
View File
@@ -3,6 +3,7 @@
namespace ts {
const caseInsensitiveBasePath = "c:/dev/";
const caseInsensitiveTsconfigPath = "c:/dev/tsconfig.json";
const caseInsensitiveHost = new Utils.MockParseConfigHost(caseInsensitiveBasePath, /*useCaseSensitiveFileNames*/ false, [
"c:/dev/a.ts",
"c:/dev/a.d.ts",
@@ -88,6 +89,8 @@ namespace ts {
"c:/dev/g.min.js/.g/g.ts"
]);
const defaultExcludes = ["node_modules", "bower_components", "jspm_packages"];
describe("matchFiles", () => {
describe("with literal file list", () => {
it("without exclusions", () => {
@@ -189,11 +192,14 @@ namespace ts {
};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -207,11 +213,14 @@ namespace ts {
};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -551,13 +560,16 @@ namespace ts {
};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {
"c:/dev": ts.WatchDirectoryFlags.Recursive
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -619,7 +631,7 @@ namespace ts {
it("with common package folders and no exclusions", () => {
const json = {
include: [
"**/a.ts"
"**/a.ts"
]
};
const expected: ts.ParsedCommandLine = {
@@ -701,13 +713,16 @@ namespace ts {
options: {
allowJs: false
},
errors: [],
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {
"c:/dev/js": ts.WatchDirectoryFlags.None
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -828,11 +843,14 @@ namespace ts {
};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude))]
,
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -1030,12 +1048,14 @@ namespace ts {
const expected: ts.ParsedCommandLine = {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**")
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -1051,11 +1071,14 @@ namespace ts {
};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude))
],
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -1071,12 +1094,14 @@ namespace ts {
const expected: ts.ParsedCommandLine = {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, "**/x/**/*")
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_multiple_recursive_directory_wildcards_Asterisk_Asterisk_Colon_0, "**/x/**/*"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -1122,12 +1147,14 @@ namespace ts {
const expected: ts.ParsedCommandLine = {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/../*")
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/../*"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -1142,12 +1169,14 @@ namespace ts {
const expected: ts.ParsedCommandLine = {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/../*")
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/../*"),
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(defaultExcludes))
],
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
@@ -1195,7 +1224,7 @@ namespace ts {
const expected: ts.ParsedCommandLine = {
options: {},
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/..")
ts.createCompilerDiagnostic(ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0, "**/y/..")
],
fileNames: [
"c:/dev/a.ts",
@@ -1320,11 +1349,14 @@ namespace ts {
};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
errors: [
ts.createCompilerDiagnostic(ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2,
caseInsensitiveTsconfigPath, JSON.stringify(json.include), JSON.stringify(json.exclude))
],
fileNames: [],
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath, undefined, caseInsensitiveTsconfigPath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
+7 -13
View File
@@ -323,7 +323,7 @@ namespace ts {
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
},
getDefaultLibFileName: () => "lib.d.ts",
writeFile: (fileName, content): void => { throw new Error("NotImplemented"); },
writeFile: notImplemented,
getCurrentDirectory: () => currentDirectory,
getDirectories: () => [],
getCanonicalFileName: fileName => fileName.toLowerCase(),
@@ -333,7 +333,7 @@ namespace ts {
const path = normalizePath(combinePaths(currentDirectory, fileName));
return path in files;
},
readFile: (fileName): string => { throw new Error("NotImplemented"); }
readFile: notImplemented
};
const program = createProgram(rootFiles, options, host);
@@ -403,7 +403,7 @@ export = C;
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
},
getDefaultLibFileName: () => "lib.d.ts",
writeFile: (fileName, content): void => { throw new Error("NotImplemented"); },
writeFile: notImplemented,
getCurrentDirectory: () => currentDirectory,
getDirectories: () => [],
getCanonicalFileName,
@@ -413,7 +413,7 @@ export = C;
const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName)));
return path in files;
},
readFile: (fileName): string => { throw new Error("NotImplemented"); }
readFile: notImplemented
};
const program = createProgram(rootFiles, options, host);
const diagnostics = sortAndDeduplicateDiagnostics(program.getSemanticDiagnostics().concat(program.getOptionsDiagnostics()));
@@ -940,15 +940,11 @@ import b = require("./moduleB");
});
});
function notImplemented(name: string): () => any {
return () => assert(`${name} is not implemented and should not be called`);
}
describe("ModuleResolutionHost.directoryExists", () => {
it("No 'fileExists' calls if containing directory is missing", () => {
const host: ModuleResolutionHost = {
readFile: notImplemented("readFile"),
fileExists: notImplemented("fileExists"),
readFile: notImplemented,
fileExists: notImplemented,
directoryExists: _ => false
};
@@ -1051,9 +1047,7 @@ import b = require("./moduleB");
fileExists : fileName => fileName in sourceFiles,
getSourceFile: fileName => sourceFiles[fileName],
getDefaultLibFileName: () => "lib.d.ts",
writeFile(file, text) {
throw new Error("NYI");
},
writeFile: notImplemented,
getCurrentDirectory: () => "/",
getDirectories: () => [],
getCanonicalFileName: f => f.toLowerCase(),
+7 -13
View File
@@ -111,13 +111,11 @@ namespace ts {
getDefaultLibFileName(): string {
return "lib.d.ts";
},
writeFile(file, text) {
throw new Error("NYI");
},
writeFile: notImplemented,
getCurrentDirectory(): string {
return "";
},
getDirectories(path: string): string[] {
getDirectories(): string[] {
return [];
},
getCanonicalFileName(fileName): string {
@@ -233,17 +231,13 @@ namespace ts {
it("fails if change affects type references", () => {
const program_1 = newProgram(files, ["a.ts"], { types: ["a"] });
updateProgram(program_1, ["a.ts"], { types: ["b"] }, files => {
});
updateProgram(program_1, ["a.ts"], { types: ["b"] }, noop);
assert.isTrue(!program_1.structureIsReused);
});
it("succeeds if change doesn't affect type references", () => {
const program_1 = newProgram(files, ["a.ts"], { types: ["a"] });
updateProgram(program_1, ["a.ts"], { types: ["a"] }, files => {
});
updateProgram(program_1, ["a.ts"], { types: ["a"] }, noop);
assert.isTrue(program_1.structureIsReused);
});
@@ -269,19 +263,19 @@ namespace ts {
it("fails if module kind changes", () => {
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.AMD }, files => void 0);
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.AMD }, noop);
assert.isTrue(!program_1.structureIsReused);
});
it("fails if rootdir changes", () => {
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, files => void 0);
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop);
assert.isTrue(!program_1.structureIsReused);
});
it("fails if config path changes", () => {
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/b/tsconfig.json" });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, files => void 0);
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, noop);
assert.isTrue(!program_1.structureIsReused);
});
@@ -62,7 +62,7 @@ describe("DocumentRegistry", () => {
const snapshot = ts.ScriptSnapshot.fromString(contents);
// Always treat any change as a full change.
snapshot.getChangeRange = old => ts.createTextChangeRange(ts.createTextSpan(0, contents.length), contents.length);
snapshot.getChangeRange = () => ts.createTextChangeRange(ts.createTextSpan(0, contents.length), contents.length);
// Simulate one LS getting the document.
documentRegistry.acquireDocument("file1.ts", defaultCompilerOptions, snapshot, /* version */ "1");
+16 -16
View File
@@ -10,32 +10,32 @@ namespace ts.server {
useCaseSensitiveFileNames: true,
write(s): void { lastWrittenToHost = s; },
readFile(): string { return void 0; },
writeFile(): void {},
writeFile: noop,
resolvePath(): string { return void 0; },
fileExists: () => false,
directoryExists: () => false,
getDirectories: () => [],
createDirectory(): void {},
createDirectory: noop,
getExecutingFilePath(): string { return void 0; },
getCurrentDirectory(): string { return void 0; },
getEnvironmentVariable(name: string): string { return ""; },
getEnvironmentVariable(): string { return ""; },
readDirectory(): string[] { return []; },
exit(): void { },
setTimeout(callback, ms, ...args) { return 0; },
clearTimeout(timeoutId) { },
exit: noop,
setTimeout() { return 0; },
clearTimeout: noop,
setImmediate: () => 0,
clearImmediate() {}
clearImmediate: noop
};
const nullCancellationToken: HostCancellationToken = { isCancellationRequested: () => false };
const mockLogger: Logger = {
close(): void {},
close: noop,
hasLevel(): boolean { return false; },
loggingEnabled(): boolean { return false; },
perftrc(s: string): void {},
info(s: string): void {},
startGroup(): void {},
endGroup(): void {},
msg(s: string, type?: string): void {},
perftrc: noop,
info: noop,
startGroup: noop,
endGroup: noop,
msg: noop,
getLogFileName: (): string => undefined
};
@@ -245,7 +245,7 @@ namespace ts.server {
responseRequired: true
};
session.addProtocolHandler(command, (req) => result);
session.addProtocolHandler(command, () => result);
expect(session.executeCommand({
command,
@@ -263,9 +263,9 @@ namespace ts.server {
};
const command = "newhandle";
session.addProtocolHandler(command, (req) => resp);
session.addProtocolHandler(command, () => resp);
expect(() => session.addProtocolHandler(command, (req) => resp))
expect(() => session.addProtocolHandler(command, () => resp))
.to.throw(`Protocol handler already exists for command "${command}"`);
});
});
+67
View File
@@ -28,6 +28,14 @@ namespace ts {
assert.isTrue(arrayIsEqualTo(parsed.fileNames.sort(), expectedFileList.sort()));
}
function assertParseFileDiagnostics(jsonText: string, configFileName: string, basePath: string, allFileList: string[], expectedDiagnosticCode: number) {
const json = JSON.parse(jsonText);
const host: ParseConfigHost = new Utils.MockParseConfigHost(basePath, true, allFileList);
const parsed = ts.parseJsonConfigFileContent(json, host, basePath, /*existingOptions*/ undefined, configFileName);
assert.isTrue(parsed.errors.length >= 0);
assert.isTrue(parsed.errors.filter(e => e.code === expectedDiagnosticCode).length > 0, `Expected error code ${expectedDiagnosticCode} to be in ${JSON.stringify(parsed.errors)}`);
}
it("returns empty config for file with only whitespaces", () => {
assertParseResult("", { config : {} });
assertParseResult(" ", { config : {} });
@@ -202,5 +210,64 @@ namespace ts {
assert.isTrue(diagnostics.length === 2);
assert.equal(JSON.stringify(configJsonObject), JSON.stringify(expectedResult));
});
it("generates errors for empty files list", () => {
const content = `{
"files": []
}`;
assertParseFileDiagnostics(content,
"/apath/tsconfig.json",
"tests/cases/unittests",
["/apath/a.ts"],
Diagnostics.The_files_list_in_config_file_0_is_empty.code);
});
it("generates errors for directory with no .ts files", () => {
const content = `{
}`;
assertParseFileDiagnostics(content,
"/apath/tsconfig.json",
"tests/cases/unittests",
["/apath/a.js"],
Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code);
});
it("generates errors for empty directory", () => {
const content = `{
"compilerOptions": {
"allowJs": true
}
}`;
assertParseFileDiagnostics(content,
"/apath/tsconfig.json",
"tests/cases/unittests",
[],
Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code);
});
it("generates errors for empty include", () => {
const content = `{
"include": []
}`;
assertParseFileDiagnostics(content,
"/apath/tsconfig.json",
"tests/cases/unittests",
["/apath/a.ts"],
Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code);
});
it("generates errors for includes with outDir", () => {
const content = `{
"compilerOptions": {
"outDir": "./"
},
"include": ["**/*"]
}`;
assertParseFileDiagnostics(content,
"/apath/tsconfig.json",
"tests/cases/unittests",
["/apath/a.ts"],
Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code);
});
});
}
+14 -22
View File
@@ -23,10 +23,6 @@ namespace ts.projectSystem {
readonly callback: TI.RequestCompletedAction;
}
export function notImplemented(): any {
throw new Error("Not yet implemented");
}
export const nullLogger: server.Logger = {
close: () => void 0,
hasLevel: () => void 0,
@@ -72,7 +68,7 @@ namespace ts.projectSystem {
this.postExecActions.forEach((act, i) => assert.equal(act.requestKind, expected[i], "Unexpected post install action"));
}
onProjectClosed(p: server.Project) {
onProjectClosed() {
}
attach(projectService: server.ProjectService) {
@@ -83,7 +79,7 @@ namespace ts.projectSystem {
return this.installTypingHost;
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
switch (requestKind) {
case TI.NpmViewRequest:
case TI.NpmInstallRequest:
@@ -98,8 +94,8 @@ namespace ts.projectSystem {
this.projectService.updateTypingsForProject(response);
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions) {
const request = server.createInstallTypingsRequest(project, typingOptions, this.globalTypingsCacheLocation);
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
const request = server.createInstallTypingsRequest(project, typingOptions, unresolvedImports, this.globalTypingsCacheLocation);
this.install(request);
}
@@ -122,7 +118,7 @@ namespace ts.projectSystem {
return JSON.stringify({ dependencies: dependencies });
}
export function getExecutingFilePathFromLibFile(libFilePath: string): string {
export function getExecutingFilePathFromLibFile(): string {
return combinePaths(getDirectoryPath(libFile.path), "tsc.js");
}
@@ -154,16 +150,13 @@ namespace ts.projectSystem {
currentDirectory?: string;
}
export function createServerHost(fileOrFolderList: FileOrFolder[],
params?: TestServerHostCreationParameters,
libFilePath: string = libFile.path): TestServerHost {
export function createServerHost(fileOrFolderList: FileOrFolder[], params?: TestServerHostCreationParameters): TestServerHost {
if (!params) {
params = {};
}
const host = new TestServerHost(
params.useCaseSensitiveFileNames !== undefined ? params.useCaseSensitiveFileNames : false,
params.executingFilePath || getExecutingFilePathFromLibFile(libFilePath),
params.executingFilePath || getExecutingFilePathFromLibFile(),
params.currentDirectory || "/",
fileOrFolderList);
host.createFileOrFolder(safeList, /*createParentDirectory*/ true);
@@ -322,9 +315,9 @@ namespace ts.projectSystem {
count() {
let n = 0;
/* tslint:disable:no-unused-variable */
for (const _ in this.map) {
/* tslint:enable:no-unused-variable */
// TODO: GH#11734
_;
n++;
}
return n;
@@ -473,7 +466,7 @@ namespace ts.projectSystem {
}
// TOOD: record and invoke callbacks to simulate timer events
setTimeout(callback: TimeOutCallback, time: number, ...args: any[]) {
setTimeout(callback: TimeOutCallback, _time: number, ...args: any[]) {
return this.timeoutCallbacks.register(callback, args);
};
@@ -490,7 +483,7 @@ namespace ts.projectSystem {
this.timeoutCallbacks.invoke();
}
setImmediate(callback: TimeOutCallback, time: number, ...args: any[]) {
setImmediate(callback: TimeOutCallback, _time: number, ...args: any[]) {
return this.immediateCallbacks.register(callback, args);
}
@@ -522,15 +515,14 @@ namespace ts.projectSystem {
this.reloadFS(filesOrFolders);
}
write(s: string) {
}
write() { }
readonly readFile = (s: string) => (<File>this.fs.get(this.toPath(s))).content;
readonly resolvePath = (s: string) => s;
readonly getExecutingFilePath = () => this.executingFilePath;
readonly getCurrentDirectory = () => this.currentDirectory;
readonly exit = () => notImplemented();
readonly getEnvironmentVariable = (v: string) => notImplemented();
readonly exit = notImplemented;
readonly getEnvironmentVariable = notImplemented;
}
export function makeSessionRequest<T>(command: string, args: T) {
+229 -28
View File
@@ -81,7 +81,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -125,7 +125,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -217,11 +217,11 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions) {
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions);
super.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/jquery"];
const typingFiles = [jquery];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -275,7 +275,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/lodash", "@types/react"];
const typingFiles = [lodash, react];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -319,11 +319,11 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions) {
enqueueInstallTypingsRequest(project: server.Project, typingOptions: TypingOptions, unresolvedImports: server.SortedReadonlyArray<string>) {
enqueueIsCalled = true;
super.enqueueInstallTypingsRequest(project, typingOptions);
super.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings: string[] = [];
const typingFiles: FileOrFolder[] = [];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -398,7 +398,7 @@ namespace ts.projectSystem {
constructor() {
super(host);
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment"];
const typingFiles = [commander, express, jquery, moment];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -477,7 +477,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { throttleLimit: 3 });
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
const installedTypings = ["@types/commander", "@types/express", "@types/jquery", "@types/moment", "@types/lodash"];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
}
@@ -567,9 +567,9 @@ namespace ts.projectSystem {
constructor() {
super(host, { throttleLimit: 3 });
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: TI.RequestCompletedAction): void {
executeRequest(requestKind: TI.RequestKind, _requestId: number, args: string[], _cwd: string, cb: TI.RequestCompletedAction): void {
if (requestKind === TI.NpmInstallRequest) {
let typingFiles: (FileOrFolder & { typings: string}) [] = [];
let typingFiles: (FileOrFolder & { typings: string })[] = [];
if (args.indexOf("@types/commander") >= 0) {
typingFiles = [commander, jquery, lodash, cordova];
}
@@ -591,7 +591,7 @@ namespace ts.projectSystem {
projectFileName: projectFileName1,
options: { allowJS: true, moduleResolution: ModuleResolutionKind.NodeJs },
rootFiles: [toExternalFile(lodashJs.path), toExternalFile(commanderJs.path), toExternalFile(file3.path)],
typingOptions: { include: ["jquery", "cordova" ] }
typingOptions: { include: ["jquery", "cordova"] }
});
installer.checkPendingCommands([TI.NpmViewRequest, TI.NpmViewRequest, TI.NpmViewRequest]);
@@ -626,7 +626,7 @@ namespace ts.projectSystem {
installer.executePendingCommands();
checkProjectActualFiles(p1, [lodashJs.path, commanderJs.path, file3.path, commander.path, jquery.path, lodash.path, cordova.path]);
checkProjectActualFiles(p2, [file3.path, grunt.path, gulp.path ]);
checkProjectActualFiles(p2, [file3.path, grunt.path, gulp.path]);
});
it("configured projects discover from node_modules", () => {
@@ -655,7 +655,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -687,10 +687,10 @@ namespace ts.projectSystem {
const bowerJson = {
path: "/bower.json",
content: JSON.stringify({
"dependencies": {
"jquery": "^3.1.0"
}
})
"dependencies": {
"jquery": "^3.1.0"
}
})
};
const jqueryDTS = {
path: "/tmp/node_modules/@types/jquery/index.d.ts",
@@ -701,7 +701,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/jquery"];
const typingFiles = [jqueryDTS];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
@@ -720,26 +720,196 @@ namespace ts.projectSystem {
checkNumberOfProjects(projectService, { configuredProjects: 1 });
checkProjectActualFiles(p, [app.path, jqueryDTS.path]);
});
it("Malformed package.json should be watched", () => {
const f = {
path: "/a/b/app.js",
content: "var x = 1"
};
const brokenPackageJson = {
path: "/a/b/package.json",
content: `{ "dependencies": { "co } }`
};
const fixedPackageJson = {
path: brokenPackageJson.path,
content: `{ "dependencies": { "commander": "0.0.2" } }`
};
const cachePath = "/a/cache/";
const commander = {
path: cachePath + "node_modules/@types/commander/index.d.ts",
content: "export let x: number"
};
const host = createServerHost([f, brokenPackageJson]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/commander"];
const typingFiles = [commander];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
}
})();
const service = createProjectService(host, { typingsInstaller: installer });
service.openClientFile(f.path);
installer.checkPendingCommands([]);
host.reloadFS([f, fixedPackageJson]);
host.triggerFileWatcherCallback(fixedPackageJson.path, /*removed*/ false);
// expected one view and one install request
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
service.checkNumberOfProjects({ inferredProjects: 1 });
checkProjectActualFiles(service.inferredProjects[0], [f.path, commander.path]);
});
it("should install typings for unresolved imports", () => {
const file = {
path: "/a/b/app.js",
content: `
import * as fs from "fs";
import * as commander from "commander";`
};
const cachePath = "/a/cache";
const node = {
path: cachePath + "/node_modules/@types/node/index.d.ts",
content: "export let x: number"
};
const commander = {
path: cachePath + "/node_modules/@types/commander/index.d.ts",
content: "export let y: string"
};
const host = createServerHost([file]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: cachePath });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, _args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
const installedTypings = ["@types/node", "@types/commander"];
const typingFiles = [node, commander];
executeCommand(this, host, installedTypings, typingFiles, requestKind, cb);
}
})();
const service = createProjectService(host, { typingsInstaller: installer });
service.openClientFile(file.path);
service.checkNumberOfProjects({ inferredProjects: 1 });
checkProjectActualFiles(service.inferredProjects[0], [file.path]);
installer.installAll([TI.NpmViewRequest, TI.NpmViewRequest], [TI.NpmInstallRequest]);
assert.isTrue(host.fileExists(node.path), "typings for 'node' should be created");
assert.isTrue(host.fileExists(commander.path), "typings for 'commander' should be created");
checkProjectActualFiles(service.inferredProjects[0], [file.path, node.path, commander.path]);
});
it("should pick typing names from non-relative unresolved imports", () => {
const f1 = {
path: "/a/b/app.js",
content: `
import * as a from "foo/a/a";
import * as b from "foo/a/b";
import * as c from "foo/a/c";
import * as d from "@bar/router/";
import * as e from "@bar/common/shared";
import * as e from "@bar/common/apps";
import * as f from "./lib"
`
};
const host = createServerHost([f1]);
const installer = new (class extends Installer {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" });
}
executeRequest(requestKind: TI.RequestKind, _requestId: number, args: string[], _cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
if (requestKind === TI.NpmViewRequest) {
// args should have only non-scoped packages - scoped packages are not yet supported
assert.deepEqual(args, ["foo"]);
}
executeCommand(this, host, ["foo"], [], requestKind, cb);
}
})();
const projectService = createProjectService(host, { typingsInstaller: installer });
projectService.openClientFile(f1.path);
projectService.checkNumberOfProjects({ inferredProjects: 1 });
const proj = projectService.inferredProjects[0];
proj.updateGraph();
assert.deepEqual(
proj.getCachedUnresolvedImportsPerFile_TestOnly().get(<Path>f1.path),
["foo", "foo", "foo", "@bar/router", "@bar/common", "@bar/common"]
);
installer.installAll([TI.NpmViewRequest], [TI.NpmInstallRequest]);
});
it("cached unresolved typings are not recomputed if program structure did not change", () => {
const host = createServerHost([]);
const session = createSession(host);
const f = {
path: "/a/app.js",
content: `
import * as fs from "fs";
import * as cmd from "commander
`
};
session.executeCommand(<server.protocol.OpenRequest>{
seq: 1,
type: "request",
command: "open",
arguments: {
file: f.path,
fileContent: f.content
}
});
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { inferredProjects: 1 });
const proj = projectService.inferredProjects[0];
const version1 = proj.getCachedUnresolvedImportsPerFile_TestOnly().getVersion();
// make a change that should not affect the structure of the program
session.executeCommand(<server.protocol.ChangeRequest>{
seq: 2,
type: "request",
command: "change",
arguments: {
file: f.path,
insertString: "\nlet x = 1;",
line: 2,
offset: 0,
endLine: 2,
endOffset: 0
}
});
host.checkTimeoutQueueLength(1);
host.runQueuedTimeoutCallbacks();
const version2 = proj.getCachedUnresolvedImportsPerFile_TestOnly().getVersion();
assert.equal(version1, version2, "set of unresolved imports should not change");
});
});
describe("Validate package name:", () => {
it ("name cannot be too long", () => {
it("name cannot be too long", () => {
let packageName = "a";
for (let i = 0; i < 8; i++) {
packageName += packageName;
}
assert.equal(TI.validatePackageName(packageName), TI.PackageNameValidationResult.NameTooLong);
});
it ("name cannot start with dot", () => {
it("name cannot start with dot", () => {
assert.equal(TI.validatePackageName(".foo"), TI.PackageNameValidationResult.NameStartsWithDot);
});
it ("name cannot start with underscore", () => {
it("name cannot start with underscore", () => {
assert.equal(TI.validatePackageName("_foo"), TI.PackageNameValidationResult.NameStartsWithUnderscore);
});
it ("scoped packages not supported", () => {
it("scoped packages not supported", () => {
assert.equal(TI.validatePackageName("@scope/bar"), TI.PackageNameValidationResult.ScopedPackagesNotSupported);
});
it ("non URI safe characters are not supported", () => {
it("non URI safe characters are not supported", () => {
assert.equal(TI.validatePackageName(" scope "), TI.PackageNameValidationResult.NameContainsNonURISafeCharacters);
assert.equal(TI.validatePackageName("; say Hello from TypeScript! #"), TI.PackageNameValidationResult.NameContainsNonURISafeCharacters);
assert.equal(TI.validatePackageName("a/b/c"), TI.PackageNameValidationResult.NameContainsNonURISafeCharacters);
@@ -747,7 +917,7 @@ namespace ts.projectSystem {
});
describe("Invalid package names", () => {
it ("should not be installed", () => {
it("should not be installed", () => {
const f1 = {
path: "/a/b/app.js",
content: "let x = 1"
@@ -766,7 +936,7 @@ namespace ts.projectSystem {
constructor() {
super(host, { globalTypingsCacheLocation: "/tmp" }, { isEnabled: () => true, writeLine: msg => messages.push(msg) });
}
executeRequest(requestKind: TI.RequestKind, requestId: number, args: string[], cwd: string, cb: server.typingsInstaller.RequestCompletedAction) {
executeRequest() {
assert(false, "runCommand should not be invoked");
}
})();
@@ -777,4 +947,35 @@ namespace ts.projectSystem {
assert.isTrue(messages.indexOf("Package name '; say Hello from TypeScript! #' contains non URI safe characters") > 0, "should find package with invalid name");
});
});
describe("discover typings", () => {
it("should return node for core modules", () => {
const f = {
path: "/a/b/app.js",
content: ""
};
const host = createServerHost([f]);
const cache = createMap<string>();
for (const name of JsTyping.nodeCoreModuleList) {
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enableAutoDiscovery: true }, [name, "somename"]);
assert.deepEqual(result.newTypingNames.sort(), ["node", "somename"]);
}
});
it("should use cached locaitons", () => {
const f = {
path: "/a/b/app.js",
content: ""
};
const node = {
path: "/a/b/node.d.ts",
content: ""
};
const host = createServerHost([f, node]);
const cache = createMap<string>({ "node": node.path });
const result = JsTyping.discoverTypings(host, [f.path], getDirectoryPath(<Path>f.path), /*safeListPath*/ undefined, cache, { enableAutoDiscovery: true }, ["fs", "bar"]);
assert.deepEqual(result.cachedTypingPaths, [node.path]);
assert.deepEqual(result.newTypingNames, ["bar"]);
});
});
}
+4 -4
View File
@@ -205,13 +205,13 @@ interface NumberConstructor {
* number. Only finite values of the type number, result in true.
* @param number A numeric value.
*/
isFinite(number: number): boolean;
isFinite(value: any): value is number;
/**
* Returns true if the value passed is an integer, false otherwise.
* @param number A numeric value.
*/
isInteger(number: number): boolean;
isInteger(value: any): value is number;
/**
* Returns a Boolean value that indicates whether a value is the reserved value NaN (not a
@@ -219,13 +219,13 @@ interface NumberConstructor {
* to a number. Only values of the type number, that are also NaN, result in true.
* @param number A numeric value.
*/
isNaN(number: number): boolean;
isNaN(value: any): value is number;
/**
* Returns true if the value passed is a safe integer.
* @param number A numeric value.
*/
isSafeInteger(number: number): boolean;
isSafeInteger(value: any): value is number;
/**
* The value of the largest integer n such that n and n + 1 are both exactly representable as
+1 -1
View File
@@ -122,7 +122,7 @@ namespace ts.server {
}
protected forEachFileInfo(action: (fileInfo: T) => any) {
this.fileInfos.forEachValue((path: Path, value: T) => action(value));
this.fileInfos.forEachValue((_path, value) => action(value));
}
abstract getFilesAffectedBy(scriptInfo: ScriptInfo): string[];
+3 -1
View File
@@ -11,7 +11,9 @@
"types": [
"node"
],
"target": "es5"
"target": "es5",
"noUnusedLocals": true,
"noUnusedParameters": true
},
"files": [
"cancellationToken.ts"
+33 -38
View File
@@ -5,11 +5,6 @@ namespace ts.server {
writeMessage(message: string): void;
}
interface CompletionEntry extends CompletionInfo {
fileName: string;
position: number;
}
interface RenameEntry extends RenameInfo {
fileName: string;
position: number;
@@ -246,8 +241,8 @@ namespace ts.server {
return response.body[0];
}
getCompletionEntrySymbol(fileName: string, position: number, entryName: string): Symbol {
throw new Error("Not Implemented Yet.");
getCompletionEntrySymbol(_fileName: string, _position: number, _entryName: string): Symbol {
return notImplemented();
}
getNavigateToItems(searchValue: string): NavigateToItem[] {
@@ -278,7 +273,7 @@ namespace ts.server {
});
}
getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): ts.TextChange[] {
getFormattingEditsForRange(fileName: string, start: number, end: number, _options: ts.FormatCodeOptions): ts.TextChange[] {
const startLineOffset = this.positionToOneBasedLineOffset(fileName, start);
const endLineOffset = this.positionToOneBasedLineOffset(fileName, end);
const args: protocol.FormatRequestArgs = {
@@ -300,7 +295,7 @@ namespace ts.server {
return this.getFormattingEditsForRange(fileName, 0, this.host.getScriptSnapshot(fileName).getLength(), options);
}
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): ts.TextChange[] {
getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, _options: FormatCodeOptions): ts.TextChange[] {
const lineOffset = this.positionToOneBasedLineOffset(fileName, position);
const args: protocol.FormatOnKeyRequestArgs = {
file: fileName,
@@ -390,7 +385,7 @@ namespace ts.server {
});
}
findReferences(fileName: string, position: number): ReferencedSymbol[] {
findReferences(_fileName: string, _position: number): ReferencedSymbol[] {
// Not yet implemented.
return [];
}
@@ -419,8 +414,8 @@ namespace ts.server {
});
}
getEmitOutput(fileName: string): EmitOutput {
throw new Error("Not Implemented Yet.");
getEmitOutput(_fileName: string): EmitOutput {
return notImplemented();
}
getSyntacticDiagnostics(fileName: string): Diagnostic[] {
@@ -441,7 +436,7 @@ namespace ts.server {
return (<protocol.DiagnosticWithLinePosition[]>response.body).map(entry => this.convertDiagnostic(entry, fileName));
}
convertDiagnostic(entry: protocol.DiagnosticWithLinePosition, fileName: string): Diagnostic {
convertDiagnostic(entry: protocol.DiagnosticWithLinePosition, _fileName: string): Diagnostic {
let category: DiagnosticCategory;
for (const id in DiagnosticCategory) {
if (typeof id === "string" && entry.category === id.toLowerCase()) {
@@ -462,7 +457,7 @@ namespace ts.server {
}
getCompilerOptionsDiagnostics(): Diagnostic[] {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo {
@@ -566,12 +561,12 @@ namespace ts.server {
this.lineOffsetToPosition(fileName, span.end, lineMap));
}
getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan {
throw new Error("Not Implemented Yet.");
getNameOrDottedNameSpan(_fileName: string, _startPos: number, _endPos: number): TextSpan {
return notImplemented();
}
getBreakpointStatementAtPosition(fileName: string, position: number): TextSpan {
throw new Error("Not Implemented Yet.");
getBreakpointStatementAtPosition(_fileName: string, _position: number): TextSpan {
return notImplemented();
}
getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems {
@@ -660,20 +655,20 @@ namespace ts.server {
}
}
getOutliningSpans(fileName: string): OutliningSpan[] {
throw new Error("Not Implemented Yet.");
getOutliningSpans(_fileName: string): OutliningSpan[] {
return notImplemented();
}
getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[] {
throw new Error("Not Implemented Yet.");
getTodoComments(_fileName: string, _descriptors: TodoCommentDescriptor[]): TodoComment[] {
return notImplemented();
}
getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion {
throw new Error("Not Implemented Yet.");
getDocCommentTemplateAtPosition(_fileName: string, _position: number): TextInsertion {
return notImplemented();
}
isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean {
throw new Error("Not Implemented Yet.");
isValidBraceCompletionAtPosition(_fileName: string, _position: number, _openingBrace: number): boolean {
return notImplemented();
}
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[] {
@@ -739,35 +734,35 @@ namespace ts.server {
});
}
getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number {
throw new Error("Not Implemented Yet.");
getIndentationAtPosition(_fileName: string, _position: number, _options: EditorOptions): number {
return notImplemented();
}
getSyntacticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] {
throw new Error("Not Implemented Yet.");
getSyntacticClassifications(_fileName: string, _span: TextSpan): ClassifiedSpan[] {
return notImplemented();
}
getSemanticClassifications(fileName: string, span: TextSpan): ClassifiedSpan[] {
throw new Error("Not Implemented Yet.");
getSemanticClassifications(_fileName: string, _span: TextSpan): ClassifiedSpan[] {
return notImplemented();
}
getEncodedSyntacticClassifications(fileName: string, span: TextSpan): Classifications {
throw new Error("Not Implemented Yet.");
getEncodedSyntacticClassifications(_fileName: string, _span: TextSpan): Classifications {
return notImplemented();
}
getEncodedSemanticClassifications(fileName: string, span: TextSpan): Classifications {
throw new Error("Not Implemented Yet.");
getEncodedSemanticClassifications(_fileName: string, _span: TextSpan): Classifications {
return notImplemented();
}
getProgram(): Program {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
getNonBoundSourceFile(fileName: string): SourceFile {
getNonBoundSourceFile(_fileName: string): SourceFile {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
getSourceFile(fileName: string): SourceFile {
getSourceFile(_fileName: string): SourceFile {
throw new Error("SourceFile objects are not serializable through the server protocol.");
}
+3 -3
View File
@@ -287,13 +287,13 @@ namespace ts.server {
}
switch (response.kind) {
case "set":
this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings);
project.updateGraph();
this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.unresolvedImports, response.typings);
break;
case "invalidate":
this.typingsCache.invalidateCachedTypingsForProject(project);
this.typingsCache.deleteTypingsForProject(response.projectName);
break;
}
project.updateGraph();
}
setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void {
+45 -6
View File
@@ -9,6 +9,8 @@ namespace ts.server {
private readonly resolvedTypeReferenceDirectives = createFileMap<Map<ResolvedTypeReferenceDirectiveWithFailedLookupLocations>>();
private readonly getCanonicalFileName: (fileName: string) => string;
private filesWithChangedSetOfUnresolvedImports: Path[];
private readonly resolveModuleName: typeof resolveModuleName;
readonly trace: (s: string) => void;
@@ -39,13 +41,24 @@ namespace ts.server {
};
}
public startRecordingFilesWithChangedResolutions() {
this.filesWithChangedSetOfUnresolvedImports = [];
}
public finishRecordingFilesWithChangedResolutions() {
const collected = this.filesWithChangedSetOfUnresolvedImports;
this.filesWithChangedSetOfUnresolvedImports = undefined;
return collected;
}
private resolveNamesWithLocalCache<T extends { failedLookupLocations: string[] }, R>(
names: string[],
containingFile: string,
cache: ts.FileMap<Map<T>>,
loader: (name: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost) => T,
getResult: (s: T) => R,
getResultFileName: (result: R) => string): R[] {
getResultFileName: (result: R) => string | undefined,
logChanges: boolean): R[] {
const path = toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName);
const currentResolutionsInFile = cache.get(path);
@@ -67,6 +80,11 @@ namespace ts.server {
else {
newResolutions[name] = resolution = loader(name, containingFile, compilerOptions, this);
}
if (logChanges && this.filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
this.filesWithChangedSetOfUnresolvedImports.push(path);
// reset log changes to avoid recording the same file multiple times
logChanges = false;
}
}
ts.Debug.assert(resolution !== undefined);
@@ -78,6 +96,24 @@ namespace ts.server {
cache.set(path, newResolutions);
return resolvedModules;
function resolutionIsEqualTo(oldResolution: T, newResolution: T): boolean {
if (oldResolution === newResolution) {
return true;
}
if (!oldResolution || !newResolution) {
return false;
}
const oldResult = getResult(oldResolution);
const newResult = getResult(newResolution);
if (oldResult === newResult) {
return true;
}
if (!oldResult || !newResult) {
return false;
}
return getResultFileName(oldResult) === getResultFileName(newResult);
}
function moduleResolutionIsValid(resolution: T): boolean {
if (!resolution) {
return false;
@@ -111,11 +147,13 @@ namespace ts.server {
}
resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[] {
return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, resolveTypeReferenceDirective, m => m.resolvedTypeReferenceDirective, r => r.resolvedFileName);
return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, resolveTypeReferenceDirective,
m => m.resolvedTypeReferenceDirective, r => r.resolvedFileName, /*logChanges*/ false);
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, m => m.resolvedModule, r => r.resolvedFileName);
return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName,
m => m.resolvedModule, r => r.resolvedFileName, /*logChanges*/ true);
}
getDefaultLibFileName() {
@@ -182,10 +220,11 @@ namespace ts.server {
}
setCompilationSettings(opt: ts.CompilerOptions) {
if (changesAffectModuleResolution(this.compilationSettings, opt)) {
this.resolvedModuleNames.clear();
this.resolvedTypeReferenceDirectives.clear();
}
this.compilationSettings = opt;
// conservatively assume that changing compiler options might affect module resolution strategy
this.resolvedModuleNames.clear();
this.resolvedTypeReferenceDirectives.clear();
}
}
}
+103 -3
View File
@@ -62,12 +62,43 @@ namespace ts.server {
projectErrors: Diagnostic[];
}
export class UnresolvedImportsMap {
readonly perFileMap = createFileMap<ReadonlyArray<string>>();
private version = 0;
public clear() {
this.perFileMap.clear();
this.version = 0;
}
public getVersion() {
return this.version;
}
public remove(path: Path) {
this.perFileMap.remove(path);
this.version++;
}
public get(path: Path) {
return this.perFileMap.get(path);
}
public set(path: Path, value: ReadonlyArray<string>) {
this.perFileMap.set(path, value);
this.version++;
}
}
export abstract class Project {
private rootFiles: ScriptInfo[] = [];
private rootFilesMap: FileMap<ScriptInfo> = createFileMap<ScriptInfo>();
private lsHost: ServerLanguageServiceHost;
private program: ts.Program;
private cachedUnresolvedImportsPerFile = new UnresolvedImportsMap();
private lastCachedUnresolvedImportsList: SortedReadonlyArray<string>;
private languageService: LanguageService;
builder: Builder;
/**
@@ -91,7 +122,7 @@ namespace ts.server {
*/
private projectStateVersion = 0;
private typingFiles: TypingsArray;
private typingFiles: SortedReadonlyArray<string>;
protected projectErrors: Diagnostic[];
@@ -107,6 +138,10 @@ namespace ts.server {
return hasOneOrMoreJsAndNoTsFiles(this);
}
public getCachedUnresolvedImportsPerFile_TestOnly() {
return this.cachedUnresolvedImportsPerFile;
}
constructor(
readonly projectKind: ProjectKind,
readonly projectService: ProjectService,
@@ -326,6 +361,7 @@ namespace ts.server {
removeFile(info: ScriptInfo, detachFromProject = true) {
this.removeRootFileIfNecessary(info);
this.lsHost.notifyFileRemoved(info);
this.cachedUnresolvedImportsPerFile.remove(info.path);
if (detachFromProject) {
info.detachFromProject(this);
@@ -338,6 +374,38 @@ namespace ts.server {
this.projectStateVersion++;
}
private extractUnresolvedImportsFromSourceFile(file: SourceFile, result: string[]) {
const cached = this.cachedUnresolvedImportsPerFile.get(file.path);
if (cached) {
// found cached result - use it and return
for (const f of cached) {
result.push(f);
}
return;
}
let unresolvedImports: string[];
if (file.resolvedModules) {
for (const name in file.resolvedModules) {
// pick unresolved non-relative names
if (!file.resolvedModules[name] && !isExternalModuleNameRelative(name)) {
// for non-scoped names extract part up-to the first slash
// for scoped names - extract up to the second slash
let trimmed = name.trim();
let i = trimmed.indexOf("/");
if (i !== -1 && trimmed.charCodeAt(0) === CharacterCodes.at) {
i = trimmed.indexOf("/", i + 1);
}
if (i !== -1) {
trimmed = trimmed.substr(0, i);
}
(unresolvedImports || (unresolvedImports = [])).push(trimmed);
result.push(trimmed);
}
}
}
this.cachedUnresolvedImportsPerFile.set(file.path, unresolvedImports || emptyArray);
}
/**
* Updates set of files that contribute to this project
* @returns: true if set of files in the project stays the same and false - otherwise.
@@ -346,8 +414,35 @@ namespace ts.server {
if (!this.languageServiceEnabled) {
return true;
}
this.lsHost.startRecordingFilesWithChangedResolutions();
let hasChanges = this.updateGraphWorker();
const cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges);
const changedFiles: ReadonlyArray<Path> = this.lsHost.finishRecordingFilesWithChangedResolutions() || emptyArray;
for (const file of changedFiles) {
// delete cached information for changed files
this.cachedUnresolvedImportsPerFile.remove(file);
}
// 1. no changes in structure, no changes in unresolved imports - do nothing
// 2. no changes in structure, unresolved imports were changed - collect unresolved imports for all files
// (can reuse cached imports for files that were not changed)
// 3. new files were added/removed, but compilation settings stays the same - collect unresolved imports for all new/modified files
// (can reuse cached imports for files that were not changed)
// 4. compilation settings were changed in the way that might affect module resolution - drop all caches and collect all data from the scratch
let unresolvedImports: SortedReadonlyArray<string>;
if (hasChanges || changedFiles.length) {
const result: string[] = [];
for (const sourceFile of this.program.getSourceFiles()) {
this.extractUnresolvedImportsFromSourceFile(sourceFile, result);
}
this.lastCachedUnresolvedImportsList = toSortedReadonlyArray(result);
}
unresolvedImports = this.lastCachedUnresolvedImportsList;
const cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, unresolvedImports, hasChanges);
if (this.setTypings(cachedTypings)) {
hasChanges = this.updateGraphWorker() || hasChanges;
}
@@ -357,7 +452,7 @@ namespace ts.server {
return !hasChanges;
}
private setTypings(typings: TypingsArray): boolean {
private setTypings(typings: SortedReadonlyArray<string>): boolean {
if (arrayIsEqualTo(this.typingFiles, typings)) {
return false;
}
@@ -430,6 +525,11 @@ namespace ts.server {
compilerOptions.allowJs = true;
}
compilerOptions.allowNonTsExtensions = true;
if (changesAffectModuleResolution(this.compilerOptions, compilerOptions)) {
// reset cached unresolved imports if changes in compiler options affected module resolution
this.cachedUnresolvedImportsPerFile.clear();
this.lastCachedUnresolvedImportsList = undefined;
}
this.compilerOptions = compilerOptions;
this.lsHost.setCompilationSettings(compilerOptions);
+4 -4
View File
@@ -41,7 +41,7 @@ namespace ts.server {
class BaseLineIndexWalker implements ILineIndexWalker {
goSubtree = true;
done = false;
leaf(rangeStart: number, rangeLength: number, ll: LineLeaf) {
leaf(_rangeStart: number, _rangeLength: number, _ll: LineLeaf) {
}
}
@@ -150,7 +150,7 @@ namespace ts.server {
return this.lineIndex;
}
post(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection): LineCollection {
post(_relativeStart: number, _relativeLength: number, lineCollection: LineCollection): 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) {
@@ -161,7 +161,7 @@ namespace ts.server {
return undefined;
}
pre(relativeStart: number, relativeLength: number, lineCollection: LineCollection, parent: LineCollection, nodeType: CharRangeSection) {
pre(_relativeStart: number, _relativeLength: number, lineCollection: LineCollection, _parent: LineCollection, nodeType: CharRangeSection) {
// currentNode corresponds to parent, but in the new tree
const currentNode = this.stack[this.stack.length - 1];
@@ -414,7 +414,7 @@ namespace ts.server {
const starts: number[] = [-1];
let count = 1;
let pos = 0;
this.index.every((ll, s, len) => {
this.index.every(ll => {
starts[count] = pos;
count++;
pos += ll.text.length;
+54 -21
View File
@@ -14,21 +14,33 @@ namespace ts.server {
} = require("child_process");
const os: {
homedir(): string
homedir?(): string;
tmpdir(): string;
} = require("os");
function getGlobalTypingsCacheLocation() {
let basePath: string;
switch (process.platform) {
case "win32":
basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir();
basePath = process.env.LOCALAPPDATA ||
process.env.APPDATA ||
(os.homedir && os.homedir()) ||
process.env.USERPROFILE ||
(process.env.HOMEDRIVE && process.env.HOMEPATH && normalizeSlashes(process.env.HOMEDRIVE + process.env.HOMEPATH)) ||
os.tmpdir();
break;
case "linux":
basePath = os.homedir();
basePath = (os.homedir && os.homedir()) ||
process.env.HOME ||
((process.env.LOGNAME || process.env.USER) && `/home/${process.env.LOGNAME || process.env.USER}`) ||
os.tmpdir();
break;
case "darwin":
basePath = combinePaths(os.homedir(), "Library/Application Support/");
const homeDir = (os.homedir && os.homedir()) ||
process.env.HOME ||
((process.env.LOGNAME || process.env.USER) && `/Users/${process.env.LOGNAME || process.env.USER}`) ||
os.tmpdir();
basePath = combinePaths(homeDir, "Library/Application Support/");
break;
}
@@ -40,6 +52,7 @@ namespace ts.server {
send(message: any, sendHandle?: any): void;
on(message: "message", f: (m: any) => void): void;
kill(): void;
pid: number;
}
interface NodeSocket {
@@ -53,14 +66,6 @@ namespace ts.server {
historySize?: number;
}
interface Key {
sequence?: string;
name?: string;
ctrl?: boolean;
meta?: boolean;
shift?: boolean;
}
interface Stats {
isFile(): boolean;
isDirectory(): boolean;
@@ -187,21 +192,40 @@ namespace ts.server {
class NodeTypingsInstaller implements ITypingsInstaller {
private installer: NodeChildProcess;
private installerPidReported = false;
private socket: NodeSocket;
private projectService: ProjectService;
private throttledOperations: ThrottledOperations;
constructor(
private readonly logger: server.Logger,
private readonly eventPort: number,
host: ServerHost,
eventPort: number,
readonly globalTypingsCacheLocation: string,
private newLine: string) {
this.throttledOperations = new ThrottledOperations(host);
if (eventPort) {
const s = net.connect({ port: eventPort }, () => {
this.socket = s;
this.reportInstallerProcessId();
});
}
}
private reportInstallerProcessId() {
if (this.installerPidReported) {
return;
}
if (this.socket && this.installer) {
this.sendEvent(0, "typingsInstallerPid", { pid: this.installer.pid });
this.installerPidReported = true;
}
}
private sendEvent(seq: number, event: string, body: any): void {
this.socket.write(formatMessage({ seq, type: "event", event, body }, this.logger, Buffer.byteLength, this.newLine), "utf8");
}
attach(projectService: ProjectService) {
this.projectService = projectService;
if (this.logger.hasLevel(LogLevel.requestTime)) {
@@ -218,7 +242,7 @@ namespace ts.server {
const match = /^--(debug|inspect)(=(\d+))?$/.exec(arg);
if (match) {
// if port is specified - use port + 1
// otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1
// otherwise pick a default port depending on if 'debug' or 'inspect' and use its value + 1
const currentPort = match[3] !== undefined
? +match[3]
: match[1] === "debug" ? 5858 : 9229;
@@ -230,6 +254,8 @@ namespace ts.server {
this.installer = childProcess.fork(combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv });
this.installer.on("message", m => this.handleMessage(m));
this.reportInstallerProcessId();
process.on("exit", () => {
this.installer.kill();
});
@@ -239,12 +265,19 @@ namespace ts.server {
this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" });
}
enqueueInstallTypingsRequest(project: Project, typingOptions: TypingOptions): void {
const request = createInstallTypingsRequest(project, typingOptions);
enqueueInstallTypingsRequest(project: Project, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>): void {
const request = createInstallTypingsRequest(project, typingOptions, unresolvedImports);
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`Sending request: ${JSON.stringify(request)}`);
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`Scheduling throttled operation: ${JSON.stringify(request)}`);
}
}
this.installer.send(request);
this.throttledOperations.schedule(project.getProjectName(), /*ms*/ 250, () => {
if (this.logger.hasLevel(LogLevel.verbose)) {
this.logger.info(`Sending request: ${JSON.stringify(request)}`);
}
this.installer.send(request);
});
}
private handleMessage(response: SetTypings | InvalidateCachedTypings) {
@@ -253,7 +286,7 @@ namespace ts.server {
}
this.projectService.updateTypingsForProject(response);
if (response.kind == "set" && this.socket) {
this.socket.write(formatMessage({ seq: 0, type: "event", message: response }, this.logger, Buffer.byteLength, this.newLine), "utf8");
this.sendEvent(0, "setTypings", response);
}
}
}
@@ -274,7 +307,7 @@ namespace ts.server {
useSingleInferredProject,
disableAutomaticTypingAcquisition
? nullTypingsInstaller
: new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine),
: new NodeTypingsInstaller(logger, host, installerEventPort, globalTypingsCacheLocation, host.newLine),
Buffer.byteLength,
process.hrtime,
logger,
+4 -4
View File
@@ -1300,7 +1300,7 @@ namespace ts.server {
}
// No need to analyze lib.d.ts
let fileNamesInProject = fileNames.filter((value, index, array) => value.indexOf("lib.d.ts") < 0);
let fileNamesInProject = fileNames.filter(value => value.indexOf("lib.d.ts") < 0);
// Sort the file name list to make the recently touched files come first
const highPriorityFiles: NormalizedPath[] = [];
@@ -1500,7 +1500,7 @@ namespace ts.server {
[CommandNames.EncodedSemanticClassificationsFull]: (request: protocol.EncodedSemanticClassificationsRequest) => {
return this.requiredResponse(this.getEncodedSemanticClassifications(request.arguments));
},
[CommandNames.Cleanup]: (request: protocol.Request) => {
[CommandNames.Cleanup]: () => {
this.cleanup();
return this.requiredResponse(true);
},
@@ -1581,7 +1581,7 @@ namespace ts.server {
[CommandNames.ProjectInfo]: (request: protocol.ProjectInfoRequest) => {
return this.requiredResponse(this.getProjectInfo(request.arguments));
},
[CommandNames.ReloadProjects]: (request: protocol.ReloadProjectsRequest) => {
[CommandNames.ReloadProjects]: () => {
this.projectService.reloadProjects();
return this.notRequired();
},
@@ -1591,7 +1591,7 @@ namespace ts.server {
[CommandNames.GetCodeFixesFull]: (request: protocol.CodeFixRequest) => {
return this.requiredResponse(this.getCodeFixes(request.arguments, /*simplifiedResult*/ false));
},
[CommandNames.GetSupportedCodeFixes]: (request: protocol.Request) => {
[CommandNames.GetSupportedCodeFixes]: () => {
return this.requiredResponse(this.getSupportedCodeFixes());
}
});
+3 -1
View File
@@ -11,7 +11,9 @@
"types": [
"node"
],
"target": "es5"
"target": "es5",
"noUnusedLocals": true,
"noUnusedParameters": true
},
"files": [
"../services/shims.ts",
+3 -1
View File
@@ -8,7 +8,9 @@
"stripInternal": true,
"declaration": true,
"types": [],
"target": "es5"
"target": "es5",
"noUnusedLocals": true,
"noUnusedParameters": true
},
"files": [
"../services/shims.ts",
+12 -4
View File
@@ -18,6 +18,10 @@ declare namespace ts.server {
trace?(s: string): void;
}
export interface SortedReadonlyArray<T> extends ReadonlyArray<T> {
" __sortedReadonlyArrayBrand": any;
}
export interface TypingInstallerRequest {
readonly projectName: string;
readonly kind: "discover" | "closeProject";
@@ -26,8 +30,9 @@ declare namespace ts.server {
export interface DiscoverTypings extends TypingInstallerRequest {
readonly fileNames: string[];
readonly projectRootPath: ts.Path;
readonly typingOptions: ts.TypingOptions;
readonly compilerOptions: ts.CompilerOptions;
readonly typingOptions: ts.TypingOptions;
readonly unresolvedImports: SortedReadonlyArray<string>;
readonly cachePath?: string;
readonly kind: "discover";
}
@@ -36,20 +41,23 @@ declare namespace ts.server {
readonly kind: "closeProject";
}
export type SetRequest = "set";
export type InvalidateRequest = "invalidate";
export interface TypingInstallerResponse {
readonly projectName: string;
readonly kind: "set" | "invalidate";
readonly kind: SetRequest | InvalidateRequest;
}
export interface SetTypings extends TypingInstallerResponse {
readonly typingOptions: ts.TypingOptions;
readonly compilerOptions: ts.CompilerOptions;
readonly typings: string[];
readonly kind: "set";
readonly unresolvedImports: SortedReadonlyArray<string>;
readonly kind: SetRequest;
}
export interface InvalidateCachedTypings extends TypingInstallerResponse {
readonly kind: "invalidate";
readonly kind: InvalidateRequest;
}
export interface InstallTypingHost extends JsTyping.TypingResolutionHost {
+28 -26
View File
@@ -2,23 +2,25 @@
namespace ts.server {
export interface ITypingsInstaller {
enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions): void;
enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>): void;
attach(projectService: ProjectService): void;
onProjectClosed(p: Project): void;
readonly globalTypingsCacheLocation: string;
}
export const nullTypingsInstaller: ITypingsInstaller = {
enqueueInstallTypingsRequest: () => {},
attach: (projectService: ProjectService) => {},
onProjectClosed: (p: Project) => {},
enqueueInstallTypingsRequest: noop,
attach: noop,
onProjectClosed: noop,
globalTypingsCacheLocation: undefined
};
class TypingsCacheEntry {
readonly typingOptions: TypingOptions;
readonly compilerOptions: CompilerOptions;
readonly typings: TypingsArray;
readonly typings: SortedReadonlyArray<string>;
readonly unresolvedImports: SortedReadonlyArray<string>;
/* mainly useful for debugging */
poisoned: boolean;
}
@@ -61,13 +63,11 @@ namespace ts.server {
return opt1.allowJs != opt2.allowJs;
}
export interface TypingsArray extends ReadonlyArray<string> {
" __typingsArrayBrand": any;
}
function toTypingsArray(arr: string[]): TypingsArray {
arr.sort();
return <any>arr;
function unresolvedImportsChanged(imports1: SortedReadonlyArray<string>, imports2: SortedReadonlyArray<string>): boolean {
if (imports1 === imports2) {
return false;
}
return !arrayIsEqualTo(imports1, imports2);
}
export class TypingsCache {
@@ -76,7 +76,7 @@ namespace ts.server {
constructor(private readonly installer: ITypingsInstaller) {
}
getTypingsForProject(project: Project, forceRefresh: boolean): TypingsArray {
getTypingsForProject(project: Project, unresolvedImports: SortedReadonlyArray<string>, forceRefresh: boolean): SortedReadonlyArray<string> {
const typingOptions = project.getTypingOptions();
if (!typingOptions || !typingOptions.enableAutoDiscovery) {
@@ -84,39 +84,41 @@ namespace ts.server {
}
const entry = this.perProjectCache[project.getProjectName()];
const result: TypingsArray = entry ? entry.typings : <any>emptyArray;
if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) {
const result: SortedReadonlyArray<string> = entry ? entry.typings : <any>emptyArray;
if (forceRefresh ||
!entry ||
typingOptionsChanged(typingOptions, entry.typingOptions) ||
compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions) ||
unresolvedImportsChanged(unresolvedImports, entry.unresolvedImports)) {
// Note: entry is now poisoned since it does not really contain typings for a given combination of compiler options\typings options.
// instead it acts as a placeholder to prevent issuing multiple requests
this.perProjectCache[project.getProjectName()] = {
compilerOptions: project.getCompilerOptions(),
typingOptions,
typings: result,
unresolvedImports,
poisoned: true
};
// something has been changed, issue a request to update typings
this.installer.enqueueInstallTypingsRequest(project, typingOptions);
this.installer.enqueueInstallTypingsRequest(project, typingOptions, unresolvedImports);
}
return result;
}
invalidateCachedTypingsForProject(project: Project) {
const typingOptions = project.getTypingOptions();
if (!typingOptions.enableAutoDiscovery) {
return;
}
this.installer.enqueueInstallTypingsRequest(project, typingOptions);
}
updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, newTypings: string[]) {
updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>, newTypings: string[]) {
this.perProjectCache[projectName] = {
compilerOptions,
typingOptions,
typings: toTypingsArray(newTypings),
typings: toSortedReadonlyArray(newTypings),
unresolvedImports,
poisoned: false
};
}
deleteTypingsForProject(projectName: string) {
delete this.perProjectCache[projectName];
}
onProjectClosed(project: Project) {
delete this.perProjectCache[project.getProjectName()];
this.installer.onProjectClosed(project);
@@ -126,7 +126,7 @@ namespace ts.server.typingsInstaller {
case NpmInstallRequest: {
const command = `${this.npmPath} install ${args.join(" ")} --save-dev`;
const start = Date.now();
this.exec(command, { cwd }, (err, stdout, stderr) => {
this.exec(command, { cwd }, (_err, stdout, stderr) => {
if (this.log.isEnabled()) {
this.log.writeLine(`${requestKind} #${requestId} took: ${Date.now() - start} ms${sys.newLine}stdout: ${stdout}${sys.newLine}stderr: ${stderr}`);
}
+3 -1
View File
@@ -11,7 +11,9 @@
"types": [
"node"
],
"target": "es5"
"target": "es5",
"noUnusedLocals": true,
"noUnusedParameters": true
},
"files": [
"../types.d.ts",
@@ -15,7 +15,7 @@ namespace ts.server.typingsInstaller {
const nullLog: Log = {
isEnabled: () => false,
writeLine: () => {}
writeLine: noop
};
function typingToFileName(cachePath: string, packageName: string, installTypingHost: InstallTypingHost): string {
@@ -26,6 +26,7 @@ namespace ts.server.typingsInstaller {
export enum PackageNameValidationResult {
Ok,
ScopedPackagesNotSupported,
EmptyName,
NameTooLong,
NameStartsWithDot,
NameStartsWithUnderscore,
@@ -38,7 +39,9 @@ namespace ts.server.typingsInstaller {
* Validates package name using rules defined at https://docs.npmjs.com/files/package.json
*/
export function validatePackageName(packageName: string): PackageNameValidationResult {
Debug.assert(!!packageName, "Package name is not specified");
if (!packageName) {
return PackageNameValidationResult.EmptyName;
}
if (packageName.length > MaxPackageNameLength) {
return PackageNameValidationResult.NameTooLong;
}
@@ -146,7 +149,7 @@ namespace ts.server.typingsInstaller {
this.safeListPath,
this.packageNameToTypingLocation,
req.typingOptions,
req.compilerOptions);
req.unresolvedImports);
if (this.log.isEnabled()) {
this.log.writeLine(`Finished typings discovery: ${JSON.stringify(discoverTypingsResult)}`);
@@ -239,6 +242,9 @@ namespace ts.server.typingsInstaller {
this.missingTypingsSet[typing] = true;
if (this.log.isEnabled()) {
switch (validationResult) {
case PackageNameValidationResult.EmptyName:
this.log.writeLine(`Package name '${typing}' cannot be empty`);
break;
case PackageNameValidationResult.NameTooLong:
this.log.writeLine(`Package name '${typing}' should be less than ${MaxPackageNameLength} characters`);
break;
@@ -382,8 +388,10 @@ namespace ts.server.typingsInstaller {
if (this.log.isEnabled()) {
this.log.writeLine(`Got FS notification for ${f}, handler is already invoked '${isInvoked}'`);
}
this.sendResponse({ projectName: projectName, kind: "invalidate" });
isInvoked = true;
if (!isInvoked) {
this.sendResponse({ projectName: projectName, kind: "invalidate" });
isInvoked = true;
}
});
watchers.push(w);
}
@@ -396,6 +404,7 @@ namespace ts.server.typingsInstaller {
typingOptions: request.typingOptions,
compilerOptions: request.compilerOptions,
typings,
unresolvedImports: request.unresolvedImports,
kind: "set"
};
}
+12 -2
View File
@@ -45,12 +45,13 @@ namespace ts.server {
}
}
export function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, cachePath?: string): DiscoverTypings {
export function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, unresolvedImports: SortedReadonlyArray<string>, cachePath?: string): DiscoverTypings {
return {
projectName: project.getProjectName(),
fileNames: project.getFileNames(),
compilerOptions: project.getCompilerOptions(),
typingOptions,
unresolvedImports,
projectRootPath: getProjectRootPath(project),
cachePath,
kind: "discover"
@@ -209,11 +210,15 @@ namespace ts.server {
export interface ServerLanguageServiceHost {
setCompilationSettings(options: CompilerOptions): void;
notifyFileRemoved(info: ScriptInfo): void;
startRecordingFilesWithChangedResolutions(): void;
finishRecordingFilesWithChangedResolutions(): Path[];
}
export const nullLanguageServiceHost: ServerLanguageServiceHost = {
setCompilationSettings: () => undefined,
notifyFileRemoved: () => undefined
notifyFileRemoved: () => undefined,
startRecordingFilesWithChangedResolutions: () => undefined,
finishRecordingFilesWithChangedResolutions: () => undefined
};
export interface ProjectOptions {
@@ -240,6 +245,11 @@ namespace ts.server {
return `/dev/null/inferredProject${counter}*`;
}
export function toSortedReadonlyArray(arr: string[]): SortedReadonlyArray<string> {
arr.sort();
return <any>arr;
}
export class ThrottledOperations {
private pendingTimeouts: Map<any> = createMap<any>();
constructor(private readonly host: ServerHost) {
+9 -9
View File
@@ -179,7 +179,7 @@ namespace ts.Completions {
// Get string literal completions from specialized signatures of the target
// i.e. declare function f(a: 'A');
// f("/*completion position*/")
return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, node);
return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo);
}
// Get completion for string literal from string literal type
@@ -199,7 +199,7 @@ namespace ts.Completions {
}
}
function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo: SignatureHelp.ArgumentListInfo, location: Node) {
function getStringLiteralCompletionEntriesFromCallExpression(argumentInfo: SignatureHelp.ArgumentListInfo) {
const candidates: Signature[] = [];
const entries: CompletionEntry[] = [];
@@ -361,7 +361,7 @@ namespace ts.Completions {
/**
* Multiple file entries might map to the same truncated name once we remove extensions
* (happens iff includeExtensions === false)so we use a set-like data structure. Eg:
*
*
* both foo.ts and foo.tsx become foo
*/
const foundFiles = createMap<boolean>();
@@ -617,7 +617,7 @@ namespace ts.Completions {
if (typeRoots) {
for (const root of typeRoots) {
getCompletionEntriesFromDirectories(host, options, root, span, result);
getCompletionEntriesFromDirectories(host, root, span, result);
}
}
}
@@ -626,14 +626,14 @@ namespace ts.Completions {
// Also get all @types typings installed in visible node_modules directories
for (const packageJson of findPackageJsons(scriptPath)) {
const typesDir = combinePaths(getDirectoryPath(packageJson), "node_modules/@types");
getCompletionEntriesFromDirectories(host, options, typesDir, span, result);
getCompletionEntriesFromDirectories(host, typesDir, span, result);
}
}
return result;
}
function getCompletionEntriesFromDirectories(host: LanguageServiceHost, options: CompilerOptions, directory: string, span: TextSpan, result: CompletionEntry[]) {
function getCompletionEntriesFromDirectories(host: LanguageServiceHost, directory: string, span: TextSpan, result: CompletionEntry[]) {
if (host.getDirectories && tryDirectoryExists(host, directory)) {
const directories = tryGetDirectories(host, directory);
if (directories) {
@@ -1708,11 +1708,11 @@ namespace ts.Completions {
* to determine if the caret is currently within the string literal and capture the literal fragment
* for completions.
* For example, this matches
*
*
* /// <reference path="fragment
*
*
* but not
*
*
* /// <reference path="fragment"
*/
const tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s*<reference\s+(path|types)\s*=\s*(?:'|"))([^\3"]*)$/;
+2 -2
View File
@@ -90,7 +90,7 @@ namespace ts.FindAllReferences {
getReferencesInNode(scope, symbol, declaredName, node, searchMeaning, findInStrings, findInComments, result, symbolToIndex);
}
else {
const internedName = getInternedName(symbol, node, declarations);
const internedName = getInternedName(symbol, node);
for (const sourceFile of sourceFiles) {
cancellationToken.throwIfCancellationRequested();
@@ -175,7 +175,7 @@ namespace ts.FindAllReferences {
return undefined;
}
function getInternedName(symbol: Symbol, location: Node, declarations: Declaration[]): string {
function getInternedName(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 under the cursor.
if (isImportOrExportSpecifierName(location)) {
+1 -1
View File
@@ -248,7 +248,7 @@ namespace ts.formatting {
}
};
function rangeHasNoErrors(r: TextRange): boolean {
function rangeHasNoErrors(): boolean {
return false;
}
}
+1 -1
View File
@@ -67,7 +67,7 @@ namespace ts.formatting {
return result;
}
public Contains(tokenValue: SyntaxKind): boolean {
public Contains(): boolean {
return true;
}
+1 -1
View File
@@ -43,7 +43,7 @@ namespace ts.JsDoc {
];
let jsDocCompletionEntries: CompletionEntry[];
export function getJsDocCommentsFromDeclarations(declarations: Declaration[], name: string, canUseParsedParamTagComments: boolean) {
export function getJsDocCommentsFromDeclarations(declarations: Declaration[]) {
// Only collect doc comments from duplicate declarations once:
// In case of a union property there might be same declaration multiple times
// which only varies in type parameter
+24 -2
View File
@@ -31,6 +31,17 @@ namespace ts.JsTyping {
const EmptySafeList: Map<string> = createMap<string>();
/* @internal */
export const nodeCoreModuleList: ReadonlyArray<string> = [
"buffer", "querystring", "events", "http", "cluster",
"zlib", "os", "https", "punycode", "repl", "readline",
"vm", "child_process", "url", "dns", "net",
"dgram", "fs", "path", "string_decoder", "tls",
"crypto", "stream", "util", "assert", "tty", "domain",
"constants", "process", "v8", "timers", "console"];
const nodeCoreModules = arrayToMap(<string[]>nodeCoreModuleList, x => x);
/**
* @param host is the object providing I/O related operations.
* @param fileNames are the file names that belong to the same project
@@ -47,7 +58,7 @@ namespace ts.JsTyping {
safeListPath: Path,
packageNameToTypingLocation: Map<string>,
typingOptions: TypingOptions,
compilerOptions: CompilerOptions):
unresolvedImports: ReadonlyArray<string>):
{ cachedTypingPaths: string[], newTypingNames: string[], filesToWatch: string[] } {
// A typing name to typing file path mapping
@@ -93,6 +104,15 @@ namespace ts.JsTyping {
}
getTypingNamesFromSourceFileNames(fileNames);
// add typings for unresolved imports
if (unresolvedImports) {
for (const moduleId of unresolvedImports) {
const typingName = moduleId in nodeCoreModules ? "node" : moduleId;
if (!(typingName in inferredTypings)) {
inferredTypings[typingName] = undefined;
}
}
}
// Add the cached typing locations for inferred typings that are already installed
for (const name in packageNameToTypingLocation) {
if (name in inferredTypings && !inferredTypings[name]) {
@@ -136,10 +156,12 @@ namespace ts.JsTyping {
* Get the typing info from common package manager json files like package.json or bower.json
*/
function getTypingNamesFromJson(jsonPath: string, filesToWatch: string[]) {
if (host.fileExists(jsonPath)) {
filesToWatch.push(jsonPath);
}
const result = readConfigFile(jsonPath, (path: string) => host.readFile(path));
if (result.config) {
const jsonConfig: PackageJson = result.config;
filesToWatch.push(jsonPath);
if (jsonConfig.dependencies) {
mergeTypings(getOwnKeys(jsonConfig.dependencies));
}
+19 -1
View File
@@ -403,6 +403,9 @@ namespace ts.NavigationBar {
if (getModifierFlags(node) & ModifierFlags.Default) {
return "default";
}
// We may get a string with newlines or other whitespace in the case of an object dereference
// (eg: "app\n.onactivated"), so we should remove the whitespace for readabiltiy in the
// navigation bar.
return getFunctionOrClassName(<ArrowFunction | FunctionExpression | ClassExpression>node);
case SyntaxKind.Constructor:
return "constructor";
@@ -602,7 +605,7 @@ namespace ts.NavigationBar {
// See if it is of the form "<expr> = function(){...}". If so, use the text from the left-hand side.
else if (node.parent.kind === SyntaxKind.BinaryExpression &&
(node.parent as BinaryExpression).operatorToken.kind === SyntaxKind.EqualsToken) {
return nodeText((node.parent as BinaryExpression).left);
return nodeText((node.parent as BinaryExpression).left).replace(whiteSpaceRegex, "");
}
// See if it is a property assignment, and if so use the property name
else if (node.parent.kind === SyntaxKind.PropertyAssignment && (node.parent as PropertyAssignment).name) {
@@ -620,4 +623,19 @@ namespace ts.NavigationBar {
function isFunctionOrClassExpression(node: Node): boolean {
return node.kind === SyntaxKind.FunctionExpression || node.kind === SyntaxKind.ArrowFunction || node.kind === SyntaxKind.ClassExpression;
}
/**
* Matches all whitespace characters in a string. Eg:
*
* "app.
*
* onactivated"
*
* matches because of the newline, whereas
*
* "app.onactivated"
*
* does not match.
*/
const whiteSpaceRegex = /\s+/g;
}
+13 -15
View File
@@ -264,23 +264,23 @@ namespace ts {
return (sourceFile || this.getSourceFile()).text.substring(this.getStart(), this.getEnd());
}
public getChildCount(sourceFile?: SourceFile): number {
public getChildCount(): number {
return 0;
}
public getChildAt(index: number, sourceFile?: SourceFile): Node {
public getChildAt(): Node {
return undefined;
}
public getChildren(sourceFile?: SourceFile): Node[] {
public getChildren(): Node[] {
return emptyArray;
}
public getFirstToken(sourceFile?: SourceFile): Node {
public getFirstToken(): Node {
return undefined;
}
public getLastToken(sourceFile?: SourceFile): Node {
public getLastToken(): Node {
return undefined;
}
}
@@ -313,7 +313,7 @@ namespace ts {
getDocumentationComment(): SymbolDisplayPart[] {
if (this.documentationComment === undefined) {
this.documentationComment = JsDoc.getJsDocCommentsFromDeclarations(this.declarations, this.name, !(this.flags & SymbolFlags.Property));
this.documentationComment = JsDoc.getJsDocCommentsFromDeclarations(this.declarations);
}
return this.documentationComment;
@@ -338,7 +338,7 @@ namespace ts {
_incrementExpressionBrand: any;
_unaryExpressionBrand: any;
_expressionBrand: any;
constructor(kind: SyntaxKind.Identifier, pos: number, end: number) {
constructor(_kind: SyntaxKind.Identifier, pos: number, end: number) {
super(pos, end);
}
}
@@ -347,6 +347,7 @@ namespace ts {
class TypeObject implements Type {
checker: TypeChecker;
flags: TypeFlags;
objectFlags?: ObjectFlags;
id: number;
symbol: Symbol;
constructor(checker: TypeChecker, flags: TypeFlags) {
@@ -381,7 +382,7 @@ namespace ts {
return this.checker.getIndexTypeOfType(this, IndexKind.Number);
}
getBaseTypes(): ObjectType[] {
return this.flags & (TypeFlags.Class | TypeFlags.Interface)
return this.flags & TypeFlags.Object && this.objectFlags & (ObjectFlags.Class | ObjectFlags.Interface)
? this.checker.getBaseTypes(<InterfaceType><Type>this)
: undefined;
}
@@ -423,10 +424,7 @@ namespace ts {
getDocumentationComment(): SymbolDisplayPart[] {
if (this.documentationComment === undefined) {
this.documentationComment = this.declaration ? JsDoc.getJsDocCommentsFromDeclarations(
[this.declaration],
/*name*/ undefined,
/*canUseParsedParamTagComments*/ false) : [];
this.documentationComment = this.declaration ? JsDoc.getJsDocCommentsFromDeclarations([this.declaration]) : [];
}
return this.documentationComment;
@@ -802,7 +800,7 @@ namespace ts {
public getRootFileNames(): string[] {
const fileNames: string[] = [];
this.fileNameToEntry.forEachValue((path, value) => {
this.fileNameToEntry.forEachValue((_path, value) => {
if (value) {
fileNames.push(value.hostFileName);
}
@@ -1054,7 +1052,7 @@ namespace ts {
useCaseSensitiveFileNames: () => useCaseSensitivefileNames,
getNewLine: () => getNewLineOrDefaultFromHost(host),
getDefaultLibFileName: (options) => host.getDefaultLibFileName(options),
writeFile: (fileName, data, writeByteOrderMark) => { },
writeFile: noop,
getCurrentDirectory: () => currentDirectory,
fileExists: (fileName): boolean => {
// stub missing host functionality
@@ -1458,7 +1456,7 @@ namespace ts {
return getNonBoundSourceFile(fileName);
}
function getNameOrDottedNameSpan(fileName: string, startPos: number, endPos: number): TextSpan {
function getNameOrDottedNameSpan(fileName: string, startPos: number, _endPos: number): TextSpan {
const sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName);
// Get node at the location
+4 -4
View File
@@ -119,13 +119,13 @@ namespace ts {
}
export interface Shim {
dispose(dummy: any): void;
dispose(_dummy: any): void;
}
export interface LanguageServiceShim extends Shim {
languageService: LanguageService;
dispose(dummy: any): void;
dispose(_dummy: any): void;
refresh(throwOnError: boolean): void;
@@ -600,7 +600,7 @@ namespace ts {
constructor(private factory: ShimFactory) {
factory.registerShim(this);
}
public dispose(dummy: any): void {
public dispose(_dummy: any): void {
this.factory.unregisterShim(this);
}
}
@@ -1169,7 +1169,7 @@ namespace ts {
toPath(info.safeListPath, info.safeListPath, getCanonicalFileName),
info.packageNameToTypingLocation,
info.typingOptions,
info.compilerOptions);
info.unresolvedImports);
});
}
}
+1 -1
View File
@@ -173,7 +173,7 @@ namespace ts.SymbolDisplay {
displayParts.push(keywordPart(SyntaxKind.NewKeyword));
displayParts.push(spacePart());
}
if (!(type.flags & TypeFlags.Anonymous) && type.symbol) {
if (!(type.flags & TypeFlags.Object && (<ObjectType>type).objectFlags & ObjectFlags.Anonymous) && type.symbol) {
addRange(displayParts, symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, SymbolFormatFlags.WriteTypeParametersOrArguments));
}
addSignatureDisplayParts(signature, allSignatures, TypeFormatFlags.WriteArrowStyleSignature);
+5 -5
View File
@@ -74,8 +74,8 @@ namespace ts {
// Create a compilerHost object to allow the compiler to read and write files
const compilerHost: CompilerHost = {
getSourceFile: (fileName, target) => fileName === normalizePath(inputFileName) ? sourceFile : undefined,
writeFile: (name, text, writeByteOrderMark) => {
getSourceFile: (fileName) => fileName === normalizePath(inputFileName) ? sourceFile : undefined,
writeFile: (name, text) => {
if (fileExtensionIs(name, ".map")) {
Debug.assert(sourceMapText === undefined, `Unexpected multiple source map outputs for the file '${name}'`);
sourceMapText = text;
@@ -91,9 +91,9 @@ namespace ts {
getCurrentDirectory: () => "",
getNewLine: () => newLine,
fileExists: (fileName): boolean => fileName === inputFileName,
readFile: (fileName): string => "",
directoryExists: directoryExists => true,
getDirectories: (path: string) => []
readFile: () => "",
directoryExists: () => true,
getDirectories: () => []
};
const program = createProgram([inputFileName], options, compilerHost);
+3 -1
View File
@@ -10,7 +10,9 @@
"stripInternal": true,
"noResolve": false,
"declaration": true,
"target": "es5"
"target": "es5",
"noUnusedLocals": true,
"noUnusedParameters": true
},
"files": [
"../compiler/core.ts",

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