Merge branch 'master' into object-spread

This commit is contained in:
Nathan Shively-Sanders
2016-11-02 10:57:20 -07:00
203 changed files with 5443 additions and 2042 deletions
+18 -8
View File
@@ -499,8 +499,8 @@ namespace ts {
const saveReturnTarget = currentReturnTarget;
const saveActiveLabels = activeLabels;
const saveHasExplicitReturn = hasExplicitReturn;
const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !!getImmediatelyInvokedFunctionExpression(node);
// An IIFE is considered part of the containing control flow. Return statements behave
const isIIFE = containerFlags & ContainerFlags.IsFunctionExpression && !hasModifier(node, ModifierFlags.Async) && !!getImmediatelyInvokedFunctionExpression(node);
// A non-async IIFE is considered part of the containing control flow. Return statements behave
// similarly to break statements that exit to a label just past the statement body.
if (isIIFE) {
currentReturnTarget = createBranchLabel();
@@ -892,8 +892,13 @@ namespace ts {
function bindDoStatement(node: DoStatement): void {
const preDoLabel = createLoopLabel();
const preConditionLabel = createBranchLabel();
const postDoLabel = createBranchLabel();
const enclosingLabeledStatement = node.parent.kind === SyntaxKind.LabeledStatement
? lastOrUndefined(activeLabels)
: undefined;
// if do statement is wrapped in labeled statement then target labels for break/continue with or without
// label should be the same
const preConditionLabel = enclosingLabeledStatement ? enclosingLabeledStatement.continueTarget : createBranchLabel();
const postDoLabel = enclosingLabeledStatement ? enclosingLabeledStatement.breakTarget : createBranchLabel();
addAntecedent(preDoLabel, currentFlow);
currentFlow = preDoLabel;
bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
@@ -1111,8 +1116,11 @@ namespace ts {
if (!activeLabel.referenced && !options.allowUnusedLabels) {
file.bindDiagnostics.push(createDiagnosticForNode(node.label, Diagnostics.Unused_label));
}
addAntecedent(postStatementLabel, currentFlow);
currentFlow = finishFlowLabel(postStatementLabel);
if (!node.statement || node.statement.kind !== SyntaxKind.DoStatement) {
// do statement sets current flow inside bindDoStatement
addAntecedent(postStatementLabel, currentFlow);
currentFlow = finishFlowLabel(postStatementLabel);
}
}
function bindDestructuringTargetFlow(node: Expression) {
@@ -1204,9 +1212,9 @@ namespace ts {
}
else {
forEachChild(node, bind);
if (operator === SyntaxKind.EqualsToken && !isAssignmentTarget(node)) {
if (isAssignmentOperator(operator) && !isAssignmentTarget(node)) {
bindAssignmentTargetFlow(node.left);
if (node.left.kind === SyntaxKind.ElementAccessExpression) {
if (operator === SyntaxKind.EqualsToken && node.left.kind === SyntaxKind.ElementAccessExpression) {
const elementAccess = <ElementAccessExpression>node.left;
if (isNarrowableOperand(elementAccess.expression)) {
currentFlow = createFlowArrayMutation(currentFlow, node);
@@ -3093,6 +3101,8 @@ namespace ts {
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
case SyntaxKind.ThisType:
case SyntaxKind.TypeOperator:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.LiteralType:
// Types and signatures are TypeScript syntax, and exclude all other facts.
transformFlags = TransformFlags.AssertTypeScript;
+416 -337
View File
File diff suppressed because it is too large Load Diff
+21 -9
View File
@@ -1008,9 +1008,7 @@ namespace ts {
function convertTypingOptionsFromJsonWorker(jsonOptions: any,
basePath: string, errors: Diagnostic[], configFileName?: string): TypingOptions {
const options: TypingOptions = getBaseFileName(configFileName) === "jsconfig.json"
? { enableAutoDiscovery: true, include: [], exclude: [] }
: { enableAutoDiscovery: false, include: [], exclude: [] };
const options: TypingOptions = { enableAutoDiscovery: getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
convertOptionsFromJson(typingOptionDeclarations, jsonOptions, basePath, options, Diagnostics.Unknown_typing_option_0, errors);
return options;
}
@@ -1263,12 +1261,13 @@ namespace ts {
/**
* Gets directories in a set of include patterns that should be watched for changes.
*/
function getWildcardDirectories(include: string[], exclude: string[], path: string, useCaseSensitiveFileNames: boolean) {
function getWildcardDirectories(include: string[], exclude: string[], path: string, useCaseSensitiveFileNames: boolean): Map<WatchDirectoryFlags> {
// We watch a directory recursively if it contains a wildcard anywhere in a directory segment
// of the pattern:
//
// /a/b/**/d - Watch /a/b recursively to catch changes to any d in any subfolder recursively
// /a/b/*/d - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
// /a/b - Watch /a/b recursively to catch changes to anything in any recursive subfoler
//
// We watch a directory without recursion if it contains a wildcard in the file segment of
// the pattern:
@@ -1281,15 +1280,14 @@ namespace ts {
if (include !== undefined) {
const recursiveKeys: string[] = [];
for (const file of include) {
const name = normalizePath(combinePaths(path, file));
if (excludeRegex && excludeRegex.test(name)) {
const spec = normalizePath(combinePaths(path, file));
if (excludeRegex && excludeRegex.test(spec)) {
continue;
}
const match = wildcardDirectoryPattern.exec(name);
const match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
if (match) {
const key = useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase();
const flags = watchRecursivePattern.test(name) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None;
const { key, flags } = match;
const existingFlags = wildcardDirectories[key];
if (existingFlags === undefined || existingFlags < flags) {
wildcardDirectories[key] = flags;
@@ -1313,6 +1311,20 @@ namespace ts {
return wildcardDirectories;
}
function getWildcardDirectoryFromSpec(spec: string, useCaseSensitiveFileNames: boolean): { key: string, flags: WatchDirectoryFlags } | undefined {
const match = wildcardDirectoryPattern.exec(spec);
if (match) {
return {
key: useCaseSensitiveFileNames ? match[0] : match[0].toLowerCase(),
flags: watchRecursivePattern.test(spec) ? WatchDirectoryFlags.Recursive : WatchDirectoryFlags.None
};
}
if (isImplicitGlob(spec)) {
return { key: spec, flags: WatchDirectoryFlags.Recursive };
}
return undefined;
}
/**
* Determines whether a literal or wildcard file has already been included that has a higher
* extension priority.
+135 -78
View File
@@ -124,6 +124,13 @@ namespace ts {
return undefined;
}
export function zipWith<T, U>(arrayA: T[], arrayB: U[], callback: (a: T, b: U, index: number) => void): void {
Debug.assert(arrayA.length === arrayB.length);
for (let i = 0; i < arrayA.length; i++) {
callback(arrayA[i], arrayB[i], i);
}
}
/**
* Iterates through `array` by index and performs the callback on each element of array until the callback
* returns a falsey value, then returns false.
@@ -439,8 +446,8 @@ namespace ts {
}
export function concatenate<T>(array1: T[], array2: T[]): T[] {
if (!array2 || !array2.length) return array1;
if (!array1 || !array1.length) return array2;
if (!some(array2)) return array1;
if (!some(array1)) return array2;
return [...array1, ...array2];
}
@@ -520,6 +527,27 @@ namespace ts {
return result || array;
}
/**
* Gets the relative complement of `arrayA` with respect to `b`, returning the elements that
* are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
* based on the provided comparer.
*/
export function relativeComplement<T>(arrayA: T[] | undefined, arrayB: T[] | undefined, comparer: (x: T, y: T) => Comparison = compareValues, offsetA = 0, offsetB = 0): T[] | undefined {
if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0) return arrayB;
const result: T[] = [];
outer: for (; offsetB < arrayB.length; offsetB++) {
inner: for (; offsetA < arrayA.length; offsetA++) {
switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
case Comparison.LessThan: break inner;
case Comparison.EqualTo: continue outer;
case Comparison.GreaterThan: continue inner;
}
}
result.push(arrayB[offsetB]);
}
return result;
}
export function sum(array: any[], prop: string): number {
let result = 0;
for (const v of array) {
@@ -619,12 +647,12 @@ namespace ts {
* @param array A sorted array whose first element must be no larger than number
* @param number The value to be searched for in the array.
*/
export function binarySearch<T>(array: T[], value: T, comparer?: (v1: T, v2: T) => number): number {
export function binarySearch<T>(array: T[], value: T, comparer?: (v1: T, v2: T) => number, offset?: number): number {
if (!array || array.length === 0) {
return -1;
}
let low = 0;
let low = offset || 0;
let high = array.length - 1;
comparer = comparer !== undefined
? comparer
@@ -1305,7 +1333,7 @@ namespace ts {
*/
export function getDirectoryPath(path: Path): Path;
export function getDirectoryPath(path: string): string;
export function getDirectoryPath(path: string): any {
export function getDirectoryPath(path: string): string {
return path.substr(0, Math.max(getRootLength(path), path.lastIndexOf(directorySeparator)));
}
@@ -1565,6 +1593,10 @@ namespace ts {
return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
}
export function hasExtension(fileName: string): boolean {
return getBaseFileName(fileName).indexOf(".") >= 0;
}
export function fileExtensionIs(path: string, extension: string): boolean {
return path.length > extension.length && endsWith(path, extension);
}
@@ -1610,73 +1642,21 @@ namespace ts {
let pattern = "";
let hasWrittenSubpattern = false;
spec: for (const spec of specs) {
for (const spec of specs) {
if (!spec) {
continue;
}
let subpattern = "";
let hasRecursiveDirectoryWildcard = false;
let hasWrittenComponent = false;
const components = getNormalizedPathComponents(spec, basePath);
if (usage !== "exclude" && components[components.length - 1] === "**") {
continue spec;
}
// getNormalizedPathComponents includes the separator for the root component.
// We need to remove to create our regex correctly.
components[0] = removeTrailingDirectorySeparator(components[0]);
let optionalCount = 0;
for (let component of components) {
if (component === "**") {
if (hasRecursiveDirectoryWildcard) {
continue spec;
}
subpattern += doubleAsteriskRegexFragment;
hasRecursiveDirectoryWildcard = true;
hasWrittenComponent = true;
}
else {
if (usage === "directories") {
subpattern += "(";
optionalCount++;
}
if (hasWrittenComponent) {
subpattern += directorySeparator;
}
if (usage !== "exclude") {
// The * and ? wildcards should not match directories or files that start with . if they
// appear first in a component. Dotted directories and files can be included explicitly
// like so: **/.*/.*
if (component.charCodeAt(0) === CharacterCodes.asterisk) {
subpattern += "([^./]" + singleAsteriskRegexFragment + ")?";
component = component.substr(1);
}
else if (component.charCodeAt(0) === CharacterCodes.question) {
subpattern += "[^./]";
component = component.substr(1);
}
}
subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
hasWrittenComponent = true;
}
}
while (optionalCount > 0) {
subpattern += ")?";
optionalCount--;
const subPattern = getSubPatternFromSpec(spec, basePath, usage, singleAsteriskRegexFragment, doubleAsteriskRegexFragment, replaceWildcardCharacter);
if (subPattern === undefined) {
continue;
}
if (hasWrittenSubpattern) {
pattern += "|";
}
pattern += "(" + subpattern + ")";
pattern += "(" + subPattern + ")";
hasWrittenSubpattern = true;
}
@@ -1684,7 +1664,83 @@ namespace ts {
return undefined;
}
return "^(" + pattern + (usage === "exclude" ? ")($|/)" : ")$");
// If excluding, match "foo/bar/baz...", but if including, only allow "foo".
const terminator = usage === "exclude" ? "($|/)" : "$";
return `^(${pattern})${terminator}`;
}
/**
* An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
* and does not contain any glob characters itself.
*/
export function isImplicitGlob(lastPathComponent: string): boolean {
return !/[.*?]/.test(lastPathComponent);
}
function getSubPatternFromSpec(spec: string, basePath: string, usage: "files" | "directories" | "exclude", singleAsteriskRegexFragment: string, doubleAsteriskRegexFragment: string, replaceWildcardCharacter: (match: string) => string): string | undefined {
let subpattern = "";
let hasRecursiveDirectoryWildcard = false;
let hasWrittenComponent = false;
const components = getNormalizedPathComponents(spec, basePath);
const lastComponent = lastOrUndefined(components);
if (usage !== "exclude" && lastComponent === "**") {
return undefined;
}
// getNormalizedPathComponents includes the separator for the root component.
// We need to remove to create our regex correctly.
components[0] = removeTrailingDirectorySeparator(components[0]);
if (isImplicitGlob(lastComponent)) {
components.push("**", "*");
}
let optionalCount = 0;
for (let component of components) {
if (component === "**") {
if (hasRecursiveDirectoryWildcard) {
return undefined;
}
subpattern += doubleAsteriskRegexFragment;
hasRecursiveDirectoryWildcard = true;
}
else {
if (usage === "directories") {
subpattern += "(";
optionalCount++;
}
if (hasWrittenComponent) {
subpattern += directorySeparator;
}
if (usage !== "exclude") {
// The * and ? wildcards should not match directories or files that start with . if they
// appear first in a component. Dotted directories and files can be included explicitly
// like so: **/.*/.*
if (component.charCodeAt(0) === CharacterCodes.asterisk) {
subpattern += "([^./]" + singleAsteriskRegexFragment + ")?";
component = component.substr(1);
}
else if (component.charCodeAt(0) === CharacterCodes.question) {
subpattern += "[^./]";
component = component.substr(1);
}
}
subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
}
hasWrittenComponent = true;
}
while (optionalCount > 0) {
subpattern += ")?";
optionalCount--;
}
return subpattern;
}
function replaceWildCardCharacterFiles(match: string) {
@@ -1771,6 +1827,7 @@ namespace ts {
function getBasePaths(path: string, includes: string[], useCaseSensitiveFileNames: boolean) {
// Storage for our results in the form of literal paths (e.g. the paths as written by the user).
const basePaths: string[] = [path];
if (includes) {
// Storage for literal base paths amongst the include patterns.
const includeBasePaths: string[] = [];
@@ -1778,14 +1835,8 @@ namespace ts {
// We also need to check the relative paths by converting them to absolute and normalizing
// in case they escape the base path (e.g "..\somedirectory")
const absolute: string = isRootedDiskPath(include) ? include : normalizePath(combinePaths(path, include));
const wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes);
const includeBasePath = wildcardOffset < 0
? removeTrailingDirectorySeparator(getDirectoryPath(absolute))
: absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset));
// Append the literal and canonical candidate base paths.
includeBasePaths.push(includeBasePath);
includeBasePaths.push(getIncludeBasePath(absolute));
}
// Sort the offsets array using either the literal or canonical path representations.
@@ -1793,21 +1844,27 @@ namespace ts {
// Iterate over each include base path and include unique base paths that are not a
// subpath of an existing base path
include: for (let i = 0; i < includeBasePaths.length; i++) {
const includeBasePath = includeBasePaths[i];
for (let j = 0; j < basePaths.length; j++) {
if (containsPath(basePaths[j], includeBasePath, path, !useCaseSensitiveFileNames)) {
continue include;
}
for (const includeBasePath of includeBasePaths) {
if (ts.every(basePaths, basePath => !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames))) {
basePaths.push(includeBasePath);
}
basePaths.push(includeBasePath);
}
}
return basePaths;
}
function getIncludeBasePath(absolute: string): string {
const wildcardOffset = indexOfAnyCharCode(absolute, wildcardCharCodes);
if (wildcardOffset < 0) {
// No "*" or "?" in the path
return !hasExtension(absolute)
? absolute
: removeTrailingDirectorySeparator(getDirectoryPath(absolute));
}
return absolute.substring(0, absolute.lastIndexOf(directorySeparator, wildcardOffset));
}
export function ensureScriptKind(fileName: string, scriptKind?: ScriptKind): ScriptKind {
// Using scriptKind as a condition handles both:
// - 'scriptKind' is unspecified and thus it is `undefined`
+17
View File
@@ -413,6 +413,10 @@ namespace ts {
return emitIntersectionType(<IntersectionTypeNode>type);
case SyntaxKind.ParenthesizedType:
return emitParenType(<ParenthesizedTypeNode>type);
case SyntaxKind.TypeOperator:
return emitTypeOperator(<TypeOperatorNode>type);
case SyntaxKind.IndexedAccessType:
return emitPropertyAccessType(<IndexedAccessTypeNode>type);
case SyntaxKind.FunctionType:
case SyntaxKind.ConstructorType:
return emitSignatureDeclarationWithJsDocComments(<FunctionOrConstructorTypeNode>type);
@@ -506,6 +510,19 @@ namespace ts {
write(")");
}
function emitTypeOperator(type: TypeOperatorNode) {
write(tokenToString(type.operator));
write(" ");
emitType(type.type);
}
function emitPropertyAccessType(node: IndexedAccessTypeNode) {
emitType(node.objectType);
write("[");
emitType(node.indexType);
write("]");
}
function emitTypeLiteral(type: TypeLiteralNode) {
write("{");
if (type.members.length) {
+48 -24
View File
@@ -163,7 +163,7 @@
"category": "Error",
"code": 1054
},
"Type '{0}' is not a valid async function return type.": {
"Type '{0}' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.": {
"category": "Error",
"code": 1055
},
@@ -1071,7 +1071,7 @@
"category": "Error",
"code": 2356
},
"The operand of an increment or decrement operator must be a variable, property or indexer.": {
"The operand of an increment or decrement operator must be a variable or a property access.": {
"category": "Error",
"code": 2357
},
@@ -1099,7 +1099,7 @@
"category": "Error",
"code": 2363
},
"Invalid left-hand side of assignment expression.": {
"The left-hand side of an assignment expression must be a variable or a property access.": {
"category": "Error",
"code": 2364
},
@@ -1259,7 +1259,7 @@
"category": "Error",
"code": 2405
},
"Invalid left-hand side in 'for...in' statement.": {
"The left-hand side of a 'for...in' statement must be a variable or a property access.": {
"category": "Error",
"code": 2406
},
@@ -1411,14 +1411,6 @@
"category": "Error",
"code": 2448
},
"The operand of an increment or decrement operator cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2449
},
"Left-hand side of assignment expression cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2450
},
"Cannot redeclare block-scoped variable '{0}'.": {
"category": "Error",
"code": 2451
@@ -1551,15 +1543,7 @@
"category": "Error",
"code": 2484
},
"The left-hand side of a 'for...of' statement cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2485
},
"The left-hand side of a 'for...in' statement cannot be a constant or a read-only property.": {
"category": "Error",
"code": 2486
},
"Invalid left-hand side in 'for...of' statement.": {
"The left-hand side of a 'for...of' statement must be a variable or a property access.": {
"category": "Error",
"code": 2487
},
@@ -1747,6 +1731,34 @@
"category": "Error",
"code": 2535
},
"Type '{0}' is not constrained to 'keyof {1}'.": {
"category": "Error",
"code": 2536
},
"Type '{0}' has no matching index signature for type '{1}'.": {
"category": "Error",
"code": 2537
},
"Type '{0}' cannot be used as an index type.": {
"category": "Error",
"code": 2538
},
"Cannot assign to '{0}' because it is not a variable.": {
"category": "Error",
"code": 2539
},
"Cannot assign to '{0}' because it is a constant or a read-only property.": {
"category": "Error",
"code": 2540
},
"The target of an assignment must be a variable or a property access.": {
"category": "Error",
"code": 2541
},
"Index signature in type '{0}' only permits reading.": {
"category": "Error",
"code": 2542
},
"JSX element attributes type '{0}' may not be a union type.": {
"category": "Error",
"code": 2600
@@ -1839,6 +1851,10 @@
"category": "Error",
"code": 2664
},
"Invalid module name in augmentation. Module '{0}' resolves to an untyped module at '{1}', which cannot be augmented.": {
"category": "Error",
"code": 2665
},
"Exports and export assignments are not permitted in module augmentations.": {
"category": "Error",
"code": 2666
@@ -1963,14 +1979,18 @@
"category": "Error",
"code": 2696
},
"Interface declaration cannot contain a spread property.": {
"An async function or method must return a 'Promise'. Make sure you have a declaration for 'Promise' or include 'ES2015' in your `--lib` option.": {
"category": "Error",
"code": 2697
},
"Type literals with spreads cannot contain index, call or construct signatures.": {
"Interface declaration cannot contain a spread property.": {
"category": "Error",
"code": 2698
},
"Type literals with spreads cannot contain index, call or construct signatures.": {
"category": "Error",
"code": 2699
},
"Import declaration '{0}' is using private name '{1}'.": {
"category": "Error",
@@ -2909,7 +2929,11 @@
"category": "Error",
"code": 7015
},
"Index signature of object type implicitly has an 'any' type.": {
"Could not find a declaration file for module '{0}'. '{1}' implicitly has an 'any' type.": {
"category": "Error",
"code": 7016
},
"Element implicitly has an 'any' type because type '{0}' has no index signature.": {
"category": "Error",
"code": 7017
},
+17
View File
@@ -594,6 +594,10 @@ const _super = (function (geti, seti) {
return emitExpressionWithTypeArguments(<ExpressionWithTypeArguments>node);
case SyntaxKind.ThisType:
return emitThisType();
case SyntaxKind.TypeOperator:
return emitTypeOperator(<TypeOperatorNode>node);
case SyntaxKind.IndexedAccessType:
return emitPropertyAccessType(<IndexedAccessTypeNode>node);
case SyntaxKind.LiteralType:
return emitLiteralType(<LiteralTypeNode>node);
@@ -1088,6 +1092,19 @@ const _super = (function (geti, seti) {
write("this");
}
function emitTypeOperator(node: TypeOperatorNode) {
writeTokenText(node.operator);
write(" ");
emit(node.type);
}
function emitPropertyAccessType(node: IndexedAccessTypeNode) {
emit(node.objectType);
write("[");
emit(node.indexType);
write("]");
}
function emitLiteralType(node: LiteralTypeNode) {
emitExpression(node.literal);
}
+1 -1
View File
@@ -45,7 +45,7 @@ namespace ts {
}
/** Adds `isExernalLibraryImport` to a Resolved to get a ResolvedModule. */
function resolvedModuleFromResolved({ path, extension }: Resolved, isExternalLibraryImport: boolean): ResolvedModule {
function resolvedModuleFromResolved({ path, extension }: Resolved, isExternalLibraryImport: boolean): ResolvedModuleFull {
return { resolvedFileName: path, extension, isExternalLibraryImport };
}
+35 -6
View File
@@ -138,7 +138,11 @@ namespace ts {
case SyntaxKind.IntersectionType:
return visitNodes(cbNodes, (<UnionOrIntersectionTypeNode>node).types);
case SyntaxKind.ParenthesizedType:
return visitNode(cbNode, (<ParenthesizedTypeNode>node).type);
case SyntaxKind.TypeOperator:
return visitNode(cbNode, (<ParenthesizedTypeNode | TypeOperatorNode>node).type);
case SyntaxKind.IndexedAccessType:
return visitNode(cbNode, (<IndexedAccessTypeNode>node).objectType) ||
visitNode(cbNode, (<IndexedAccessTypeNode>node).indexType);
case SyntaxKind.LiteralType:
return visitNode(cbNode, (<LiteralTypeNode>node).literal);
case SyntaxKind.ObjectBindingPattern:
@@ -2538,14 +2542,39 @@ namespace ts {
function parseArrayTypeOrHigher(): TypeNode {
let type = parseNonArrayType();
while (!scanner.hasPrecedingLineBreak() && parseOptional(SyntaxKind.OpenBracketToken)) {
parseExpected(SyntaxKind.CloseBracketToken);
const node = <ArrayTypeNode>createNode(SyntaxKind.ArrayType, type.pos);
node.elementType = type;
type = finishNode(node);
if (isStartOfType()) {
const node = <IndexedAccessTypeNode>createNode(SyntaxKind.IndexedAccessType, type.pos);
node.objectType = type;
node.indexType = parseType();
parseExpected(SyntaxKind.CloseBracketToken);
type = finishNode(node);
}
else {
const node = <ArrayTypeNode>createNode(SyntaxKind.ArrayType, type.pos);
node.elementType = type;
parseExpected(SyntaxKind.CloseBracketToken);
type = finishNode(node);
}
}
return type;
}
function parseTypeOperator(operator: SyntaxKind.KeyOfKeyword) {
const node = <TypeOperatorNode>createNode(SyntaxKind.TypeOperator);
parseExpected(operator);
node.operator = operator;
node.type = parseTypeOperatorOrHigher();
return finishNode(node);
}
function parseTypeOperatorOrHigher(): TypeNode {
switch (token()) {
case SyntaxKind.KeyOfKeyword:
return parseTypeOperator(SyntaxKind.KeyOfKeyword);
}
return parseArrayTypeOrHigher();
}
function parseUnionOrIntersectionType(kind: SyntaxKind, parseConstituentType: () => TypeNode, operator: SyntaxKind): TypeNode {
let type = parseConstituentType();
if (token() === operator) {
@@ -2562,7 +2591,7 @@ namespace ts {
}
function parseIntersectionTypeOrHigher(): TypeNode {
return parseUnionOrIntersectionType(SyntaxKind.IntersectionType, parseArrayTypeOrHigher, SyntaxKind.AmpersandToken);
return parseUnionOrIntersectionType(SyntaxKind.IntersectionType, parseTypeOperatorOrHigher, SyntaxKind.AmpersandToken);
}
function parseUnionTypeOrHigher(): TypeNode {
+34 -24
View File
@@ -329,16 +329,16 @@ namespace ts {
// Map storing if there is emit blocking diagnostics for given input
const hasEmitBlockingDiagnostics = createFileMap<boolean>(getCanonicalFileName);
let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string) => ResolvedModule[];
let resolveModuleNamesWorker: (moduleNames: string[], containingFile: string) => ResolvedModuleFull[];
if (host.resolveModuleNames) {
resolveModuleNamesWorker = (moduleNames, containingFile) => host.resolveModuleNames(moduleNames, containingFile).map(resolved => {
// An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
if (!resolved || resolved.extension !== undefined) {
return resolved;
if (!resolved || (resolved as ResolvedModuleFull).extension !== undefined) {
return resolved as ResolvedModuleFull;
}
resolved = clone(resolved);
resolved.extension = extensionFromPath(resolved.resolvedFileName);
return resolved;
const withExtension = clone(resolved) as ResolvedModuleFull;
withExtension.extension = extensionFromPath(resolved.resolvedFileName);
return withExtension;
});
}
else {
@@ -719,6 +719,14 @@ namespace ts {
}
function getSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
// For JavaScript files, we report semantic errors for using TypeScript-only
// constructs from within a JavaScript file as syntactic errors.
if (isSourceFileJavaScript(sourceFile)) {
if (!sourceFile.additionalSyntacticDiagnostics) {
sourceFile.additionalSyntacticDiagnostics = getJavaScriptSyntacticDiagnosticsForFile(sourceFile);
}
return concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
}
return sourceFile.parseDiagnostics;
}
@@ -751,12 +759,10 @@ namespace ts {
Debug.assert(!!sourceFile.bindDiagnostics);
const bindDiagnostics = sourceFile.bindDiagnostics;
// For JavaScript files, we don't want to report the normal typescript semantic errors.
// Instead, we just report errors for using TypeScript-only constructs from within a
// JavaScript file.
const checkDiagnostics = isSourceFileJavaScript(sourceFile) ?
getJavaScriptSemanticDiagnosticsForFile(sourceFile) :
typeChecker.getDiagnostics(sourceFile, cancellationToken);
// For JavaScript files, we don't want to report semantic errors.
// Instead, we'll report errors for using TypeScript-only constructs from within a
// JavaScript file when we get syntactic diagnostics for the file.
const checkDiagnostics = isSourceFileJavaScript(sourceFile) ? [] : typeChecker.getDiagnostics(sourceFile, cancellationToken);
const fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
const programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
@@ -764,7 +770,7 @@ namespace ts {
});
}
function getJavaScriptSemanticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
function getJavaScriptSyntacticDiagnosticsForFile(sourceFile: SourceFile): Diagnostic[] {
return runWithCancellationToken(() => {
const diagnostics: Diagnostic[] = [];
walk(sourceFile);
@@ -965,10 +971,6 @@ namespace ts {
return sortAndDeduplicateDiagnostics(allDiagnostics);
}
function hasExtension(fileName: string): boolean {
return getBaseFileName(fileName).indexOf(".") >= 0;
}
function processRootFile(fileName: string, isDefaultLib: boolean) {
processSourceFile(normalizePath(fileName), isDefaultLib);
}
@@ -1294,7 +1296,7 @@ namespace ts {
function processImportedModules(file: SourceFile) {
collectExternalModuleReferences(file);
if (file.imports.length || file.moduleAugmentations.length) {
file.resolvedModules = createMap<ResolvedModule>();
file.resolvedModules = createMap<ResolvedModuleFull>();
const moduleNames = map(concatenate(file.imports, file.moduleAugmentations), getTextOfLiteral);
const resolutions = resolveModuleNamesWorker(moduleNames, getNormalizedAbsolutePath(file.fileName, currentDirectory));
Debug.assert(resolutions.length === moduleNames.length);
@@ -1321,6 +1323,7 @@ namespace ts {
// - it's not a top level JavaScript module that exceeded the search max
const elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
// Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
// This may still end up being an untyped module -- the file won't be included but imports will be allowed.
const shouldAddFile = resolvedFileName && !getResolutionDiagnostic(options, resolution) && !options.noResolve && i < file.imports.length && !elideImport;
if (elideImport) {
@@ -1568,22 +1571,29 @@ namespace ts {
/* @internal */
/**
* Returns a DiagnosticMessage if we can't use a resolved module due to its extension.
* Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
* The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
* This returns a diagnostic even if the module will be an untyped module.
*/
export function getResolutionDiagnostic(options: CompilerOptions, { extension }: ResolvedModule): DiagnosticMessage | undefined {
export function getResolutionDiagnostic(options: CompilerOptions, { extension }: ResolvedModuleFull): DiagnosticMessage | undefined {
switch (extension) {
case Extension.Ts:
case Extension.Dts:
// These are always allowed.
return undefined;
case Extension.Tsx:
return needJsx();
case Extension.Jsx:
return options.jsx ? undefined : Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
return needJsx() || needAllowJs();
case Extension.Js:
return options.allowJs ? undefined : Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set;
return needAllowJs();
}
function needJsx() {
return options.jsx ? undefined : Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
}
function needAllowJs() {
return options.allowJs ? undefined : Diagnostics.Module_0_was_resolved_to_1_but_allowJs_is_not_set;
}
}
}
+1
View File
@@ -90,6 +90,7 @@ namespace ts {
"instanceof": SyntaxKind.InstanceOfKeyword,
"interface": SyntaxKind.InterfaceKeyword,
"is": SyntaxKind.IsKeyword,
"keyof": SyntaxKind.KeyOfKeyword,
"let": SyntaxKind.LetKeyword,
"module": SyntaxKind.ModuleKeyword,
"namespace": SyntaxKind.NamespaceKeyword,
+10 -8
View File
@@ -262,7 +262,8 @@ namespace ts {
}
function transformAsyncFunctionBody(node: FunctionLikeDeclaration): ConciseBody | FunctionBody {
const nodeType = node.original ? (<FunctionLikeDeclaration>node.original).type : node.type;
const original = getOriginalNode(node, isFunctionLike);
const nodeType = original.type;
const promiseConstructor = languageVersion < ScriptTarget.ES2015 ? getPromiseConstructor(nodeType) : undefined;
const isArrowFunction = node.kind === SyntaxKind.ArrowFunction;
const hasLexicalArguments = (resolver.getNodeCheckFlags(node) & NodeCheckFlags.CaptureArguments) !== 0;
@@ -336,15 +337,16 @@ namespace ts {
}
function getPromiseConstructor(type: TypeNode) {
const typeName = getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
if (type) {
const typeName = getEntityNameFromTypeNode(type);
if (typeName && isEntityName(typeName)) {
const serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
if (serializationKind === TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
|| serializationKind === TypeReferenceSerializationKind.Unknown) {
return typeName;
}
}
}
return undefined;
}
+4
View File
@@ -300,6 +300,8 @@ namespace ts {
case SyntaxKind.IntersectionType:
case SyntaxKind.ParenthesizedType:
case SyntaxKind.ThisType:
case SyntaxKind.TypeOperator:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.LiteralType:
// TypeScript type nodes are elided.
@@ -1783,6 +1785,8 @@ namespace ts {
}
// Fallthrough
case SyntaxKind.TypeQuery:
case SyntaxKind.TypeOperator:
case SyntaxKind.IndexedAccessType:
case SyntaxKind.TypeLiteral:
case SyntaxKind.AnyKeyword:
case SyntaxKind.ThisType:
+56 -17
View File
@@ -168,6 +168,7 @@ namespace ts {
DeclareKeyword,
GetKeyword,
IsKeyword,
KeyOfKeyword,
ModuleKeyword,
NamespaceKeyword,
NeverKeyword,
@@ -216,6 +217,8 @@ namespace ts {
IntersectionType,
ParenthesizedType,
ThisType,
TypeOperator,
IndexedAccessType,
LiteralType,
// Binding patterns
ObjectBindingPattern,
@@ -426,7 +429,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,
@@ -895,6 +898,18 @@ namespace ts {
type: TypeNode;
}
export interface TypeOperatorNode extends TypeNode {
kind: SyntaxKind.TypeOperator;
operator: SyntaxKind.KeyOfKeyword;
type: TypeNode;
}
export interface IndexedAccessTypeNode extends TypeNode {
kind: SyntaxKind.IndexedAccessType;
objectType: TypeNode;
indexType: TypeNode;
}
export interface LiteralTypeNode extends TypeNode {
kind: SyntaxKind.LiteralType;
literal: Expression;
@@ -966,10 +981,6 @@ namespace ts {
operator: PostfixUnaryOperator;
}
export interface PostfixExpression extends UnaryExpression {
_postfixExpressionBrand: any;
}
export interface LeftHandSideExpression extends IncrementExpression {
_leftHandSideExpressionBrand: any;
}
@@ -2087,6 +2098,9 @@ namespace ts {
// as well as code diagnostics).
/* @internal */ parseDiagnostics: Diagnostic[];
// Stores additional file level diagnostics reported by the program
/* @internal */ additionalSyntacticDiagnostics?: Diagnostic[];
// File level diagnostics reported by the binder.
/* @internal */ bindDiagnostics: Diagnostic[];
@@ -2097,7 +2111,7 @@ namespace ts {
// Stores a mapping 'external module reference text' -> 'resolved file name' | undefined
// It is used to resolve module names in the checker.
// Content of this field should never be used directly - use getResolvedModuleFileName/setResolvedModuleFileName functions instead
/* @internal */ resolvedModules: Map<ResolvedModule>;
/* @internal */ resolvedModules: Map<ResolvedModuleFull>;
/* @internal */ resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
/* @internal */ imports: LiteralExpression[];
/* @internal */ moduleAugmentations: LiteralExpression[];
@@ -2687,15 +2701,17 @@ namespace ts {
Object = 1 << 15, // Object type
Union = 1 << 16, // Union (T | U)
Intersection = 1 << 17, // Intersection (T & U)
Index = 1 << 18, // keyof T
IndexedAccess = 1 << 19, // T[K]
/* @internal */
FreshLiteral = 1 << 18, // Fresh literal type
FreshLiteral = 1 << 20, // Fresh literal type
/* @internal */
ContainsWideningType = 1 << 19, // Type is or contains undefined or null widening type
ContainsWideningType = 1 << 21, // Type is or contains undefined or null widening type
/* @internal */
ContainsObjectLiteral = 1 << 20, // Type is or contains object literal type
ContainsObjectLiteral = 1 << 22, // Type is or contains object literal type
/* @internal */
ContainsAnyFunctionType = 1 << 21, // Type is or contains object literal type
Spread = 1 << 22, // Spread types
ContainsAnyFunctionType = 1 << 23, // Type is or contains object literal type
Spread = 1 << 24, // Spread types
/* @internal */
Nullable = Undefined | Null,
@@ -2718,7 +2734,7 @@ namespace ts {
// '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 | Spread,
Narrowable = Any | StructuredType | TypeParameter | Index | IndexedAccess | StringLike | NumberLike | BooleanLike | ESSymbol | Spread,
NotUnionOrUnit = Any | ESSymbol | Object,
/* @internal */
RequiresWidening = ContainsWideningType | ContainsObjectLiteral,
@@ -2887,9 +2903,22 @@ namespace ts {
/* @internal */
resolvedApparentType: Type;
/* @internal */
resolvedIndexType: IndexType;
/* @internal */
resolvedIndexedAccessTypes: IndexedAccessType[];
/* @internal */
isThisType?: boolean;
}
export interface IndexType extends Type {
type: TypeParameter;
}
export interface IndexedAccessType extends Type {
objectType: Type;
indexType: TypeParameter;
}
export const enum SignatureKind {
Call,
Construct,
@@ -3172,6 +3201,7 @@ namespace ts {
Pretty,
}
/** Either a parsed command line or a parsed tsconfig.json */
export interface ParsedCommandLine {
options: CompilerOptions;
typingOptions?: TypingOptions;
@@ -3382,14 +3412,11 @@ namespace ts {
* Module resolution will pick up tsx/jsx/js files even if '--jsx' and '--allowJs' are turned off.
* The Program will then filter results based on these flags.
*
* At least one of `resolvedTsFileName` or `resolvedJsFileName` must be defined,
* else resolution should just return `undefined` instead of a ResolvedModule.
* Prefer to return a `ResolvedModuleFull` so that the file type does not have to be inferred.
*/
export interface ResolvedModule {
/** Path of the file the module was resolved to. */
resolvedFileName: string;
/** Extension of resolvedFileName. This must match what's at the end of resolvedFileName. */
extension: Extension;
/**
* Denotes if 'resolvedFileName' is isExternalLibraryImport and thus should be a proper external module:
* - be a .d.ts file
@@ -3399,6 +3426,18 @@ namespace ts {
isExternalLibraryImport?: boolean;
}
/**
* ResolvedModule with an explicitly provided `extension` property.
* Prefer this over `ResolvedModule`.
*/
export interface ResolvedModuleFull extends ResolvedModule {
/**
* Extension of resolvedFileName. This must match what's at the end of resolvedFileName.
* This is optional for backwards-compatibility, but will be added if not provided.
*/
extension: Extension;
}
export enum Extension {
Ts,
Tsx,
@@ -3409,7 +3448,7 @@ namespace ts {
}
export interface ResolvedModuleWithFailedLookupLocations {
resolvedModule: ResolvedModule | undefined;
resolvedModule: ResolvedModuleFull | undefined;
failedLookupLocations: string[];
}
+70 -38
View File
@@ -87,13 +87,13 @@ namespace ts {
return !!(sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules[moduleNameText]);
}
export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule {
export function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModuleFull {
return hasResolvedModule(sourceFile, moduleNameText) ? sourceFile.resolvedModules[moduleNameText] : undefined;
}
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void {
export function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModuleFull): void {
if (!sourceFile.resolvedModules) {
sourceFile.resolvedModules = createMap<ResolvedModule>();
sourceFile.resolvedModules = createMap<ResolvedModuleFull>();
}
sourceFile.resolvedModules[moduleNameText] = resolvedModule;
@@ -108,11 +108,7 @@ namespace ts {
}
/* @internal */
/**
* Considers two ResolvedModules equal if they have the same `resolvedFileName`.
* Thus `{ ts: foo, js: bar }` is equal to `{ ts: foo, js: baz }` because `ts` is preferred.
*/
export function moduleResolutionIsEqualTo(oldResolution: ResolvedModule, newResolution: ResolvedModule): boolean {
export function moduleResolutionIsEqualTo(oldResolution: ResolvedModuleFull, newResolution: ResolvedModuleFull): boolean {
return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
oldResolution.extension === newResolution.extension &&
oldResolution.resolvedFileName === newResolution.resolvedFileName;
@@ -406,6 +402,7 @@ namespace ts {
((<ModuleDeclaration>node).name.kind === SyntaxKind.StringLiteral || isGlobalScopeAugmentation(<ModuleDeclaration>node));
}
/** Given a symbol for a module, checks that it is either an untyped import or a shorthand ambient module. */
export function isShorthandAmbientModuleSymbol(moduleSymbol: Symbol): boolean {
return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
}
@@ -488,6 +485,17 @@ namespace ts {
return getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
}
export function entityNameToString(name: EntityNameOrEntityNameExpression): string {
switch (name.kind) {
case SyntaxKind.Identifier:
return getFullWidth(name) === 0 ? unescapeIdentifier((<Identifier>name).text) : getTextOfNode(name);
case SyntaxKind.QualifiedName:
return entityNameToString((<QualifiedName>name).left) + "." + entityNameToString((<QualifiedName>name).right);
case SyntaxKind.PropertyAccessExpression:
return entityNameToString((<PropertyAccessEntityNameExpression>name).expression) + "." + entityNameToString((<PropertyAccessEntityNameExpression>name).name);
}
}
export function createDiagnosticForNode(node: Node, message: DiagnosticMessage, arg0?: string | number, arg1?: string | number, arg2?: string | number): Diagnostic {
const sourceFile = getSourceFileOfNode(node);
const span = getErrorSpanForNode(sourceFile, node);
@@ -1045,17 +1053,19 @@ namespace ts {
}
export function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression {
if (node) {
switch (node.kind) {
case SyntaxKind.TypeReference:
return (<TypeReferenceNode>node).typeName;
case SyntaxKind.ExpressionWithTypeArguments:
Debug.assert(isEntityNameExpression((<ExpressionWithTypeArguments>node).expression));
return <EntityNameExpression>(<ExpressionWithTypeArguments>node).expression;
case SyntaxKind.Identifier:
case SyntaxKind.QualifiedName:
return (<EntityName><Node>node);
}
switch (node.kind) {
case SyntaxKind.TypeReference:
case SyntaxKind.JSDocTypeReference:
return (<TypeReferenceNode>node).typeName;
case SyntaxKind.ExpressionWithTypeArguments:
return isEntityNameExpression((<ExpressionWithTypeArguments>node).expression)
? <EntityNameExpression>(<ExpressionWithTypeArguments>node).expression
: undefined;
case SyntaxKind.Identifier:
case SyntaxKind.QualifiedName:
return (<EntityName><Node>node);
}
return undefined;
@@ -1609,29 +1619,51 @@ namespace ts {
return node && node.dotDotDotToken !== undefined;
}
export const enum AssignmentKind {
None, Definite, Compound
}
export function getAssignmentTargetKind(node: Node): AssignmentKind {
let parent = node.parent;
while (true) {
switch (parent.kind) {
case SyntaxKind.BinaryExpression:
const binaryOperator = (<BinaryExpression>parent).operatorToken.kind;
return isAssignmentOperator(binaryOperator) && (<BinaryExpression>parent).left === node ?
binaryOperator === SyntaxKind.EqualsToken ? AssignmentKind.Definite : AssignmentKind.Compound :
AssignmentKind.None;
case SyntaxKind.PrefixUnaryExpression:
case SyntaxKind.PostfixUnaryExpression:
const unaryOperator = (<PrefixUnaryExpression | PostfixUnaryExpression>parent).operator;
return unaryOperator === SyntaxKind.PlusPlusToken || unaryOperator === SyntaxKind.MinusMinusToken ? AssignmentKind.Compound : AssignmentKind.None;
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
return (<ForInStatement | ForOfStatement>parent).initializer === node ? AssignmentKind.Definite : AssignmentKind.None;
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.ArrayLiteralExpression:
case SyntaxKind.SpreadExpression:
node = parent;
break;
case SyntaxKind.ShorthandPropertyAssignment:
if ((<ShorthandPropertyAssignment>parent).name !== node) {
return AssignmentKind.None;
}
// Fall through
case SyntaxKind.PropertyAssignment:
node = parent.parent;
break;
default:
return AssignmentKind.None;
}
parent = node.parent;
}
}
// A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
// assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
// an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ p: a}] = xxx'.
export function isAssignmentTarget(node: Node): boolean {
while (node.parent.kind === SyntaxKind.ParenthesizedExpression) {
node = node.parent;
}
while (true) {
const parent = node.parent;
if (parent.kind === SyntaxKind.ArrayLiteralExpression || parent.kind === SyntaxKind.SpreadExpression) {
node = parent;
continue;
}
if (parent.kind === SyntaxKind.PropertyAssignment || parent.kind === SyntaxKind.ShorthandPropertyAssignment) {
node = parent.parent;
continue;
}
return parent.kind === SyntaxKind.BinaryExpression &&
isAssignmentOperator((<BinaryExpression>parent).operatorToken.kind) &&
(<BinaryExpression>parent).left === node ||
(parent.kind === SyntaxKind.ForInStatement || parent.kind === SyntaxKind.ForOfStatement) &&
(<ForInStatement | ForOfStatement>parent).initializer === node;
}
return getAssignmentTargetKind(node) !== AssignmentKind.None;
}
export function isNodeDescendantOf(node: Node, ancestor: Node): boolean {
+48 -93
View File
@@ -438,9 +438,8 @@ namespace FourSlash {
private getAllDiagnostics(): ts.Diagnostic[] {
const diagnostics: ts.Diagnostic[] = [];
const fileNames = this.languageServiceAdapterHost.getFilenames();
for (let i = 0, n = fileNames.length; i < n; i++) {
diagnostics.push.apply(this.getDiagnostics(fileNames[i]));
for (const fileName of this.languageServiceAdapterHost.getFilenames()) {
diagnostics.push.apply(this.getDiagnostics(fileName));
}
return diagnostics;
@@ -580,12 +579,12 @@ namespace FourSlash {
this.raiseError(`goToDefinitions failed - expected to find ${endMarkers.length} definitions but got ${definitions.length}`);
}
for (let i = 0; i < endMarkers.length; i++) {
const marker = this.getMarkerByName(endMarkers[i]), definition = definitions[i];
ts.zipWith(endMarkers, definitions, (endMarker, definition, i) => {
const marker = this.getMarkerByName(endMarker);
if (marker.fileName !== definition.fileName || marker.position !== definition.textSpan.start) {
this.raiseError(`goToDefinition failed for definition ${i}: expected ${marker.fileName} at ${marker.position}, got ${definition.fileName} at ${definition.textSpan.start}`);
}
}
});
}
public verifyGetEmitOutputForCurrentFile(expected: string): void {
@@ -602,10 +601,10 @@ namespace FourSlash {
public verifyGetEmitOutputContentsForCurrentFile(expected: ts.OutputFile[]): void {
const emit = this.languageService.getEmitOutput(this.activeFile.fileName);
assert.equal(emit.outputFiles.length, expected.length, "Number of emit output files");
for (let i = 0; i < emit.outputFiles.length; i++) {
assert.equal(emit.outputFiles[i].name, expected[i].name, "FileName");
assert.equal(emit.outputFiles[i].text, expected[i].text, "Content");
}
ts.zipWith(emit.outputFiles, expected, (outputFile, expected) => {
assert.equal(outputFile.name, expected.name, "FileName");
assert.equal(outputFile.text, expected.text, "Content");
});
}
public verifyMemberListContains(symbol: string, text?: string, documentation?: string, kind?: string) {
@@ -668,9 +667,9 @@ namespace FourSlash {
const entries = this.getCompletionListAtCaret().entries;
assert.isTrue(items.length <= entries.length, `Amount of expected items in completion list [ ${items.length} ] is greater than actual number of items in list [ ${entries.length} ]`);
for (let i = 0; i < items.length; i++) {
assert.equal(entries[i].name, items[i], `Unexpected item in completion list`);
}
ts.zipWith(entries, items, (entry, item) => {
assert.equal(entry.name, item, `Unexpected item in completion list`);
});
}
public noItemsWithSameNameButDifferentKind(): void {
@@ -692,15 +691,7 @@ namespace FourSlash {
this.raiseError("Member list is empty at Caret");
}
else if ((members && members.entries.length !== 0) && !negative) {
let errorMsg = "\n" + "Member List contains: [" + members.entries[0].name;
for (let i = 1; i < members.entries.length; i++) {
errorMsg += ", " + members.entries[i].name;
}
errorMsg += "]\n";
this.raiseError("Member list is not empty at Caret: " + errorMsg);
this.raiseError(`Member list is not empty at Caret:\nMember List contains: ${stringify(members.entries.map(e => e.name))}`);
}
}
@@ -710,13 +701,8 @@ namespace FourSlash {
this.raiseError("Completion list is empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition);
}
else if (completions && completions.entries.length !== 0 && !negative) {
let errorMsg = "\n" + "Completion List contains: [" + completions.entries[0].name;
for (let i = 1; i < completions.entries.length; i++) {
errorMsg += ", " + completions.entries[i].name;
}
errorMsg += "]\n";
this.raiseError("Completion list is not empty at caret at position " + this.activeFile.fileName + " " + this.currentCaretPosition + errorMsg);
this.raiseError(`Completion list is not empty at caret at position ${this.activeFile.fileName} ${this.currentCaretPosition}\n` +
`Completion List contains: ${stringify(completions.entries.map(e => e.name))}`);
}
}
@@ -890,8 +876,7 @@ namespace FourSlash {
}
private verifyReferencesWorker(references: ts.ReferenceEntry[], fileName: string, start: number, end: number, isWriteAccess?: boolean, isDefinition?: boolean) {
for (let i = 0; i < references.length; i++) {
const reference = references[i];
for (const reference of references) {
if (reference && reference.fileName === fileName && reference.textSpan.start === start && ts.textSpanEnd(reference.textSpan) === end) {
if (typeof isWriteAccess !== "undefined" && reference.isWriteAccess !== isWriteAccess) {
this.raiseError(`verifyReferencesAtPositionListContains failed - item isWriteAccess value does not match, actual: ${reference.isWriteAccess}, expected: ${isWriteAccess}.`);
@@ -1008,16 +993,11 @@ namespace FourSlash {
ranges = ranges.sort((r1, r2) => r1.start - r2.start);
references = references.sort((r1, r2) => r1.textSpan.start - r2.textSpan.start);
for (let i = 0, n = ranges.length; i < n; i++) {
const reference = references[i];
const range = ranges[i];
if (reference.textSpan.start !== range.start ||
ts.textSpanEnd(reference.textSpan) !== range.end) {
ts.zipWith(references, ranges, (reference, range) => {
if (reference.textSpan.start !== range.start || ts.textSpanEnd(reference.textSpan) !== range.end) {
this.raiseError("Rename location results do not match.\n\nExpected: " + stringify(ranges) + "\n\nActual:" + JSON.stringify(references));
}
}
});
}
else {
this.raiseError("Expected rename to succeed, but it actually failed.");
@@ -1247,8 +1227,7 @@ namespace FourSlash {
const emitFiles: FourSlashFile[] = []; // List of FourSlashFile that has emitThisFile flag on
const allFourSlashFiles = this.testData.files;
for (let idx = 0; idx < allFourSlashFiles.length; idx++) {
const file = allFourSlashFiles[idx];
for (const file of allFourSlashFiles) {
if (file.fileOptions[metadataOptionNames.emitThisFile] === "true") {
// Find a file with the flag emitThisFile turned on
emitFiles.push(file);
@@ -1273,8 +1252,8 @@ namespace FourSlash {
if (emitOutput.emitSkipped) {
resultString += "Diagnostics:" + Harness.IO.newLine();
const diagnostics = ts.getPreEmitDiagnostics(this.languageService.getProgram());
for (let i = 0, n = diagnostics.length; i < n; i++) {
resultString += " " + diagnostics[0].messageText + Harness.IO.newLine();
for (const diagnostic of diagnostics) {
resultString += " " + diagnostic.messageText + Harness.IO.newLine();
}
}
@@ -1340,8 +1319,7 @@ namespace FourSlash {
}
public printCurrentFileState(makeWhitespaceVisible = false, makeCaretVisible = true) {
for (let i = 0; i < this.testData.files.length; i++) {
const file = this.testData.files[i];
for (const file of this.testData.files) {
const active = (this.activeFile === file);
Harness.IO.log(`=== Script (${file.fileName}) ${(active ? "(active, cursor at |)" : "")} ===`);
let content = this.getFileContent(file.fileName);
@@ -1576,10 +1554,10 @@ namespace FourSlash {
edits = edits.sort((a, b) => a.span.start - b.span.start);
// Get a snapshot of the content of the file so we can make sure any formatting edits didn't destroy non-whitespace characters
const oldContent = this.getFileContent(this.activeFile.fileName);
for (let j = 0; j < edits.length; j++) {
this.languageServiceAdapterHost.editScript(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText);
this.updateMarkersForEdit(fileName, edits[j].span.start + runningOffset, ts.textSpanEnd(edits[j].span) + runningOffset, edits[j].newText);
const change = (edits[j].span.start - ts.textSpanEnd(edits[j].span)) + edits[j].newText.length;
for (const edit of edits) {
this.languageServiceAdapterHost.editScript(fileName, edit.span.start + runningOffset, ts.textSpanEnd(edit.span) + runningOffset, edit.newText);
this.updateMarkersForEdit(fileName, edit.span.start + runningOffset, ts.textSpanEnd(edit.span) + runningOffset, edit.newText);
const change = (edit.span.start - ts.textSpanEnd(edit.span)) + edit.newText.length;
runningOffset += change;
// TODO: Consider doing this at least some of the time for higher fidelity. Currently causes a failure (bug 707150)
// this.languageService.getScriptLexicalStructure(fileName);
@@ -1913,10 +1891,7 @@ namespace FourSlash {
jsonMismatchString());
}
for (let i = 0; i < expected.length; i++) {
const expectedClassification = expected[i];
const actualClassification = actual[i];
ts.zipWith(expected, actual, (expectedClassification, actualClassification) => {
const expectedType: string = (<any>ts.ClassificationTypeNames)[expectedClassification.classificationType];
if (expectedType !== actualClassification.classificationType) {
this.raiseError("verifyClassifications failed - expected classifications type to be " +
@@ -1946,7 +1921,7 @@ namespace FourSlash {
actualText +
jsonMismatchString());
}
}
});
function jsonMismatchString() {
return Harness.IO.newLine() +
@@ -1991,13 +1966,11 @@ namespace FourSlash {
this.raiseError(`verifyOutliningSpans failed - expected total spans to be ${spans.length}, but was ${actual.length}`);
}
for (let i = 0; i < spans.length; i++) {
const expectedSpan = spans[i];
const actualSpan = actual[i];
ts.zipWith(spans, actual, (expectedSpan, actualSpan, i) => {
if (expectedSpan.start !== actualSpan.textSpan.start || expectedSpan.end !== ts.textSpanEnd(actualSpan.textSpan)) {
this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualSpan.textSpan.start},${ts.textSpanEnd(actualSpan.textSpan)})`);
}
}
});
}
public verifyTodoComments(descriptors: string[], spans: TextSpan[]) {
@@ -2008,15 +1981,13 @@ namespace FourSlash {
this.raiseError(`verifyTodoComments failed - expected total spans to be ${spans.length}, but was ${actual.length}`);
}
for (let i = 0; i < spans.length; i++) {
const expectedSpan = spans[i];
const actualComment = actual[i];
ts.zipWith(spans, actual, (expectedSpan, actualComment, i) => {
const actualCommentSpan = ts.createTextSpan(actualComment.position, actualComment.message.length);
if (expectedSpan.start !== actualCommentSpan.start || expectedSpan.end !== ts.textSpanEnd(actualCommentSpan)) {
this.raiseError(`verifyOutliningSpans failed - span ${(i + 1)} expected: (${expectedSpan.start},${expectedSpan.end}), actual: (${actualCommentSpan.start},${ts.textSpanEnd(actualCommentSpan)})`);
}
}
});
}
private getCodeFixes(errorCode?: number) {
@@ -2163,11 +2134,9 @@ namespace FourSlash {
public verifyNavigationItemsCount(expected: number, searchValue: string, matchKind?: string, fileName?: string) {
const items = this.languageService.getNavigateToItems(searchValue, /*maxResultCount*/ undefined, fileName);
let actual = 0;
let item: ts.NavigateToItem;
// Count only the match that match the same MatchKind
for (let i = 0; i < items.length; i++) {
item = items[i];
for (const item of items) {
if (!matchKind || item.matchKind === matchKind) {
actual++;
}
@@ -2195,8 +2164,7 @@ namespace FourSlash {
this.raiseError("verifyNavigationItemsListContains failed - found 0 navigation items, expected at least one.");
}
for (let i = 0; i < items.length; i++) {
const item = items[i];
for (const item of items) {
if (item && item.name === name && item.kind === kind &&
(matchKind === undefined || item.matchKind === matchKind) &&
(fileName === undefined || item.fileName === fileName) &&
@@ -2247,24 +2215,16 @@ namespace FourSlash {
public printNavigationItems(searchValue: string) {
const items = this.languageService.getNavigateToItems(searchValue);
const length = items && items.length;
Harness.IO.log(`NavigationItems list (${length} items)`);
for (let i = 0; i < length; i++) {
const item = items[i];
Harness.IO.log(`NavigationItems list (${items.length} items)`);
for (const item of items) {
Harness.IO.log(`name: ${item.name}, kind: ${item.kind}, parentName: ${item.containerName}, fileName: ${item.fileName}`);
}
}
public printNavigationBar() {
const items = this.languageService.getNavigationBarItems(this.activeFile.fileName);
const length = items && items.length;
Harness.IO.log(`Navigation bar (${length} items)`);
for (let i = 0; i < length; i++) {
const item = items[i];
Harness.IO.log(`Navigation bar (${items.length} items)`);
for (const item of items) {
Harness.IO.log(`${repeatString(item.indent, " ")}name: ${item.text}, kind: ${item.kind}, childItems: ${item.childItems.map(child => child.text)}`);
}
}
@@ -2385,8 +2345,7 @@ namespace FourSlash {
}
private assertItemInCompletionList(items: ts.CompletionEntry[], name: string, text?: string, documentation?: string, kind?: string, spanIndex?: number) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
for (const item of items) {
if (item.name === name) {
if (documentation != undefined || text !== undefined) {
const details = this.getCompletionEntryDetails(item.name);
@@ -2435,20 +2394,17 @@ namespace FourSlash {
name = name.indexOf("/") === -1 ? (this.basePath + "/" + name) : name;
const availableNames: string[] = [];
let foundIt = false;
for (let i = 0; i < this.testData.files.length; i++) {
const fn = this.testData.files[i].fileName;
result = ts.forEach(this.testData.files, file => {
const fn = file.fileName;
if (fn) {
if (fn === name) {
result = this.testData.files[i];
foundIt = true;
break;
return file;
}
availableNames.push(fn);
}
}
});
if (!foundIt) {
if (!result) {
throw new Error(`No test file named "${name}" exists. Available file names are: ${availableNames.join(", ")}`);
}
}
@@ -2549,8 +2505,8 @@ ${code}
function chompLeadingSpace(content: string) {
const lines = content.split("\n");
for (let i = 0; i < lines.length; i++) {
if ((lines[i].length !== 0) && (lines[i].charAt(0) !== " ")) {
for (const line of lines) {
if ((line.length !== 0) && (line.charAt(0) !== " ")) {
return content;
}
}
@@ -2588,8 +2544,7 @@ ${code}
currentFileName = fileName;
}
for (let i = 0; i < lines.length; i++) {
let line = lines[i];
for (let line of lines) {
const lineLength = line.length;
if (lineLength > 0 && line.charAt(lineLength - 1) === "\r") {
+37 -24
View File
@@ -1029,7 +1029,7 @@ namespace Harness {
},
realpath: realPathMap && ((f: string) => {
const path = ts.toPath(f, currentDirectory, getCanonicalFileName);
return realPathMap.contains(path) ? realPathMap.get(path) : path;
return realPathMap.get(path) || path;
}),
directoryExists: dir => {
let path = ts.toPath(dir, currentDirectory, getCanonicalFileName);
@@ -1037,13 +1037,7 @@ namespace Harness {
if (path[path.length - 1] === "/") {
path = <ts.Path>path.substr(0, path.length - 1);
}
let exists = false;
fileMap.forEachValue(key => {
if (key.indexOf(path) === 0 && key[path.length] === "/") {
exists = true;
}
});
return exists;
return mapHasFileInDirectory(path, fileMap) || mapHasFileInDirectory(path, realPathMap);
},
getDirectories: d => {
const path = ts.toPath(d, currentDirectory, getCanonicalFileName);
@@ -1064,6 +1058,19 @@ namespace Harness {
};
}
function mapHasFileInDirectory(directoryPath: ts.Path, map: ts.FileMap<any>): boolean {
if (!map) {
return false;
}
let exists = false;
map.forEachValue(fileName => {
if (!exists && ts.startsWith(fileName, directoryPath) && fileName[directoryPath.length] === "/") {
exists = true;
}
});
return exists;
}
interface HarnessOptions {
useCaseSensitiveFileNames?: boolean;
includeBuiltFile?: string;
@@ -1108,22 +1115,7 @@ namespace Harness {
const option = getCommandLineOption(name);
if (option) {
const errors: ts.Diagnostic[] = [];
switch (option.type) {
case "boolean":
options[option.name] = value.toLowerCase() === "true";
break;
case "string":
options[option.name] = value;
break;
// If not a primitive, the possible types are specified in what is effectively a map of options.
case "list":
options[option.name] = ts.parseListTypeOption(<ts.CommandLineOptionOfListType>option, value, errors);
break;
default:
options[option.name] = ts.parseCustomTypeOption(<ts.CommandLineOptionOfCustomType>option, value, errors);
break;
}
options[option.name] = optionValue(option, value, errors);
if (errors.length > 0) {
throw new Error(`Unknown value '${value}' for compiler option '${name}'.`);
}
@@ -1135,6 +1127,27 @@ namespace Harness {
}
}
function optionValue(option: ts.CommandLineOption, value: string, errors: ts.Diagnostic[]): any {
switch (option.type) {
case "boolean":
return value.toLowerCase() === "true";
case "string":
return value;
case "number": {
const number = parseInt(value, 10);
if (isNaN(number)) {
throw new Error(`Value must be a number, got: ${JSON.stringify(value)}`);
}
return number;
}
// If not a primitive, the possible types are specified in what is effectively a map of options.
case "list":
return ts.parseListTypeOption(<ts.CommandLineOptionOfListType>option, value, errors);
default:
return ts.parseCustomTypeOption(<ts.CommandLineOptionOfCustomType>option, value, errors);
}
}
export interface TestFile {
unitName: string;
content: string;
+10 -26
View File
@@ -22,33 +22,17 @@ namespace ts {
newLine: "\r\n",
useCaseSensitiveFileNames: false,
write: noop,
readFile: (path: string): string => {
return path in fileMap ? fileMap[path].content : undefined;
},
writeFile: (_path: string, _data: string, _writeByteOrderMark?: boolean) => {
return ts.notImplemented();
},
resolvePath: (_path: string): string => {
return ts.notImplemented();
},
fileExists: (path: string): boolean => {
return path in fileMap;
},
directoryExists: (path: string): boolean => {
return existingDirectories[path] || false;
},
readFile: path => path in fileMap ? fileMap[path].content : undefined,
writeFile: notImplemented,
resolvePath: notImplemented,
fileExists: path => path in fileMap,
directoryExists: path => existingDirectories[path] || false,
createDirectory: noop,
getExecutingFilePath: (): string => {
return "";
},
getCurrentDirectory: (): string => {
return "";
},
getExecutingFilePath: () => "",
getCurrentDirectory: () => "",
getDirectories: () => [],
getEnvironmentVariable: () => "",
readDirectory: (_path: string, _extension?: string[], _exclude?: string[], _include?: string[]): string[] => {
return ts.notImplemented();
},
readDirectory: notImplemented,
exit: noop,
watchFile: () => ({
close: noop
@@ -58,8 +42,8 @@ namespace ts {
}),
setTimeout,
clearTimeout,
setImmediate,
clearImmediate
setImmediate: typeof setImmediate !== "undefined" ? setImmediate : action => setTimeout(action, 0),
clearImmediate: typeof clearImmediate !== "undefined" ? clearImmediate : clearTimeout
};
}
+75 -153
View File
@@ -91,6 +91,12 @@ namespace ts {
const defaultExcludes = ["node_modules", "bower_components", "jspm_packages"];
function assertParsed(actual: ts.ParsedCommandLine, expected: ts.ParsedCommandLine): void {
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
}
describe("matchFiles", () => {
describe("with literal file list", () => {
it("without exclusions", () => {
@@ -110,9 +116,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("missing files are still present", () => {
const json = {
@@ -131,9 +135,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("are not removed due to excludes", () => {
const json = {
@@ -155,9 +157,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
});
@@ -179,9 +179,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with non .ts file extensions are excluded", () => {
const json = {
@@ -200,9 +198,7 @@ namespace ts {
wildcardDirectories: {},
};
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);
assertParsed(actual, expected);
});
it("with missing files are excluded", () => {
const json = {
@@ -221,9 +217,7 @@ namespace ts {
wildcardDirectories: {},
};
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);
assertParsed(actual, expected);
});
it("with literal excludes", () => {
const json = {
@@ -244,9 +238,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with wildcard excludes", () => {
const json = {
@@ -274,9 +266,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with recursive excludes", () => {
const json = {
@@ -303,9 +293,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with case sensitive exclude", () => {
const json = {
@@ -325,9 +313,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseSensitiveHost, caseSensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with common package folders and no exclusions", () => {
const json = {
@@ -349,9 +335,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with common package folders and exclusions", () => {
const json = {
@@ -378,9 +362,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with common package folders and empty exclude", () => {
const json = {
@@ -406,9 +388,7 @@ namespace ts {
wildcardDirectories: {},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
});
@@ -432,9 +412,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("`*` matches only ts files", () => {
const json = {
@@ -455,9 +433,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("`?` matches only a single character", () => {
const json = {
@@ -477,9 +453,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with recursive directory", () => {
const json = {
@@ -501,9 +475,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with multiple recursive directories", () => {
const json = {
@@ -527,9 +499,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("case sensitive", () => {
const json = {
@@ -548,9 +518,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseSensitiveHost, caseSensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with missing files are excluded", () => {
const json = {
@@ -570,9 +538,7 @@ namespace ts {
},
};
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);
assertParsed(actual, expected);
});
it("always include literal files", () => {
const json = {
@@ -597,9 +563,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("exclude folders", () => {
const json = {
@@ -624,9 +588,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with common package folders and no exclusions", () => {
const json = {
@@ -645,9 +607,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with common package folders and exclusions", () => {
const json = {
@@ -671,9 +631,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with common package folders and empty exclude", () => {
const json = {
@@ -696,9 +654,7 @@ namespace ts {
},
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveCommonFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("exclude .js files when allowJs=false", () => {
const json = {
@@ -723,9 +679,7 @@ namespace ts {
}
};
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);
assertParsed(actual, expected);
});
it("include .js files when allowJs=true", () => {
const json = {
@@ -750,9 +704,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("include explicitly listed .min.js files when allowJs=true", () => {
const json = {
@@ -777,9 +729,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("include paths outside of the project", () => {
const json = {
@@ -803,9 +753,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("include paths outside of the project using relative paths", () => {
const json = {
@@ -828,9 +776,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("exclude paths outside of the project using relative paths", () => {
const json = {
@@ -851,9 +797,7 @@ namespace ts {
wildcardDirectories: {}
};
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);
assertParsed(actual, expected);
});
it("include files with .. in their name", () => {
const json = {
@@ -873,9 +817,7 @@ namespace ts {
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("exclude files with .. in their name", () => {
const json = {
@@ -897,9 +839,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with jsx=none, allowJs=false", () => {
const json = {
@@ -922,9 +862,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with jsx=preserve, allowJs=false", () => {
const json = {
@@ -949,9 +887,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with jsx=none, allowJs=true", () => {
const json = {
@@ -976,9 +912,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with jsx=preserve, allowJs=true", () => {
const json = {
@@ -1005,9 +939,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveMixedExtensionHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("exclude .min.js files using wildcards", () => {
const json = {
@@ -1034,9 +966,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
describe("with trailing recursive directory", () => {
it("in includes", () => {
@@ -1056,9 +986,7 @@ namespace ts {
wildcardDirectories: {}
};
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);
assertParsed(actual, expected);
});
it("in excludes", () => {
const json = {
@@ -1079,9 +1007,7 @@ namespace ts {
wildcardDirectories: {}
};
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);
assertParsed(actual, expected);
});
});
describe("with multiple recursive directory patterns", () => {
@@ -1102,9 +1028,7 @@ namespace ts {
wildcardDirectories: {}
};
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);
assertParsed(actual, expected);
});
it("in excludes", () => {
const json = {
@@ -1131,9 +1055,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
});
@@ -1155,9 +1077,7 @@ namespace ts {
wildcardDirectories: {}
};
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);
assertParsed(actual, expected);
});
it("in includes after a subdirectory", () => {
@@ -1177,9 +1097,7 @@ namespace ts {
wildcardDirectories: {}
};
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);
assertParsed(actual, expected);
});
it("in excludes immediately after", () => {
@@ -1207,9 +1125,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("in excludes after a subdirectory", () => {
@@ -1237,9 +1153,25 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
});
describe("with implicit globbification", () => {
it("Expands 'z' to 'z/**/*'", () => {
const json = {
include: ["z"]
};
const expected: ts.ParsedCommandLine = {
options: {},
errors: [],
fileNames: [ "a.ts", "aba.ts", "abz.ts", "b.ts", "bba.ts", "bbz.ts" ].map(x => `c:/dev/z/${x}`),
wildcardDirectories: {
"c:/dev/z": ts.WatchDirectoryFlags.Recursive
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveHost, caseInsensitiveBasePath);
assertParsed(actual, expected);
});
});
});
@@ -1264,9 +1196,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
describe("that are explicitly included", () => {
it("without wildcards", () => {
@@ -1286,9 +1216,7 @@ namespace ts {
wildcardDirectories: {}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with recursive wildcards that match directories", () => {
const json = {
@@ -1310,9 +1238,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with recursive wildcards that match nothing", () => {
const json = {
@@ -1334,9 +1260,7 @@ namespace ts {
}
};
const actual = ts.parseJsonConfigFileContent(json, caseInsensitiveDottedFoldersHost, caseInsensitiveBasePath);
assert.deepEqual(actual.fileNames, expected.fileNames);
assert.deepEqual(actual.wildcardDirectories, expected.wildcardDirectories);
assert.deepEqual(actual.errors, expected.errors);
assertParsed(actual, expected);
});
it("with wildcard excludes that implicitly exclude dotted files", () => {
const json = {
@@ -1357,9 +1281,7 @@ namespace ts {
wildcardDirectories: {}
};
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);
assertParsed(actual, expected);
});
});
});
+3 -3
View File
@@ -1,7 +1,7 @@
/// <reference path="..\harness.ts" />
namespace ts {
export function checkResolvedModule(expected: ResolvedModule, actual: ResolvedModule): boolean {
export function checkResolvedModule(expected: ResolvedModuleFull, actual: ResolvedModuleFull): boolean {
if (!expected === !actual) {
if (expected) {
assert.isTrue(expected.resolvedFileName === actual.resolvedFileName, `'resolvedFileName': expected '${expected.resolvedFileName}' to be equal to '${actual.resolvedFileName}'`);
@@ -13,13 +13,13 @@ namespace ts {
return false;
}
export function checkResolvedModuleWithFailedLookupLocations(actual: ResolvedModuleWithFailedLookupLocations, expectedResolvedModule: ResolvedModule, expectedFailedLookupLocations: string[]): void {
export function checkResolvedModuleWithFailedLookupLocations(actual: ResolvedModuleWithFailedLookupLocations, expectedResolvedModule: ResolvedModuleFull, expectedFailedLookupLocations: string[]): void {
assert.isTrue(actual.resolvedModule !== undefined, "module should be resolved");
checkResolvedModule(actual.resolvedModule, expectedResolvedModule);
assert.deepEqual(actual.failedLookupLocations, expectedFailedLookupLocations);
}
export function createResolvedModule(resolvedFileName: string, isExternalLibraryImport = false): ResolvedModule {
export function createResolvedModule(resolvedFileName: string, isExternalLibraryImport = false): ResolvedModuleFull {
return { resolvedFileName, extension: extensionFromPath(resolvedFileName), isExternalLibraryImport };
}
+2 -1
View File
@@ -150,7 +150,8 @@ namespace ts.server {
target: ScriptTarget.ES5,
jsx: JsxEmit.React,
newLine: NewLineKind.LineFeed,
moduleResolution: ModuleResolutionKind.NodeJs
moduleResolution: ModuleResolutionKind.NodeJs,
allowNonTsExtensions: true // injected by tsserver
});
});
});
@@ -2471,4 +2471,38 @@ namespace ts.projectSystem {
});
});
describe("Inferred projects", () => {
it("should support files without extensions", () => {
const f = {
path: "/a/compile",
content: "let x = 1"
};
const host = createServerHost([f]);
const session = createSession(host);
session.executeCommand(<server.protocol.SetCompilerOptionsForInferredProjectsRequest>{
seq: 1,
type: "request",
command: "compilerOptionsForInferredProjects",
arguments: {
options: {
allowJs: true
}
}
});
session.executeCommand(<server.protocol.OpenRequest>{
seq: 2,
type: "request",
command: "open",
arguments: {
file: f.path,
fileContent: f.content,
scriptKindName: "JS"
}
});
const projectService = session.getProjectService();
checkNumberOfProjects(projectService, { inferredProjects: 1 });
checkProjectActualFiles(projectService.inferredProjects[0], [f.path]);
});
});
}
+16 -12
View File
@@ -1679,6 +1679,7 @@ interface CSSStyleDeclaration {
writingMode: string | null;
zIndex: string | null;
zoom: string | null;
resize: string | null;
getPropertyPriority(propertyName: string): string;
getPropertyValue(propertyName: string): string;
item(index: number): string;
@@ -1748,6 +1749,7 @@ declare var CanvasGradient: {
}
interface CanvasPattern {
setTransform(matrix: SVGMatrix): void;
}
declare var CanvasPattern: {
@@ -2173,7 +2175,7 @@ interface DataTransfer {
effectAllowed: string;
readonly files: FileList;
readonly items: DataTransferItemList;
readonly types: DOMStringList;
readonly types: string[];
clearData(format?: string): boolean;
getData(format: string): string;
setData(format: string, data: string): boolean;
@@ -7584,7 +7586,7 @@ declare var IDBCursorWithValue: {
interface IDBDatabase extends EventTarget {
readonly name: string;
readonly objectStoreNames: DOMStringList;
readonly objectStoreNames: string[];
onabort: (this: this, ev: Event) => any;
onerror: (this: this, ev: ErrorEvent) => any;
version: number;
@@ -7650,7 +7652,7 @@ declare var IDBKeyRange: {
}
interface IDBObjectStore {
readonly indexNames: DOMStringList;
readonly indexNames: string[];
keyPath: string | string[];
readonly name: string;
readonly transaction: IDBTransaction;
@@ -8602,7 +8604,7 @@ interface MouseEvent extends UIEvent {
readonly x: number;
readonly y: number;
getModifierState(keyArg: string): boolean;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget): void;
initMouseEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, ctrlKeyArg: boolean, altKeyArg: boolean, shiftKeyArg: boolean, metaKeyArg: boolean, buttonArg: number, relatedTargetArg: EventTarget | null): void;
}
declare var MouseEvent: {
@@ -8715,6 +8717,7 @@ interface Navigator extends Object, NavigatorID, NavigatorOnLine, NavigatorConte
readonly plugins: PluginArray;
readonly pointerEnabled: boolean;
readonly webdriver: boolean;
readonly hardwareConcurrency: number;
getGamepads(): Gamepad[];
javaEnabled(): boolean;
msLaunchUri(uri: string, successCallback?: MSLaunchUriCallback, noHandlerCallback?: MSLaunchUriCallback): void;
@@ -8732,18 +8735,18 @@ interface Node extends EventTarget {
readonly attributes: NamedNodeMap;
readonly baseURI: string | null;
readonly childNodes: NodeList;
readonly firstChild: Node;
readonly lastChild: Node;
readonly firstChild: Node | null;
readonly lastChild: Node | null;
readonly localName: string | null;
readonly namespaceURI: string | null;
readonly nextSibling: Node;
readonly nextSibling: Node | null;
readonly nodeName: string;
readonly nodeType: number;
nodeValue: string | null;
readonly ownerDocument: Document;
readonly parentElement: HTMLElement;
readonly parentNode: Node;
readonly previousSibling: Node;
readonly parentElement: HTMLElement | null;
readonly parentNode: Node | null;
readonly previousSibling: Node | null;
textContent: string | null;
appendChild(newChild: Node): Node;
cloneNode(deep?: boolean): Node;
@@ -12853,7 +12856,7 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window
readonly devicePixelRatio: number;
readonly doNotTrack: string;
readonly document: Document;
event: Event;
event: Event | undefined;
readonly external: External;
readonly frameElement: Element;
readonly frames: Window;
@@ -13155,6 +13158,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
msCaching?: string;
readonly responseURL: string;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
@@ -14301,7 +14305,7 @@ declare var defaultStatus: string;
declare var devicePixelRatio: number;
declare var doNotTrack: string;
declare var document: Document;
declare var event: Event;
declare var event: Event | undefined;
declare var external: External;
declare var frameElement: Element;
declare var frames: Window;
+4 -2
View File
@@ -341,7 +341,7 @@ declare var IDBCursorWithValue: {
interface IDBDatabase extends EventTarget {
readonly name: string;
readonly objectStoreNames: DOMStringList;
readonly objectStoreNames: string[];
onabort: (this: this, ev: Event) => any;
onerror: (this: this, ev: ErrorEvent) => any;
version: number;
@@ -407,7 +407,7 @@ declare var IDBKeyRange: {
}
interface IDBObjectStore {
readonly indexNames: DOMStringList;
readonly indexNames: string[];
keyPath: string | string[];
readonly name: string;
readonly transaction: IDBTransaction;
@@ -740,6 +740,7 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
readonly upload: XMLHttpRequestUpload;
withCredentials: boolean;
msCaching?: string;
readonly responseURL: string;
abort(): void;
getAllResponseHeaders(): string;
getResponseHeader(header: string): string | null;
@@ -902,6 +903,7 @@ declare var WorkerLocation: {
}
interface WorkerNavigator extends Object, NavigatorID, NavigatorOnLine {
readonly hardwareConcurrency: number;
addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}
+4 -1
View File
@@ -298,6 +298,9 @@ namespace ts.server {
setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void {
this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions);
// always set 'allowNonTsExtensions' for inferred projects since user cannot configure it from the outside
// previously we did not expose a way for user to change these settings and this option was enabled by default
this.compilerOptionsForInferredProjects.allowNonTsExtensions = true;
this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave;
for (const proj of this.inferredProjects) {
proj.setCompilerOptions(this.compilerOptionsForInferredProjects);
@@ -1008,7 +1011,7 @@ namespace ts.server {
const useExistingProject = this.useSingleInferredProject && this.inferredProjects.length;
const project = useExistingProject
? this.inferredProjects[0]
: new InferredProject(this, this.documentRegistry, /*languageServiceEnabled*/ true, this.compilerOptionsForInferredProjects, /*compileOnSaveEnabled*/ this.compileOnSaveForInferredProjects);
: new InferredProject(this, this.documentRegistry, /*languageServiceEnabled*/ true, this.compilerOptionsForInferredProjects);
project.addRoot(root);
+1 -1
View File
@@ -151,7 +151,7 @@ namespace ts.server {
m => m.resolvedTypeReferenceDirective, r => r.resolvedFileName, /*logChanges*/ false);
}
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[] {
resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModuleFull[] {
return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName,
m => m.resolvedModule, r => r.resolvedFileName, /*logChanges*/ true);
}
+2 -2
View File
@@ -666,14 +666,14 @@ namespace ts.server {
// Used to keep track of what directories are watched for this project
directoriesWatchedForTsconfig: string[] = [];
constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, public compileOnSaveEnabled: boolean) {
constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions) {
super(ProjectKind.Inferred,
projectService,
documentRegistry,
/*files*/ undefined,
languageServiceEnabled,
compilerOptions,
compileOnSaveEnabled);
/*compileOnSaveEnabled*/ false);
this.inferredProjectName = makeInferredProjectName(InferredProject.NextId);
InferredProject.NextId++;
+1 -1
View File
@@ -467,7 +467,7 @@ namespace ts {
public languageVariant: LanguageVariant;
public identifiers: Map<string>;
public nameTable: Map<number>;
public resolvedModules: Map<ResolvedModule>;
public resolvedModules: Map<ResolvedModuleFull>;
public resolvedTypeReferenceDirectiveNames: Map<ResolvedTypeReferenceDirective>;
public imports: LiteralExpression[];
public moduleAugmentations: LiteralExpression[];
+1 -1
View File
@@ -316,7 +316,7 @@ namespace ts {
private loggingEnabled = false;
private tracingEnabled = false;
public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModule[];
public resolveModuleNames: (moduleName: string[], containingFile: string) => ResolvedModuleFull[];
public resolveTypeReferenceDirectives: (typeDirectiveNames: string[], containingFile: string) => ResolvedTypeReferenceDirective[];
public directoryExists: (directoryName: string) => boolean;