diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index dda476e4e3957..110f36e21df5d 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -22,8 +22,8 @@ and limitations under the License. /// ECMAScript APIs ///////////////////////////// -declare const NaN: number; -declare const Infinity: number; +declare var NaN: number; +declare var Infinity: number; /** * Evaluates JavaScript code and executes it. @@ -264,7 +264,7 @@ interface ObjectConstructor { /** * Provides functionality common to all JavaScript objects. */ -declare const Object: ObjectConstructor; +declare var Object: ObjectConstructor; /** * Creates a new function. @@ -313,7 +313,7 @@ interface FunctionConstructor { readonly prototype: Function; } -declare const Function: FunctionConstructor; +declare var Function: FunctionConstructor; /** * Extracts the type of the 'this' parameter of a function type, or 'unknown' if the function type has no 'this' parameter. @@ -524,7 +524,7 @@ interface StringConstructor { /** * Allows manipulation and formatting of text strings and determination and location of substrings within strings. */ -declare const String: StringConstructor; +declare var String: StringConstructor; interface Boolean { /** Returns the primitive value of the specified object. */ @@ -537,7 +537,7 @@ interface BooleanConstructor { readonly prototype: Boolean; } -declare const Boolean: BooleanConstructor; +declare var Boolean: BooleanConstructor; interface Number { /** @@ -599,7 +599,7 @@ interface NumberConstructor { } /** An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. */ -declare const Number: NumberConstructor; +declare var Number: NumberConstructor; interface TemplateStringsArray extends ReadonlyArray { readonly raw: ReadonlyArray; @@ -723,7 +723,7 @@ interface Math { tan(x: number): number; } /** An intrinsic object that provides basic mathematics functionality and constants. */ -declare const Math: Math; +declare var Math: Math; /** Enables basic storage and retrieval of dates and times. */ interface Date { @@ -904,7 +904,7 @@ interface DateConstructor { now(): number; } -declare const Date: DateConstructor; +declare var Date: DateConstructor; interface RegExpMatchArray extends Array { index?: number; @@ -967,7 +967,7 @@ interface RegExpConstructor { lastMatch: string; } -declare const RegExp: RegExpConstructor; +declare var RegExp: RegExpConstructor; interface Error { name: string; @@ -981,7 +981,7 @@ interface ErrorConstructor { readonly prototype: Error; } -declare const Error: ErrorConstructor; +declare var Error: ErrorConstructor; interface EvalError extends Error { } @@ -992,7 +992,7 @@ interface EvalErrorConstructor { readonly prototype: EvalError; } -declare const EvalError: EvalErrorConstructor; +declare var EvalError: EvalErrorConstructor; interface RangeError extends Error { } @@ -1003,7 +1003,7 @@ interface RangeErrorConstructor { readonly prototype: RangeError; } -declare const RangeError: RangeErrorConstructor; +declare var RangeError: RangeErrorConstructor; interface ReferenceError extends Error { } @@ -1014,7 +1014,7 @@ interface ReferenceErrorConstructor { readonly prototype: ReferenceError; } -declare const ReferenceError: ReferenceErrorConstructor; +declare var ReferenceError: ReferenceErrorConstructor; interface SyntaxError extends Error { } @@ -1025,7 +1025,7 @@ interface SyntaxErrorConstructor { readonly prototype: SyntaxError; } -declare const SyntaxError: SyntaxErrorConstructor; +declare var SyntaxError: SyntaxErrorConstructor; interface TypeError extends Error { } @@ -1036,7 +1036,7 @@ interface TypeErrorConstructor { readonly prototype: TypeError; } -declare const TypeError: TypeErrorConstructor; +declare var TypeError: TypeErrorConstructor; interface URIError extends Error { } @@ -1047,7 +1047,7 @@ interface URIErrorConstructor { readonly prototype: URIError; } -declare const URIError: URIErrorConstructor; +declare var URIError: URIErrorConstructor; interface JSON { /** @@ -1076,7 +1076,7 @@ interface JSON { /** * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. */ -declare const JSON: JSON; +declare var JSON: JSON; ///////////////////////////// @@ -1365,7 +1365,7 @@ interface ArrayConstructor { readonly prototype: Array; } -declare const Array: ArrayConstructor; +declare var Array: ArrayConstructor; interface TypedPropertyDescriptor { enumerable?: boolean; @@ -1524,7 +1524,7 @@ interface ArrayBufferConstructor { new(byteLength: number): ArrayBuffer; isView(arg: any): arg is ArrayBufferView; } -declare const ArrayBuffer: ArrayBufferConstructor; +declare var ArrayBuffer: ArrayBufferConstructor; interface ArrayBufferView { /** @@ -1674,7 +1674,7 @@ interface DataView { interface DataViewConstructor { new(buffer: ArrayBufferLike, byteOffset?: number, byteLength?: number): DataView; } -declare const DataView: DataViewConstructor; +declare var DataView: DataViewConstructor; /** * A typed array of 8-bit integer values. The contents are initialized to 0. If the requested @@ -1949,7 +1949,7 @@ interface Int8ArrayConstructor { } -declare const Int8Array: Int8ArrayConstructor; +declare var Int8Array: Int8ArrayConstructor; /** * A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the @@ -2224,7 +2224,7 @@ interface Uint8ArrayConstructor { from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8Array; } -declare const Uint8Array: Uint8ArrayConstructor; +declare var Uint8Array: Uint8ArrayConstructor; /** * A typed array of 8-bit unsigned integer (clamped) values. The contents are initialized to 0. @@ -2498,7 +2498,7 @@ interface Uint8ClampedArrayConstructor { */ from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint8ClampedArray; } -declare const Uint8ClampedArray: Uint8ClampedArrayConstructor; +declare var Uint8ClampedArray: Uint8ClampedArrayConstructor; /** * A typed array of 16-bit signed integer values. The contents are initialized to 0. If the @@ -2773,7 +2773,7 @@ interface Int16ArrayConstructor { } -declare const Int16Array: Int16ArrayConstructor; +declare var Int16Array: Int16ArrayConstructor; /** * A typed array of 16-bit unsigned integer values. The contents are initialized to 0. If the @@ -3049,7 +3049,7 @@ interface Uint16ArrayConstructor { } -declare const Uint16Array: Uint16ArrayConstructor; +declare var Uint16Array: Uint16ArrayConstructor; /** * A typed array of 32-bit signed integer values. The contents are initialized to 0. If the * requested number of bytes could not be allocated an exception is raised. @@ -3323,7 +3323,7 @@ interface Int32ArrayConstructor { from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Int32Array; } -declare const Int32Array: Int32ArrayConstructor; +declare var Int32Array: Int32ArrayConstructor; /** * A typed array of 32-bit unsigned integer values. The contents are initialized to 0. If the @@ -3597,7 +3597,7 @@ interface Uint32ArrayConstructor { from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Uint32Array; } -declare const Uint32Array: Uint32ArrayConstructor; +declare var Uint32Array: Uint32ArrayConstructor; /** * A typed array of 32-bit float values. The contents are initialized to 0. If the requested number @@ -3873,7 +3873,7 @@ interface Float32ArrayConstructor { } -declare const Float32Array: Float32ArrayConstructor; +declare var Float32Array: Float32ArrayConstructor; /** * A typed array of 64-bit float values. The contents are initialized to 0. If the requested @@ -4148,7 +4148,7 @@ interface Float64ArrayConstructor { from(arrayLike: ArrayLike, mapfn: (v: T, k: number) => number, thisArg?: any): Float64Array; } -declare const Float64Array: Float64ArrayConstructor; +declare var Float64Array: Float64ArrayConstructor; ///////////////////////////// /// ECMAScript Internationalization API diff --git a/lib/lib.esnext.bigint.d.ts b/lib/lib.esnext.bigint.d.ts index ccb73bee76175..50967de98fea7 100644 --- a/lib/lib.esnext.bigint.d.ts +++ b/lib/lib.esnext.bigint.d.ts @@ -54,7 +54,7 @@ interface BigIntConstructor { asUintN(bits: number, int: bigint): bigint; } -declare const BigInt: BigIntConstructor; +declare var BigInt: BigIntConstructor; /** * A typed array of 64-bit signed integer values. The contents are initialized to 0. If the @@ -323,7 +323,7 @@ interface BigInt64ArrayConstructor { from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigInt64Array; } -declare const BigInt64Array: BigInt64ArrayConstructor; +declare var BigInt64Array: BigInt64ArrayConstructor; /** * A typed array of 64-bit unsigned integer values. The contents are initialized to 0. If the @@ -592,7 +592,7 @@ interface BigUint64ArrayConstructor { from(arrayLike: ArrayLike, mapfn: (v: U, k: number) => bigint, thisArg?: any): BigUint64Array; } -declare const BigUint64Array: BigUint64ArrayConstructor; +declare var BigUint64Array: BigUint64ArrayConstructor; interface DataView { /** @@ -626,4 +626,4 @@ interface DataView { * otherwise a little-endian value should be written. */ setBigUint64(byteOffset: number, value: bigint, littleEndian?: boolean): void; -} \ No newline at end of file +} diff --git a/lib/tsc.js b/lib/tsc.js index d0cef6fa5c933..202882d5885da 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -60,7 +60,7 @@ var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cook var ts; (function (ts) { ts.versionMajorMinor = "3.4"; - ts.version = ts.versionMajorMinor + ".0-rc"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { ts.emptyArray = []; @@ -25644,6 +25644,7 @@ var ts; return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16); }, getExpandedParameters: getExpandedParameters, + hasEffectiveRestParameter: hasEffectiveRestParameter, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; @@ -25703,6 +25704,8 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, getObjectFlags: ts.getObjectFlags, + isArrayType: isArrayType, + isTupleType: isTupleType, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -26517,7 +26520,7 @@ var ts; if (location.parent && location.parent.kind === 151) { location = location.parent; } - if (location.parent && ts.isClassElement(location.parent)) { + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240)) { location = location.parent; } break; @@ -27215,19 +27218,11 @@ var ts; return undefined; } if (moduleNotFoundError) { - if (ts.pathIsRelative(moduleReference)) { - var sourceFile_1 = ts.getSourceFileOfNode(location); - var redirects = sourceFile_1.redirectedReferences; - if (redirects) { - var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); - for (var _i = 0, _a = [".ts", ".tsx"]; _i < _a.length; _i++) { - var ext = _a[_i]; - var probePath = normalizedTargetPath + ext; - if (redirects.indexOf(probePath) >= 0) { - error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); - return undefined; - } - } + if (resolvedModule) { + var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return undefined; } } if (resolutionDiagnostic) { @@ -28165,8 +28160,8 @@ var ts; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); - var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); + var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } @@ -29791,9 +29786,6 @@ var ts; } return type_1; } - if (declaration.kind === 254) { - return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); - } if (!pushTypeResolution(symbol, 0)) { if (symbol.flags & 512) { return getTypeOfFuncClassEnumModule(symbol); @@ -29801,7 +29793,10 @@ var ts; return reportCircularityError(symbol); } var type; - if (ts.isInJSFile(declaration) && + if (declaration.kind === 254) { + type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + else if (ts.isInJSFile(declaration) && (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } @@ -31116,6 +31111,15 @@ var ts; var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); + if (symbol === globalThisSymbol) { + var varsOnly_1 = ts.createMap(); + members.forEach(function (p) { + if (!(p.flags & 418)) { + varsOnly_1.set(p.escapedName, p); + } + }); + members = varsOnly_1; + } } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32) { @@ -31414,6 +31418,9 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined; + } + function getConstraintFromIndexedAccess(type) { var objectType = getConstraintOfType(type.objectType) || type.objectType; if (objectType !== type.objectType) { var constraint = getIndexedAccessType(objectType, type.indexType, undefined, errorType); @@ -31424,19 +31431,10 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } - function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { - var rootTrueType = root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432) - ? rootTrueType - : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - return instantiateType(rootTrueConstraint, combinedMapper || mapper); - } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { - var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); - var falseConstraint = getFalseTypeFromConditionalType(type); + var trueConstraint = getInferredTrueTypeFromConditionalType(type); + var falseConstraint = type.falseType; type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; @@ -31455,9 +31453,12 @@ var ts; } return undefined; } - function getConstraintOfConditionalType(type) { + function getConstraintFromConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined; + } function getUnionConstraintOfIntersection(type, targetIsUnion) { var constraints; var hasDisjointDomainType = false; @@ -31514,7 +31515,7 @@ var ts; if (!pushTypeResolution(t, 4)) { return circularConstraintType; } - if (constraintDepth === 50) { + if (constraintDepth >= 50) { error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite); nonTerminating = true; return t.immediateBaseConstraint = noConstraintType; @@ -31576,8 +31577,11 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 16777216) { - var constraint = getConstraintOfConditionalType(t); - return constraint && getBaseConstraint(constraint); + var constraint = getConstraintFromConditionalType(t); + constraintDepth++; + var result = constraint && getBaseConstraint(constraint); + constraintDepth--; + return result; } if (t.flags & 33554432) { return getBaseConstraint(t.substitute); @@ -31646,7 +31650,7 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var props; + var propSet = ts.createMap(); var indexTypes; var isUnion = containingType.flags & 1048576; var excludeModifiers = isUnion ? 24 : 0; @@ -31661,7 +31665,10 @@ var ts; var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - props = ts.appendIfUnique(props, prop); + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } checkFlags |= (isReadonlySymbol(prop) ? 8 : 0) | (!(modifiers & 24) ? 128 : 0) | (modifiers & 16 ? 256 : 0) | @@ -31683,9 +31690,10 @@ var ts; } } } - if (!props) { + if (!propSet.size) { return undefined; } + var props = ts.arrayFrom(propSet.values()); if (props.length === 1 && !(checkFlags & 16) && !indexTypes) { return props[0]; } @@ -32078,32 +32086,23 @@ var ts; } } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type, signature.declaration) : + createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } - function createTypePredicateFromTypePredicateNode(node, func) { + function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 72) { - return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } else { return createThisTypePredicate(type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 72 && param.name.escapedText === parameter.escapedText) { - return i; - } - } - return -1; - } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3)) { @@ -32525,6 +32524,9 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { + if (substitute.flags & 3) { + return typeVariable; + } var result = createType(33554432); result.typeVariable = typeVariable; result.substitute = substitute; @@ -33410,7 +33412,10 @@ var ts; return anyType; } if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418)) { + error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); } @@ -33584,28 +33589,18 @@ var ts; var trueType = instantiateType(root.trueType, mapper); var falseType = instantiateType(root.falseType, mapper); var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); - if (conditionalTypes.has(instantiationId)) { - var result = conditionalTypes.get(instantiationId); - if (result !== undefined) { - return result; - } - var deferred = getDeferredConditionalType(root, mapper, undefined, checkType, extendsType, trueType, falseType); - conditionalTypes.set(instantiationId, deferred); - return deferred; + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; } - conditionalTypes.set(instantiationId, undefined); var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); - var cachedRecursiveResult = conditionalTypes.get(instantiationId); - if (cachedRecursiveResult) { - return cachedRecursiveResult; - } conditionalTypes.set(instantiationId, newResult); return newResult; } function getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType) { if (falseType.flags & 131072 && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { if (checkType.flags & 1 || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { - return getDefaultConstraintOfTrueBranchOfConditionalType(root, undefined, mapper); + return trueType; } else if (isIntersectionEmpty(checkType, extendsType)) { return neverType; @@ -33653,19 +33648,14 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; - if (!combinedMapper) { - result.resolvedTrueType = trueType; - result.resolvedFalseType = falseType; - } + result.trueType = trueType; + result.falseType = falseType; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); return result; } - function getTrueTypeFromConditionalType(type) { - return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); - } - function getFalseTypeFromConditionalType(type) { - return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper)); } function getInferTypeParameters(node) { var result; @@ -34456,7 +34446,11 @@ var ts; return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); } else { - return maybeVariable; + var sub = instantiateType(type.substitute, mapper); + if (sub.flags & 3 || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + return maybeVariable; + } + return sub; } } return type; @@ -34953,10 +34947,18 @@ var ts; function isSignatureAssignableTo(source, target, ignoreReturnTypes) { return compareSignaturesRelated(source, target, 0, ignoreReturnTypes, false, undefined, compareTypesAssignable) !== 0; } + function isAnySignature(s) { + return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && + s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + isTypeAny(getReturnTypeOfSignature(s)); + } function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, compareTypes) { if (source === target) { return -1; } + if (isAnySignature(target)) { + return -1; + } var targetCount = getParameterCount(target); if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0; @@ -35022,7 +35024,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -35038,7 +35040,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -35047,12 +35049,9 @@ var ts; return 0; } if (source.kind === 1) { - var targetPredicate = target; - var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); - var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); - if (sourceIndex !== targetIndex) { + if (source.parameterIndex !== target.parameterIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0; @@ -35758,8 +35757,8 @@ var ts; if (source.root.isDistributive === target.root.isDistributive) { if (result_3 = isRelatedTo(source.checkType, target.checkType, false)) { if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, false)) { - if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), false)) { - if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), false)) { + if (result_3 &= isRelatedTo(source.trueType, target.trueType, false)) { + if (result_3 &= isRelatedTo(source.falseType, target.falseType, false)) { return result_3; } } @@ -35885,8 +35884,8 @@ var ts; if (target.flags & 16777216) { if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { - if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { + result &= isRelatedTo(source.falseType, target.falseType, reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -37032,7 +37031,7 @@ var ts; } } } - function forEachMatchingParameterType(source, target, callback) { + function applyToParameterTypes(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); var sourceRestType = getEffectiveRestType(source); @@ -37053,6 +37052,17 @@ var ts; callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } + function applyToReturnTypes(source, target, callback) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind && + (sourceTypePredicate.kind === 0 || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } function createInferenceContext(typeParameters, signature, flags, compareTypes) { return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); } @@ -37249,11 +37259,11 @@ var ts; inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : emptyObjectType; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } + if (contravariant === void 0) { contravariant = false; } var symbolStack; var visited; - var contravariant = false; var bivariant = false; var propagationType; var allowComplexConstraintInference = true; @@ -37320,9 +37330,11 @@ var ts; } if (priority === inference.priority) { var candidate = propagationType || source; - if (contravariant && !bivariant && !ts.contains(inference.contraCandidates, candidate)) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); - inference.inferredType = undefined; + if (contravariant && !bivariant) { + if (!ts.contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + inference.inferredType = undefined; + } } else if (!ts.contains(inference.candidates, candidate)) { inference.candidates = ts.append(inference.candidates, candidate); @@ -37390,12 +37402,12 @@ var ts; else if (source.flags & 16777216 && target.flags & 16777216) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes(source.trueType, target.trueType); + inferFromTypes(source.falseType, target.falseType); } else if (target.flags & 16777216 && !contravariant) { - inferFromTypes(source, getTrueTypeFromConditionalType(target)); - inferFromTypes(source, getFalseTypeFromConditionalType(target)); + inferFromTypes(source, target.trueType); + inferFromTypes(source, target.falseType); } else if (target.flags & 3145728) { for (var _d = 0, _e = target.types; _d < _e.length; _d++) { @@ -37585,17 +37597,10 @@ var ts; var saveBivariant = bivariant; var kind = target.declaration ? target.declaration.kind : 0; bivariant = bivariant || kind === 156 || kind === 155 || kind === 157; - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } - var sourceTypePredicate = getTypePredicateOfSignature(source); - var targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { - inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { var targetStringIndexType = getIndexTypeOfType(target, 0); @@ -38945,7 +38950,7 @@ var ts; return type; } if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); @@ -41115,7 +41120,10 @@ var ts; return anyType; } if (leftType.symbol === globalThisSymbol) { - if (noImplicitAny) { + if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418)) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } + else if (noImplicitAny) { error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; @@ -41612,17 +41620,13 @@ var ts; var restType = getEffectiveRestType(contextualSignature); var mapper = inferenceContext && (restType && restType.flags & 262144 ? inferenceContext.nonFixingMapper : inferenceContext.mapper); var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; - forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + applyToParameterTypes(sourceSignature, signature, function (source, target) { inferTypes(context.inferences, source, target); }); if (!inferenceContext) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); - var signaturePredicate = getTypePredicateOfSignature(signature); - var contextualPredicate = getTypePredicateOfSignature(sourceSignature); - if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind && - (signaturePredicate.kind === 0 || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) { - inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8); - } + applyToReturnTypes(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target, 8); + }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } @@ -44191,13 +44195,20 @@ var ts; var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature)); if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) { var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); - var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters)); - var inferences = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); - inferTypes(inferences, strippedType, contextualType); - if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) { - mergeInferences(context.inferences, inferences); - context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); - return strippedType; + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); + applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target, 0, true); + }); + if (ts.some(inferences_2, hasInferenceCandidates)) { + applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target); + }); + if (!hasOverlappingInferences(context.inferences, inferences_2)) { + mergeInferences(context.inferences, inferences_2); + context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } } } return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context)); @@ -44485,7 +44496,8 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + var signature = getSignatureFromDeclaration(parent); + var typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) { return; } @@ -44496,12 +44508,12 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { var leadingError = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); } } else if (parameterName) { @@ -47544,8 +47556,8 @@ var ts; checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 - && symbol.declarations.length > 1 && !inAmbientContext + && symbol.declarations.length > 1 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -57336,11 +57348,14 @@ var ts; var decorators; if (node) { var parameters = node.parameters; - for (var i = 0; i < parameters.length; i++) { - var parameter = parameters[i]; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array(numParameters); } decorators[i] = parameter.decorators; } @@ -58759,8 +58774,10 @@ var ts; } var savedCapturedSuperProperties = capturedSuperProperties; var savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = ts.createUnderscoreEscapedMap(); - hasSuperElementAccess = false; + if (!isArrowFunction) { + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + } var result; if (!isArrowFunction) { var statements = []; @@ -58770,9 +58787,11 @@ var ts; var emitSuperHelpers = languageVersion >= 2 && resolver.getNodeCheckFlags(node) & (4096 | 2048); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); - substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + if (ts.hasEntries(capturedSuperProperties)) { + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } } var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); @@ -58798,8 +58817,10 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; - capturedSuperProperties = savedCapturedSuperProperties; - hasSuperElementAccess = savedHasSuperElementAccess; + if (!isArrowFunction) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + } return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -58921,11 +58942,11 @@ var ts; names.forEach(function (_, key) { var name = ts.unescapeLeadingUnderscores(key); var getterAndSetter = []; - getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + getterAndSetter.push(ts.createPropertyAssignment("get", ts.createArrowFunction(undefined, undefined, [], undefined, undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4), name), 4)))); if (hasBinding) { getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction(undefined, undefined, [ ts.createParameter(undefined, undefined, undefined, "v", undefined, undefined, undefined) - ], undefined, undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + ], undefined, undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4), name), 4), ts.createIdentifier("v"))))); } accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); }); @@ -71820,9 +71841,7 @@ var ts; function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); function getSourceFile(fileName, languageVersion, onError) { var text; try { @@ -73442,7 +73461,6 @@ var ts; if (refFile) { var redirect = getProjectReferenceRedirect(fileName); if (redirect) { - (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); fileName = redirect; redirectedPath = toPath(redirect); } @@ -74328,7 +74346,7 @@ var ts; var useOldState = canReuseOldState(referencedMap, oldState); for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var version_1 = sourceFile.version; + var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -75111,8 +75129,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_2 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -76390,6 +76408,32 @@ var ts; return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); } ts.readBuilderProgram = readBuilderProgram; + function createIncrementalCompilerHost(options, system) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker(options, undefined, system); + host.createHash = ts.maybeBind(system, system.createHash); + setGetSourceFileAsHashVersioned(host, system); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); + return host; + } + ts.createIncrementalCompilerHost = createIncrementalCompilerHost; + function createIncrementalProgram(_a) { + var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram; + host = host || createIncrementalCompilerHost(options); + createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram; + var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); }); + return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + } + function performIncrementalCompilation(input) { + var system = input.system || ts.sys; + var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + var builderProgram = createIncrementalProgram(input); + var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + if (input.afterProgramEmitAndDiagnostics) + input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; + } + ts.performIncrementalCompilation = performIncrementalCompilation; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -77207,6 +77251,14 @@ var ts; newerInputFileName: newestInputFileName }; } + else { + var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + } if (!buildInfoChecked.hasKey(project.options.configFilePath)) { buildInfoChecked.setValue(project.options.configFilePath, true); var buildInfoPath = ts.getOutputPathForBuildInfo(project.options); @@ -77238,6 +77290,16 @@ var ts; oldestOutputFileName: oldestOutputFileName }; } + function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) { + var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + if (oldestOutputFileTime < tsconfigTime) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } + } function invalidateProject(configFileName, reloadLevel) { invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } @@ -77524,6 +77586,8 @@ var ts; } } function getOldProgram(proj, parsed) { + if (options.force) + return undefined; var value = builderPrograms.getValue(proj); if (value) return value; @@ -78080,7 +78144,7 @@ var ts; return ts.sys.exit(ts.ExitStatus.Success); } // Update to pretty if host supports it - updateReportDiagnostic(); + updateReportDiagnostic(buildOptions); if (projects.length === 0) { ts.printVersion(); ts.printHelp(ts.buildOpts, "--build "); @@ -78095,8 +78159,8 @@ var ts; } // Use default createProgram var buildHost = buildOptions.watch ? - ts.createSolutionBuilderWithWatchHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createWatchStatusReporter()) : - ts.createSolutionBuilderHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty()), createReportErrorSummary(buildOptions)); + ts.createSolutionBuilderWithWatchHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createWatchStatusReporter(buildOptions)) : + ts.createSolutionBuilderHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createReportErrorSummary(buildOptions)); updateCreateProgram(buildHost); buildHost.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(program.getProgram()); }; var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); @@ -78134,29 +78198,16 @@ var ts; } function performIncrementalCompilation(config) { var options = config.options, fileNames = config.fileNames, projectReferences = config.projectReferences; - var host = ts.createCompilerHost(options); - var currentDirectory = host.getCurrentDirectory(); - var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }); enableStatistics(options); - var oldProgram = ts.readBuilderProgram(options, function (path) { return host.readFile(path); }); - var configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(config); - var programOptions = { + return ts.sys.exit(ts.performIncrementalCompilation({ rootNames: fileNames, options: options, - projectReferences: projectReferences, - host: host, configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(config), - }; - var program = ts.createProgram(programOptions); - var builderProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram(program, { - useCaseSensitiveFileNames: function () { return ts.sys.useCaseSensitiveFileNames; }, - createHash: ts.maybeBind(ts.sys, ts.sys.createHash), - writeFile: function (path, data, writeByteOrderMark) { return ts.sys.writeFile(path, data, writeByteOrderMark); } - }, oldProgram, configFileParsingDiagnostics); - var exitStatus = ts.emitFilesAndReportErrors(builderProgram, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }, createReportErrorSummary(options)); - reportStatistics(program); - return ts.sys.exit(exitStatus); + projectReferences: projectReferences, + reportDiagnostic: reportDiagnostic, + reportErrorSummary: createReportErrorSummary(options), + afterProgramEmitAndDiagnostics: function (builderProgram) { return reportStatistics(builderProgram.getProgram()); } + })); } function updateCreateProgram(host) { var compileUsingBuilder = host.createProgram; diff --git a/lib/tsserver.js b/lib/tsserver.js index 9d4b5bcf89a6f..86ff8c078910d 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -85,7 +85,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.4"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-rc"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -31321,6 +31321,7 @@ var ts; return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */); }, getExpandedParameters: getExpandedParameters, + hasEffectiveRestParameter: hasEffectiveRestParameter, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; @@ -31382,6 +31383,8 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, getObjectFlags: ts.getObjectFlags, + isArrayType: isArrayType, + isTupleType: isTupleType, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -32464,7 +32467,13 @@ var ts; // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. // } // - if (location.parent && ts.isClassElement(location.parent)) { + // class Decorators are resolved outside of the class to avoid referencing type parameters of that class. + // + // type T = number; + // declare function y(x: T): any; + // @param(1 as T) // <-- T should resolve to the type alias outside of class C + // class C {} + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) { location = location.parent; } break; @@ -33262,20 +33271,12 @@ var ts; return undefined; } if (moduleNotFoundError) { - // For relative paths, see if this was possibly a projectReference redirect - if (ts.pathIsRelative(moduleReference)) { - var sourceFile_1 = ts.getSourceFileOfNode(location); - var redirects = sourceFile_1.redirectedReferences; - if (redirects) { - var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); - for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { - var ext = _a[_i]; - var probePath = normalizedTargetPath + ext; - if (redirects.indexOf(probePath) >= 0) { - error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); - return undefined; - } - } + // See if this was possibly a projectReference redirect + if (resolvedModule) { + var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return undefined; } } if (resolutionDiagnostic) { @@ -34307,8 +34308,8 @@ var ts; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); - var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); + var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } @@ -36115,9 +36116,6 @@ var ts; } return type_1; } - if (declaration.kind === 254 /* ExportAssignment */) { - return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` @@ -36127,7 +36125,10 @@ var ts; return reportCircularityError(symbol); } var type; - if (ts.isInJSFile(declaration) && + if (declaration.kind === 254 /* ExportAssignment */) { + type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + else if (ts.isInJSFile(declaration) && (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } @@ -37652,6 +37653,15 @@ var ts; var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); + if (symbol === globalThisSymbol) { + var varsOnly_1 = ts.createMap(); + members.forEach(function (p) { + if (!(p.flags & 418 /* BlockScoped */)) { + varsOnly_1.set(p.escapedName, p); + } + }); + members = varsOnly_1; + } } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { @@ -37984,6 +37994,9 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined; + } + function getConstraintFromIndexedAccess(type) { var objectType = getConstraintOfType(type.objectType) || type.objectType; if (objectType !== type.objectType) { var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); @@ -37994,23 +38007,14 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } - function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { - var rootTrueType = root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - return instantiateType(rootTrueConstraint, combinedMapper || mapper); - } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, // in effect treating `any` like `never` rather than `unknown` in this location. - var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); - var falseConstraint = getFalseTypeFromConditionalType(type); + var trueConstraint = getInferredTrueTypeFromConditionalType(type); + var falseConstraint = type.falseType; type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; @@ -38040,9 +38044,12 @@ var ts; } return undefined; } - function getConstraintOfConditionalType(type) { + function getConstraintFromConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined; + } function getUnionConstraintOfIntersection(type, targetIsUnion) { var constraints; var hasDisjointDomainType = false; @@ -38116,7 +38123,7 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } - if (constraintDepth === 50) { + if (constraintDepth >= 50) { // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a // very high likelyhood we're dealing with an infinite generic type that perpetually generates // new type identities as we descend into it. We stop the recursion here and mark this type @@ -38182,8 +38189,11 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 16777216 /* Conditional */) { - var constraint = getConstraintOfConditionalType(t); - return constraint && getBaseConstraint(constraint); + var constraint = getConstraintFromConditionalType(t); + constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward) + var result = constraint && getBaseConstraint(constraint); + constraintDepth--; + return result; } if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -38270,7 +38280,7 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var props; + var propSet = ts.createMap(); var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; @@ -38286,7 +38296,10 @@ var ts; var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - props = ts.appendIfUnique(props, prop); + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | @@ -38308,9 +38321,10 @@ var ts; } } } - if (!props) { + if (!propSet.size) { return undefined; } + var props = ts.arrayFrom(propSet.values()); if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } @@ -38753,32 +38767,23 @@ var ts; } } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type, signature.declaration) : + createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } - function createTypePredicateFromTypePredicateNode(node, func) { + function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 72 /* Identifier */) { - return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } else { return createThisTypePredicate(type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - return -1; - } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -39255,6 +39260,9 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { + if (substitute.flags & 3 /* AnyOrUnknown */) { + return typeVariable; + } var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; @@ -40233,7 +40241,10 @@ var ts; return anyType; } if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) { + error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); } @@ -40436,24 +40447,11 @@ var ts; var trueType = instantiateType(root.trueType, mapper); var falseType = instantiateType(root.falseType, mapper); var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); - if (conditionalTypes.has(instantiationId)) { - var result = conditionalTypes.get(instantiationId); - if (result !== undefined) { - return result; - } - // Somehow the conditional type depends on itself - usually via `infer` types in the `extends` clause - // paired with a (potentially deferred) circularly constrained type. - // The conditional _must_ be deferred. - var deferred = getDeferredConditionalType(root, mapper, /*combinedMapper*/ undefined, checkType, extendsType, trueType, falseType); - conditionalTypes.set(instantiationId, deferred); - return deferred; + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; } - conditionalTypes.set(instantiationId, undefined); var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); - var cachedRecursiveResult = conditionalTypes.get(instantiationId); - if (cachedRecursiveResult) { - return cachedRecursiveResult; - } conditionalTypes.set(instantiationId, newResult); return newResult; } @@ -40461,7 +40459,7 @@ var ts; // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true - return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + return trueType; } else if (isIntersectionEmpty(checkType, extendsType)) { // Always false return neverType; @@ -40472,7 +40470,7 @@ var ts; return neverType; } else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false - return falseType; // TODO: Intersect negated `extends` type here + return falseType; } } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); @@ -40525,19 +40523,14 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; - if (!combinedMapper) { - result.resolvedTrueType = trueType; - result.resolvedFalseType = falseType; - } + result.trueType = trueType; + result.falseType = falseType; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } - function getTrueTypeFromConditionalType(type) { - return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); - } - function getFalseTypeFromConditionalType(type) { - return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper)); } function getInferTypeParameters(node) { var result; @@ -41398,7 +41391,11 @@ var ts; return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); } else { - return maybeVariable; + var sub = instantiateType(type.substitute, mapper); + if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + return maybeVariable; + } + return sub; } } return type; @@ -41955,6 +41952,14 @@ var ts; return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } + /** + * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` + */ + function isAnySignature(s) { + return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && + s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + isTypeAny(getReturnTypeOfSignature(s)); + } /** * See signatureRelatedTo, compareSignaturesIdentical */ @@ -41963,6 +41968,9 @@ var ts; if (source === target) { return -1 /* True */; } + if (isAnySignature(target)) { + return -1 /* True */; + } var targetCount = getParameterCount(target); if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; @@ -42040,7 +42048,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -42059,7 +42067,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -42068,12 +42076,9 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var targetPredicate = target; - var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); - var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); - if (sourceIndex !== targetIndex) { + if (source.parameterIndex !== target.parameterIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -42881,8 +42886,8 @@ var ts; if (source.root.isDistributive === target.root.isDistributive) { if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { return result_3; } } @@ -43031,8 +43036,8 @@ var ts; // and Y1 is related to Y2. if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { - if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { + result &= isRelatedTo(source.falseType, target.falseType, reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -44357,7 +44362,7 @@ var ts; } } } - function forEachMatchingParameterType(source, target, callback) { + function applyToParameterTypes(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); var sourceRestType = getEffectiveRestType(source); @@ -44378,6 +44383,17 @@ var ts; callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } + function applyToReturnTypes(source, target, callback) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind && + (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } function createInferenceContext(typeParameters, signature, flags, compareTypes) { return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); } @@ -44592,11 +44608,11 @@ var ts; inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : emptyObjectType; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } + if (contravariant === void 0) { contravariant = false; } var symbolStack; var visited; - var contravariant = false; var bivariant = false; var propagationType; var allowComplexConstraintInference = true; @@ -44688,9 +44704,11 @@ var ts; var candidate = propagationType || source; // We make contravariant inferences only if we are in a pure contravariant position, // i.e. only if we have not descended into a bivariant position. - if (contravariant && !bivariant && !ts.contains(inference.contraCandidates, candidate)) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); - inference.inferredType = undefined; + if (contravariant && !bivariant) { + if (!ts.contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + inference.inferredType = undefined; + } } else if (!ts.contains(inference.candidates, candidate)) { inference.candidates = ts.append(inference.candidates, candidate); @@ -44762,12 +44780,12 @@ var ts; else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes(source.trueType, target.trueType); + inferFromTypes(source.falseType, target.falseType); } else if (target.flags & 16777216 /* Conditional */ && !contravariant) { - inferFromTypes(source, getTrueTypeFromConditionalType(target)); - inferFromTypes(source, getFalseTypeFromConditionalType(target)); + inferFromTypes(source, target.trueType); + inferFromTypes(source, target.falseType); } else if (target.flags & 3145728 /* UnionOrIntersection */) { for (var _d = 0, _e = target.types; _d < _e.length; _d++) { @@ -44991,17 +45009,10 @@ var ts; var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; // Once we descend into a bivariant signature we remain bivariant for all nested inferences bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } - var sourceTypePredicate = getTypePredicateOfSignature(source); - var targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { - inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); @@ -46549,7 +46560,7 @@ var ts; return type; } if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); @@ -49203,7 +49214,10 @@ var ts; return anyType; } if (leftType.symbol === globalThisSymbol) { - if (noImplicitAny) { + if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } + else if (noImplicitAny) { error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; @@ -49782,18 +49796,14 @@ var ts; var restType = getEffectiveRestType(contextualSignature); var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; - forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + applyToParameterTypes(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, source, target); }); if (!inferenceContext) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); - var signaturePredicate = getTypePredicateOfSignature(signature); - var contextualPredicate = getTypePredicateOfSignature(sourceSignature); - if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind && - (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) { - inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */); - } + applyToReturnTypes(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target, 8 /* ReturnType */); + }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } @@ -52817,23 +52827,30 @@ var ts; // potentially add inferred type parameters to the outer function return type. var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature)); if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) { - // Instantiate the expression type with its own type parameters as type arguments. This - // ensures that the type parameters are not erased to type any during type inference such - // that they can be inferred as actual types. + // Instantiate the signature with its own type parameters as type arguments, possibly + // renaming the type parameters to ensure they have unique names. var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); - var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters)); - // Infer from the stripped expression type to the contextual type starting with an empty - // set of inference candidates. - var inferences = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); - inferTypes(inferences, strippedType, contextualType); - // If we produced some inference candidates and if the type parameters for which we produced - // candidates do not already have existing inferences, we adopt the new inference candidates and - // add the type parameters of the expression type to the set of inferred type parameters for - // the outer function return type. - if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) { - mergeInferences(context.inferences, inferences); - context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); - return strippedType; + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + // Infer from the parameters of the instantiated signature to the parameters of the + // contextual signature starting with an empty set of inference candidates. + var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); + applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true); + }); + if (ts.some(inferences_2, hasInferenceCandidates)) { + // We have inference candidates, indicating that one or more type parameters are referenced + // in the parameter types of the contextual signature. Now also infer from the return type. + applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target); + }); + // If the type parameters for which we produced candidates do not have any inferences yet, + // we adopt the new inference candidates and add the type parameters of the expression type + // to the set of inferred type parameters for the outer function return type. + if (!hasOverlappingInferences(context.inferences, inferences_2)) { + mergeInferences(context.inferences, inferences_2); + context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } } } return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context)); @@ -53156,7 +53173,8 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + var signature = getSignatureFromDeclaration(parent); + var typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) { return; } @@ -53167,12 +53185,12 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -56830,8 +56848,8 @@ var ts; var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 && !inAmbientContext + && symbol.declarations.length > 1 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -68343,11 +68361,14 @@ var ts; var decorators; if (node) { var parameters = node.parameters; - for (var i = 0; i < parameters.length; i++) { - var parameter = parameters[i]; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array(numParameters); } decorators[i] = parameter.decorators; } @@ -70477,8 +70498,10 @@ var ts; } var savedCapturedSuperProperties = capturedSuperProperties; var savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = ts.createUnderscoreEscapedMap(); - hasSuperElementAccess = false; + if (!isArrowFunction) { + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + } var result; if (!isArrowFunction) { var statements = []; @@ -70490,9 +70513,11 @@ var ts; var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); - substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + if (ts.hasEntries(capturedSuperProperties)) { + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70519,8 +70544,10 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; - capturedSuperProperties = savedCapturedSuperProperties; - hasSuperElementAccess = savedHasSuperElementAccess; + if (!isArrowFunction) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + } return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -70673,7 +70700,7 @@ var ts; /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */)))); if (hasBinding) { getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( /* modifiers */ undefined, @@ -70688,7 +70715,7 @@ var ts; /* initializer */ undefined) ], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v"))))); } accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); }); @@ -87733,11 +87760,7 @@ var ts; function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); function getSourceFile(fileName, languageVersion, onError) { var text; try { @@ -89608,7 +89631,6 @@ var ts; if (refFile) { var redirect = getProjectReferenceRedirect(fileName); if (redirect) { - (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); fileName = redirect; // Once we start redirecting to a file, we can potentially come back to it // via a back-reference from another file in the .d.ts folder. If that happens we'll @@ -90600,7 +90622,7 @@ var ts; // Create the reference map, and set the file infos for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var version_1 = sourceFile.version; + var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -91609,8 +91631,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_2 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -93071,6 +93093,32 @@ var ts; return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); } ts.readBuilderProgram = readBuilderProgram; + function createIncrementalCompilerHost(options, system) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); + host.createHash = ts.maybeBind(system, system.createHash); + setGetSourceFileAsHashVersioned(host, system); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); + return host; + } + ts.createIncrementalCompilerHost = createIncrementalCompilerHost; + function createIncrementalProgram(_a) { + var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram; + host = host || createIncrementalCompilerHost(options); + createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram; + var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); }); + return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + } + function performIncrementalCompilation(input) { + var system = input.system || ts.sys; + var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + var builderProgram = createIncrementalProgram(input); + var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + if (input.afterProgramEmitAndDiagnostics) + input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; + } + ts.performIncrementalCompilation = performIncrementalCompilation; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -93988,6 +94036,16 @@ var ts; newerInputFileName: newestInputFileName }; } + else { + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + } if (!buildInfoChecked.hasKey(project.options.configFilePath)) { buildInfoChecked.setValue(project.options.configFilePath, true); var buildInfoPath = ts.getOutputPathForBuildInfo(project.options); @@ -94020,6 +94078,17 @@ var ts; oldestOutputFileName: oldestOutputFileName }; } + function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) { + // Check tsconfig time + var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + if (oldestOutputFileTime < tsconfigTime) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } + } function invalidateProject(configFileName, reloadLevel) { invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } @@ -94330,6 +94399,8 @@ var ts; } } function getOldProgram(proj, parsed) { + if (options.force) + return undefined; var value = builderPrograms.getValue(proj); if (value) return value; @@ -98485,6 +98556,7 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -98530,7 +98602,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression; if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. @@ -98561,7 +98633,7 @@ var ts; } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); - for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; if (!entryNames.has(keywordEntry.name)) { entries.push(keywordEntry); @@ -99128,7 +99200,22 @@ var ts; var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { + kind: 0 /* Data */, + symbols: symbols, + completionKind: completionKind, + isInSnippetScope: isInSnippetScope, + propertyAccessToConvert: propertyAccessToConvert, + isNewIdentifierLocation: isNewIdentifierLocation, + location: location, + keywordFilters: keywordFilters, + literals: literals, + symbolToOriginInfoMap: symbolToOriginInfoMap, + recommendedCompletion: recommendedCompletion, + previousToken: previousToken, + isJsxInitializer: isJsxInitializer, + insideJsDocTagTypeExpression: insideJsDocTagTypeExpression + }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 304 /* JSDocParameterTag */: @@ -99175,7 +99262,9 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + if (!isTypeLocation && + symbol.declarations && + symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -100098,7 +100187,15 @@ var ts; } return res; }); - function getKeywordCompletions(keywordFilter) { + function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { + if (!filterOutTsOnlyKeywords) + return getTypescriptKeywordCompletions(keywordFilter); + var index = keywordFilter + 6 /* Last */ + 1; + return _keywordCompletions[index] || + (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter) + .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); })); + } + function getTypescriptKeywordCompletions(keywordFilter) { return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { var kind = ts.stringToToken(entry.name); switch (keywordFilter) { @@ -100122,6 +100219,39 @@ var ts; } })); } + function isTypeScriptOnlyKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 120 /* AnyKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 145 /* GlobalKeyword */: + case 109 /* ImplementsKeyword */: + case 127 /* InferKeyword */: + case 110 /* InterfaceKeyword */: + case 128 /* IsKeyword */: + case 129 /* KeyOfKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 132 /* NeverKeyword */: + case 135 /* NumberKeyword */: + case 136 /* ObjectKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + case 138 /* StringKeyword */: + case 139 /* SymbolKeyword */: + case 140 /* TypeKeyword */: + case 142 /* UniqueKeyword */: + case 143 /* UnknownKeyword */: + return true; + default: + return false; + } + } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { return kind === 133 /* ReadonlyKeyword */; } @@ -101899,23 +102029,26 @@ var ts; } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); - } - else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); - } - } + getReferencesInContainerOrFiles(symbol, state, search); } return result; } + function getReferencesInContainerOrFiles(symbol, state, search) { + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } function getSpecialSearchKind(node) { switch (node.kind) { case 124 /* ConstructorKeyword */: @@ -101967,9 +102100,7 @@ var ts; * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { - function State(sourceFiles, sourceFilesSet, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.sourceFilesSet = sourceFilesSet; this.specialSearchKind = specialSearchKind; @@ -102523,6 +102654,7 @@ var ts; var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); if (classExtending) { findSuperConstructorAccesses(classExtending, pusher()); + findInheritedConstructorReferences(classExtending, state); } } } @@ -102555,33 +102687,41 @@ var ts; * Reference the constructor and all calls to `new this()`. */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); - addNode(ctrKeyword); - } - classSymbol.exports.forEach(function (member) { - var decl = member.valueDeclaration; - if (decl && decl.kind === 156 /* MethodDeclaration */) { - var body = decl.body; - if (body) { - forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { - if (ts.isNewExpressionTarget(thisKeyword)) { - addNode(thisKeyword); - } - }); - } + var constructorSymbol = getClassConstructorSymbol(classSymbol); + if (constructorSymbol) { + for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); } - }); + } + if (classSymbol.exports) { + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + } + function getClassConstructorSymbol(classSymbol) { + return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */); } /** Find references to `super` in the constructor of an extending class. */ - function findSuperConstructorAccesses(cls, addNode) { - var ctr = cls.symbol.members.get("__constructor" /* Constructor */); - if (!ctr) { + function findSuperConstructorAccesses(classDeclaration, addNode) { + var constructor = getClassConstructorSymbol(classDeclaration.symbol); + if (!constructor) { return; } - for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; @@ -102594,6 +102734,16 @@ var ts; } } } + function hasOwnConstructor(classDeclaration) { + return !!getClassConstructorSymbol(classDeclaration.symbol); + } + function findInheritedConstructorReferences(classDeclaration, state) { + if (hasOwnConstructor(classDeclaration)) + return; + var classSymbol = classDeclaration.symbol; + var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined); + getReferencesInContainerOrFiles(classSymbol, state, search); + } function addImplementationReferences(refNode, addReference, state) { // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { @@ -106594,7 +106744,7 @@ var ts; return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - var isVariadic = candidateSignature.hasRestParameter; + var isVariadic = checker.hasEffectiveRestParameter(candidateSignature); var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { @@ -119264,7 +119414,7 @@ var ts; var checker = program.getTypeChecker(); var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); }); var groupedReferences = groupReferences(references); - if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) { + if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) { groupedReferences.valid = false; } return groupedReferences; @@ -119280,7 +119430,18 @@ var ts; groupedReferences.valid = false; continue; } - if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) { + /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. + Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: + class A { foo(a: number, b: number) { return a + b; } } + class B { foo(c: number, d: number) { return c + d; } } + declare const ab: A | B; + ab.foo(1, 2); + Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`. + When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol. + So we need to add a special case for this because when calling a constructor of a class through one of its subclasses, + the symbols are going to be different. + */ + if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) { var decl = entryToDeclaration(entry); if (decl) { groupedReferences.declarations.push(decl); @@ -119404,6 +119565,9 @@ var ts; function getFunctionDeclarationAtPosition(file, startPosition, checker) { var node = ts.getTouchingToken(file, startPosition); var functionDeclaration = ts.getContainingFunction(node); + // don't offer refactor on top-level JSDoc + if (isTopLevelJSDoc(node)) + return undefined; if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && ts.rangeContainsRange(functionDeclaration, node) @@ -119411,19 +119575,33 @@ var ts; return functionDeclaration; return undefined; } + function isTopLevelJSDoc(node) { + var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode); + if (containingJSDoc) { + var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); }); + return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; + } function isValidFunctionDeclaration(functionDeclaration, checker) { - if (!isValidParameterNodeArray(functionDeclaration.parameters)) + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { case 239 /* FunctionDeclaration */: case 156 /* MethodDeclaration */: - return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.name + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); case 157 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { - return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.body + && !!functionDeclaration.parent.name + && !checker.isImplementationOfOverload(functionDeclaration); } else { - return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return isValidVariableDeclaration(functionDeclaration.parent.parent) + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); } case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: @@ -119431,11 +119609,17 @@ var ts; } return false; } - function isValidParameterNodeArray(parameters) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration); + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength + && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); }); } - function isValidParameterDeclaration(paramDeclaration) { - return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name); + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -119455,13 +119639,22 @@ var ts; } return parameters; } + function createPropertyOrShorthandAssignment(name, initializer) { + if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) { + return ts.createShorthandPropertyAssignment(name); + } + return ts.createPropertyAssignment(name, initializer); + } function createNewArgument(functionDeclaration, functionArguments) { var parameters = getRefactorableParameters(functionDeclaration.parameters); var hasRestParameter = ts.isRestParameter(ts.last(parameters)); var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments; var properties = ts.map(nonRestArguments, function (arg, i) { - var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg); - ts.suppressLeadingAndTrailingTrivia(property.initializer); + var parameterName = getParameterName(parameters[i]); + var property = createPropertyOrShorthandAssignment(parameterName, arg); + ts.suppressLeadingAndTrailingTrivia(property.name); + if (ts.isPropertyAssignment(property)) + ts.suppressLeadingAndTrailingTrivia(property.initializer); copyComments(arg, property); return property; }); @@ -119474,14 +119667,14 @@ var ts; return objectLiteral; } function createNewParameters(functionDeclaration, program, host) { + var checker = program.getTypeChecker(); var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration); var objectParameterName = ts.createObjectBindingPattern(bindingElements); var objectParameterType = createParameterTypeNode(refactorableParameters); - var checker = program.getTypeChecker(); var objectInitializer; // If every parameter in the original function was optional, add an empty object initializer to the new object parameter - if (ts.every(refactorableParameters, checker.isOptionalParameter)) { + if (ts.every(refactorableParameters, isOptionalParameter)) { objectInitializer = ts.createObjectLiteral(); } var objectParameter = ts.createParameter( @@ -119505,6 +119698,16 @@ var ts; return ts.createNodeArray([newThisParameter, objectParameter]); } return ts.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + var element = ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); + ts.suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } function createParameterTypeNode(parameters) { var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration); var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */); @@ -119516,7 +119719,7 @@ var ts; parameterType = getTypeNode(parameterDeclaration); } var propertySignature = ts.createPropertySignature( - /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, + /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); copyComments(parameterDeclaration.name, propertySignature.name); @@ -119526,20 +119729,16 @@ var ts; return propertySignature; } function getTypeNode(node) { - var checker = program.getTypeChecker(); var type = checker.getTypeAtLocation(node); return ts.getTypeNodeIfAccessible(type, node, program, host); } - } - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - var element = ts.createBindingElement( - /*dotDotDotToken*/ undefined, - /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); - ts.suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + function isOptionalParameter(parameterDeclaration) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); } - return element; } function copyComments(sourceNode, targetNode) { var sourceFile = sourceNode.getSourceFile(); @@ -120505,7 +120704,7 @@ var ts; function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { - throw new Error("Could not find file: '" + fileName + "'."); + throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + "."); } return sourceFile; } @@ -128990,16 +129189,31 @@ var ts; msg += "\n" + server.indent(err.stack); } } - if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { - try { - var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - if (scriptInfo) { - var text = ts.getSnapshotText(scriptInfo.getSnapshot()); - msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + if (this.logger.hasLevel(server.LogLevel.verbose)) { + if (fileRequest) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } } + catch (_b) { } // tslint:disable-line no-empty + } + if (err.message && err.message.indexOf("Could not find sourceFile:") !== -1) { + msg += "\n\nProjects::\n"; + var counter_1 = 0; + var addProjectInfo = function (project) { + msg += "\nProject '" + project.projectName + "' (" + server.ProjectKind[project.projectKind] + ") " + counter_1 + "\n"; + msg += project.filesToString(/*writeProjectFileNames*/ true); + msg += "\n-----------------------------------------------\n"; + counter_1++; + }; + this.projectService.externalProjects.forEach(addProjectInfo); + this.projectService.configuredProjects.forEach(addProjectInfo); + this.projectService.inferredProjects.forEach(addProjectInfo); } - catch (_b) { } // tslint:disable-line no-empty } this.logger.msg(msg, server.Msg.Err); }; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 59ae825a8dc80..8208cdba2ab46 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -2382,8 +2382,8 @@ declare namespace ts { root: ConditionalRoot; checkType: Type; extendsType: Type; - resolvedTrueType?: Type; - resolvedFalseType?: Type; + trueType: Type; + falseType: Type; } interface SubstitutionType extends InstantiableType { typeVariable: TypeVariable; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index de2a5b55d121c..79f6dcec55b08 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -84,7 +84,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.4"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-rc"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -31320,6 +31320,7 @@ var ts; return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */); }, getExpandedParameters: getExpandedParameters, + hasEffectiveRestParameter: hasEffectiveRestParameter, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; @@ -31381,6 +31382,8 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, getObjectFlags: ts.getObjectFlags, + isArrayType: isArrayType, + isTupleType: isTupleType, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -32463,7 +32466,13 @@ var ts; // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. // } // - if (location.parent && ts.isClassElement(location.parent)) { + // class Decorators are resolved outside of the class to avoid referencing type parameters of that class. + // + // type T = number; + // declare function y(x: T): any; + // @param(1 as T) // <-- T should resolve to the type alias outside of class C + // class C {} + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) { location = location.parent; } break; @@ -33261,20 +33270,12 @@ var ts; return undefined; } if (moduleNotFoundError) { - // For relative paths, see if this was possibly a projectReference redirect - if (ts.pathIsRelative(moduleReference)) { - var sourceFile_1 = ts.getSourceFileOfNode(location); - var redirects = sourceFile_1.redirectedReferences; - if (redirects) { - var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); - for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { - var ext = _a[_i]; - var probePath = normalizedTargetPath + ext; - if (redirects.indexOf(probePath) >= 0) { - error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); - return undefined; - } - } + // See if this was possibly a projectReference redirect + if (resolvedModule) { + var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return undefined; } } if (resolutionDiagnostic) { @@ -34306,8 +34307,8 @@ var ts; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); - var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); + var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } @@ -36114,9 +36115,6 @@ var ts; } return type_1; } - if (declaration.kind === 254 /* ExportAssignment */) { - return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` @@ -36126,7 +36124,10 @@ var ts; return reportCircularityError(symbol); } var type; - if (ts.isInJSFile(declaration) && + if (declaration.kind === 254 /* ExportAssignment */) { + type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + else if (ts.isInJSFile(declaration) && (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } @@ -37651,6 +37652,15 @@ var ts; var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); + if (symbol === globalThisSymbol) { + var varsOnly_1 = ts.createMap(); + members.forEach(function (p) { + if (!(p.flags & 418 /* BlockScoped */)) { + varsOnly_1.set(p.escapedName, p); + } + }); + members = varsOnly_1; + } } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { @@ -37983,6 +37993,9 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined; + } + function getConstraintFromIndexedAccess(type) { var objectType = getConstraintOfType(type.objectType) || type.objectType; if (objectType !== type.objectType) { var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); @@ -37993,23 +38006,14 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } - function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { - var rootTrueType = root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - return instantiateType(rootTrueConstraint, combinedMapper || mapper); - } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, // in effect treating `any` like `never` rather than `unknown` in this location. - var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); - var falseConstraint = getFalseTypeFromConditionalType(type); + var trueConstraint = getInferredTrueTypeFromConditionalType(type); + var falseConstraint = type.falseType; type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; @@ -38039,9 +38043,12 @@ var ts; } return undefined; } - function getConstraintOfConditionalType(type) { + function getConstraintFromConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined; + } function getUnionConstraintOfIntersection(type, targetIsUnion) { var constraints; var hasDisjointDomainType = false; @@ -38115,7 +38122,7 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } - if (constraintDepth === 50) { + if (constraintDepth >= 50) { // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a // very high likelyhood we're dealing with an infinite generic type that perpetually generates // new type identities as we descend into it. We stop the recursion here and mark this type @@ -38181,8 +38188,11 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 16777216 /* Conditional */) { - var constraint = getConstraintOfConditionalType(t); - return constraint && getBaseConstraint(constraint); + var constraint = getConstraintFromConditionalType(t); + constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward) + var result = constraint && getBaseConstraint(constraint); + constraintDepth--; + return result; } if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -38269,7 +38279,7 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var props; + var propSet = ts.createMap(); var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; @@ -38285,7 +38295,10 @@ var ts; var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - props = ts.appendIfUnique(props, prop); + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | @@ -38307,9 +38320,10 @@ var ts; } } } - if (!props) { + if (!propSet.size) { return undefined; } + var props = ts.arrayFrom(propSet.values()); if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } @@ -38752,32 +38766,23 @@ var ts; } } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type, signature.declaration) : + createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } - function createTypePredicateFromTypePredicateNode(node, func) { + function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 72 /* Identifier */) { - return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } else { return createThisTypePredicate(type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - return -1; - } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -39254,6 +39259,9 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { + if (substitute.flags & 3 /* AnyOrUnknown */) { + return typeVariable; + } var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; @@ -40232,7 +40240,10 @@ var ts; return anyType; } if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) { + error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); } @@ -40435,24 +40446,11 @@ var ts; var trueType = instantiateType(root.trueType, mapper); var falseType = instantiateType(root.falseType, mapper); var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); - if (conditionalTypes.has(instantiationId)) { - var result = conditionalTypes.get(instantiationId); - if (result !== undefined) { - return result; - } - // Somehow the conditional type depends on itself - usually via `infer` types in the `extends` clause - // paired with a (potentially deferred) circularly constrained type. - // The conditional _must_ be deferred. - var deferred = getDeferredConditionalType(root, mapper, /*combinedMapper*/ undefined, checkType, extendsType, trueType, falseType); - conditionalTypes.set(instantiationId, deferred); - return deferred; + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; } - conditionalTypes.set(instantiationId, undefined); var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); - var cachedRecursiveResult = conditionalTypes.get(instantiationId); - if (cachedRecursiveResult) { - return cachedRecursiveResult; - } conditionalTypes.set(instantiationId, newResult); return newResult; } @@ -40460,7 +40458,7 @@ var ts; // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true - return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + return trueType; } else if (isIntersectionEmpty(checkType, extendsType)) { // Always false return neverType; @@ -40471,7 +40469,7 @@ var ts; return neverType; } else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false - return falseType; // TODO: Intersect negated `extends` type here + return falseType; } } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); @@ -40524,19 +40522,14 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; - if (!combinedMapper) { - result.resolvedTrueType = trueType; - result.resolvedFalseType = falseType; - } + result.trueType = trueType; + result.falseType = falseType; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } - function getTrueTypeFromConditionalType(type) { - return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); - } - function getFalseTypeFromConditionalType(type) { - return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper)); } function getInferTypeParameters(node) { var result; @@ -41397,7 +41390,11 @@ var ts; return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); } else { - return maybeVariable; + var sub = instantiateType(type.substitute, mapper); + if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + return maybeVariable; + } + return sub; } } return type; @@ -41954,6 +41951,14 @@ var ts; return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } + /** + * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` + */ + function isAnySignature(s) { + return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && + s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + isTypeAny(getReturnTypeOfSignature(s)); + } /** * See signatureRelatedTo, compareSignaturesIdentical */ @@ -41962,6 +41967,9 @@ var ts; if (source === target) { return -1 /* True */; } + if (isAnySignature(target)) { + return -1 /* True */; + } var targetCount = getParameterCount(target); if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; @@ -42039,7 +42047,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -42058,7 +42066,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -42067,12 +42075,9 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var targetPredicate = target; - var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); - var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); - if (sourceIndex !== targetIndex) { + if (source.parameterIndex !== target.parameterIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -42880,8 +42885,8 @@ var ts; if (source.root.isDistributive === target.root.isDistributive) { if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { return result_3; } } @@ -43030,8 +43035,8 @@ var ts; // and Y1 is related to Y2. if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { - if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { + result &= isRelatedTo(source.falseType, target.falseType, reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -44356,7 +44361,7 @@ var ts; } } } - function forEachMatchingParameterType(source, target, callback) { + function applyToParameterTypes(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); var sourceRestType = getEffectiveRestType(source); @@ -44377,6 +44382,17 @@ var ts; callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } + function applyToReturnTypes(source, target, callback) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind && + (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } function createInferenceContext(typeParameters, signature, flags, compareTypes) { return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); } @@ -44591,11 +44607,11 @@ var ts; inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : emptyObjectType; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } + if (contravariant === void 0) { contravariant = false; } var symbolStack; var visited; - var contravariant = false; var bivariant = false; var propagationType; var allowComplexConstraintInference = true; @@ -44687,9 +44703,11 @@ var ts; var candidate = propagationType || source; // We make contravariant inferences only if we are in a pure contravariant position, // i.e. only if we have not descended into a bivariant position. - if (contravariant && !bivariant && !ts.contains(inference.contraCandidates, candidate)) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); - inference.inferredType = undefined; + if (contravariant && !bivariant) { + if (!ts.contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + inference.inferredType = undefined; + } } else if (!ts.contains(inference.candidates, candidate)) { inference.candidates = ts.append(inference.candidates, candidate); @@ -44761,12 +44779,12 @@ var ts; else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes(source.trueType, target.trueType); + inferFromTypes(source.falseType, target.falseType); } else if (target.flags & 16777216 /* Conditional */ && !contravariant) { - inferFromTypes(source, getTrueTypeFromConditionalType(target)); - inferFromTypes(source, getFalseTypeFromConditionalType(target)); + inferFromTypes(source, target.trueType); + inferFromTypes(source, target.falseType); } else if (target.flags & 3145728 /* UnionOrIntersection */) { for (var _d = 0, _e = target.types; _d < _e.length; _d++) { @@ -44990,17 +45008,10 @@ var ts; var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; // Once we descend into a bivariant signature we remain bivariant for all nested inferences bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } - var sourceTypePredicate = getTypePredicateOfSignature(source); - var targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { - inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); @@ -46548,7 +46559,7 @@ var ts; return type; } if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); @@ -49202,7 +49213,10 @@ var ts; return anyType; } if (leftType.symbol === globalThisSymbol) { - if (noImplicitAny) { + if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } + else if (noImplicitAny) { error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; @@ -49781,18 +49795,14 @@ var ts; var restType = getEffectiveRestType(contextualSignature); var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; - forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + applyToParameterTypes(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, source, target); }); if (!inferenceContext) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); - var signaturePredicate = getTypePredicateOfSignature(signature); - var contextualPredicate = getTypePredicateOfSignature(sourceSignature); - if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind && - (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) { - inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */); - } + applyToReturnTypes(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target, 8 /* ReturnType */); + }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } @@ -52816,23 +52826,30 @@ var ts; // potentially add inferred type parameters to the outer function return type. var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature)); if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) { - // Instantiate the expression type with its own type parameters as type arguments. This - // ensures that the type parameters are not erased to type any during type inference such - // that they can be inferred as actual types. + // Instantiate the signature with its own type parameters as type arguments, possibly + // renaming the type parameters to ensure they have unique names. var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); - var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters)); - // Infer from the stripped expression type to the contextual type starting with an empty - // set of inference candidates. - var inferences = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); - inferTypes(inferences, strippedType, contextualType); - // If we produced some inference candidates and if the type parameters for which we produced - // candidates do not already have existing inferences, we adopt the new inference candidates and - // add the type parameters of the expression type to the set of inferred type parameters for - // the outer function return type. - if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) { - mergeInferences(context.inferences, inferences); - context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); - return strippedType; + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + // Infer from the parameters of the instantiated signature to the parameters of the + // contextual signature starting with an empty set of inference candidates. + var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); + applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true); + }); + if (ts.some(inferences_2, hasInferenceCandidates)) { + // We have inference candidates, indicating that one or more type parameters are referenced + // in the parameter types of the contextual signature. Now also infer from the return type. + applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target); + }); + // If the type parameters for which we produced candidates do not have any inferences yet, + // we adopt the new inference candidates and add the type parameters of the expression type + // to the set of inferred type parameters for the outer function return type. + if (!hasOverlappingInferences(context.inferences, inferences_2)) { + mergeInferences(context.inferences, inferences_2); + context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } } } return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context)); @@ -53155,7 +53172,8 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + var signature = getSignatureFromDeclaration(parent); + var typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) { return; } @@ -53166,12 +53184,12 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -56829,8 +56847,8 @@ var ts; var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 && !inAmbientContext + && symbol.declarations.length > 1 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -68342,11 +68360,14 @@ var ts; var decorators; if (node) { var parameters = node.parameters; - for (var i = 0; i < parameters.length; i++) { - var parameter = parameters[i]; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array(numParameters); } decorators[i] = parameter.decorators; } @@ -70476,8 +70497,10 @@ var ts; } var savedCapturedSuperProperties = capturedSuperProperties; var savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = ts.createUnderscoreEscapedMap(); - hasSuperElementAccess = false; + if (!isArrowFunction) { + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + } var result; if (!isArrowFunction) { var statements = []; @@ -70489,9 +70512,11 @@ var ts; var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); - substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + if (ts.hasEntries(capturedSuperProperties)) { + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70518,8 +70543,10 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; - capturedSuperProperties = savedCapturedSuperProperties; - hasSuperElementAccess = savedHasSuperElementAccess; + if (!isArrowFunction) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + } return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -70672,7 +70699,7 @@ var ts; /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */)))); if (hasBinding) { getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( /* modifiers */ undefined, @@ -70687,7 +70714,7 @@ var ts; /* initializer */ undefined) ], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v"))))); } accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); }); @@ -87732,11 +87759,7 @@ var ts; function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); function getSourceFile(fileName, languageVersion, onError) { var text; try { @@ -89607,7 +89630,6 @@ var ts; if (refFile) { var redirect = getProjectReferenceRedirect(fileName); if (redirect) { - (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); fileName = redirect; // Once we start redirecting to a file, we can potentially come back to it // via a back-reference from another file in the .d.ts folder. If that happens we'll @@ -90599,7 +90621,7 @@ var ts; // Create the reference map, and set the file infos for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var version_1 = sourceFile.version; + var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -91608,8 +91630,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_2 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -93070,6 +93092,32 @@ var ts; return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); } ts.readBuilderProgram = readBuilderProgram; + function createIncrementalCompilerHost(options, system) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); + host.createHash = ts.maybeBind(system, system.createHash); + setGetSourceFileAsHashVersioned(host, system); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); + return host; + } + ts.createIncrementalCompilerHost = createIncrementalCompilerHost; + function createIncrementalProgram(_a) { + var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram; + host = host || createIncrementalCompilerHost(options); + createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram; + var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); }); + return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + } + function performIncrementalCompilation(input) { + var system = input.system || ts.sys; + var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + var builderProgram = createIncrementalProgram(input); + var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + if (input.afterProgramEmitAndDiagnostics) + input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; + } + ts.performIncrementalCompilation = performIncrementalCompilation; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -93987,6 +94035,16 @@ var ts; newerInputFileName: newestInputFileName }; } + else { + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + } if (!buildInfoChecked.hasKey(project.options.configFilePath)) { buildInfoChecked.setValue(project.options.configFilePath, true); var buildInfoPath = ts.getOutputPathForBuildInfo(project.options); @@ -94019,6 +94077,17 @@ var ts; oldestOutputFileName: oldestOutputFileName }; } + function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) { + // Check tsconfig time + var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + if (oldestOutputFileTime < tsconfigTime) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } + } function invalidateProject(configFileName, reloadLevel) { invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } @@ -94329,6 +94398,8 @@ var ts; } } function getOldProgram(proj, parsed) { + if (options.force) + return undefined; var value = builderPrograms.getValue(proj); if (value) return value; @@ -98824,6 +98895,7 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -98869,7 +98941,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression; if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. @@ -98900,7 +98972,7 @@ var ts; } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); - for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; if (!entryNames.has(keywordEntry.name)) { entries.push(keywordEntry); @@ -99467,7 +99539,22 @@ var ts; var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { + kind: 0 /* Data */, + symbols: symbols, + completionKind: completionKind, + isInSnippetScope: isInSnippetScope, + propertyAccessToConvert: propertyAccessToConvert, + isNewIdentifierLocation: isNewIdentifierLocation, + location: location, + keywordFilters: keywordFilters, + literals: literals, + symbolToOriginInfoMap: symbolToOriginInfoMap, + recommendedCompletion: recommendedCompletion, + previousToken: previousToken, + isJsxInitializer: isJsxInitializer, + insideJsDocTagTypeExpression: insideJsDocTagTypeExpression + }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 304 /* JSDocParameterTag */: @@ -99514,7 +99601,9 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + if (!isTypeLocation && + symbol.declarations && + symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -100437,7 +100526,15 @@ var ts; } return res; }); - function getKeywordCompletions(keywordFilter) { + function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { + if (!filterOutTsOnlyKeywords) + return getTypescriptKeywordCompletions(keywordFilter); + var index = keywordFilter + 6 /* Last */ + 1; + return _keywordCompletions[index] || + (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter) + .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); })); + } + function getTypescriptKeywordCompletions(keywordFilter) { return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { var kind = ts.stringToToken(entry.name); switch (keywordFilter) { @@ -100461,6 +100558,39 @@ var ts; } })); } + function isTypeScriptOnlyKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 120 /* AnyKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 145 /* GlobalKeyword */: + case 109 /* ImplementsKeyword */: + case 127 /* InferKeyword */: + case 110 /* InterfaceKeyword */: + case 128 /* IsKeyword */: + case 129 /* KeyOfKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 132 /* NeverKeyword */: + case 135 /* NumberKeyword */: + case 136 /* ObjectKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + case 138 /* StringKeyword */: + case 139 /* SymbolKeyword */: + case 140 /* TypeKeyword */: + case 142 /* UniqueKeyword */: + case 143 /* UnknownKeyword */: + return true; + default: + return false; + } + } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { return kind === 133 /* ReadonlyKeyword */; } @@ -102238,23 +102368,26 @@ var ts; } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); - } - else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); - } - } + getReferencesInContainerOrFiles(symbol, state, search); } return result; } + function getReferencesInContainerOrFiles(symbol, state, search) { + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } function getSpecialSearchKind(node) { switch (node.kind) { case 124 /* ConstructorKeyword */: @@ -102306,9 +102439,7 @@ var ts; * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { - function State(sourceFiles, sourceFilesSet, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.sourceFilesSet = sourceFilesSet; this.specialSearchKind = specialSearchKind; @@ -102862,6 +102993,7 @@ var ts; var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); if (classExtending) { findSuperConstructorAccesses(classExtending, pusher()); + findInheritedConstructorReferences(classExtending, state); } } } @@ -102894,33 +103026,41 @@ var ts; * Reference the constructor and all calls to `new this()`. */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); - addNode(ctrKeyword); - } - classSymbol.exports.forEach(function (member) { - var decl = member.valueDeclaration; - if (decl && decl.kind === 156 /* MethodDeclaration */) { - var body = decl.body; - if (body) { - forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { - if (ts.isNewExpressionTarget(thisKeyword)) { - addNode(thisKeyword); - } - }); - } + var constructorSymbol = getClassConstructorSymbol(classSymbol); + if (constructorSymbol) { + for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); } - }); + } + if (classSymbol.exports) { + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + } + function getClassConstructorSymbol(classSymbol) { + return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */); } /** Find references to `super` in the constructor of an extending class. */ - function findSuperConstructorAccesses(cls, addNode) { - var ctr = cls.symbol.members.get("__constructor" /* Constructor */); - if (!ctr) { + function findSuperConstructorAccesses(classDeclaration, addNode) { + var constructor = getClassConstructorSymbol(classDeclaration.symbol); + if (!constructor) { return; } - for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; @@ -102933,6 +103073,16 @@ var ts; } } } + function hasOwnConstructor(classDeclaration) { + return !!getClassConstructorSymbol(classDeclaration.symbol); + } + function findInheritedConstructorReferences(classDeclaration, state) { + if (hasOwnConstructor(classDeclaration)) + return; + var classSymbol = classDeclaration.symbol; + var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined); + getReferencesInContainerOrFiles(classSymbol, state, search); + } function addImplementationReferences(refNode, addReference, state) { // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { @@ -106933,7 +107083,7 @@ var ts; return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - var isVariadic = candidateSignature.hasRestParameter; + var isVariadic = checker.hasEffectiveRestParameter(candidateSignature); var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { @@ -119603,7 +119753,7 @@ var ts; var checker = program.getTypeChecker(); var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); }); var groupedReferences = groupReferences(references); - if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) { + if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) { groupedReferences.valid = false; } return groupedReferences; @@ -119619,7 +119769,18 @@ var ts; groupedReferences.valid = false; continue; } - if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) { + /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. + Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: + class A { foo(a: number, b: number) { return a + b; } } + class B { foo(c: number, d: number) { return c + d; } } + declare const ab: A | B; + ab.foo(1, 2); + Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`. + When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol. + So we need to add a special case for this because when calling a constructor of a class through one of its subclasses, + the symbols are going to be different. + */ + if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) { var decl = entryToDeclaration(entry); if (decl) { groupedReferences.declarations.push(decl); @@ -119743,6 +119904,9 @@ var ts; function getFunctionDeclarationAtPosition(file, startPosition, checker) { var node = ts.getTouchingToken(file, startPosition); var functionDeclaration = ts.getContainingFunction(node); + // don't offer refactor on top-level JSDoc + if (isTopLevelJSDoc(node)) + return undefined; if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && ts.rangeContainsRange(functionDeclaration, node) @@ -119750,19 +119914,33 @@ var ts; return functionDeclaration; return undefined; } + function isTopLevelJSDoc(node) { + var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode); + if (containingJSDoc) { + var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); }); + return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; + } function isValidFunctionDeclaration(functionDeclaration, checker) { - if (!isValidParameterNodeArray(functionDeclaration.parameters)) + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { case 239 /* FunctionDeclaration */: case 156 /* MethodDeclaration */: - return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.name + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); case 157 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { - return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.body + && !!functionDeclaration.parent.name + && !checker.isImplementationOfOverload(functionDeclaration); } else { - return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return isValidVariableDeclaration(functionDeclaration.parent.parent) + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); } case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: @@ -119770,11 +119948,17 @@ var ts; } return false; } - function isValidParameterNodeArray(parameters) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration); + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength + && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); }); } - function isValidParameterDeclaration(paramDeclaration) { - return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name); + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -119794,13 +119978,22 @@ var ts; } return parameters; } + function createPropertyOrShorthandAssignment(name, initializer) { + if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) { + return ts.createShorthandPropertyAssignment(name); + } + return ts.createPropertyAssignment(name, initializer); + } function createNewArgument(functionDeclaration, functionArguments) { var parameters = getRefactorableParameters(functionDeclaration.parameters); var hasRestParameter = ts.isRestParameter(ts.last(parameters)); var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments; var properties = ts.map(nonRestArguments, function (arg, i) { - var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg); - ts.suppressLeadingAndTrailingTrivia(property.initializer); + var parameterName = getParameterName(parameters[i]); + var property = createPropertyOrShorthandAssignment(parameterName, arg); + ts.suppressLeadingAndTrailingTrivia(property.name); + if (ts.isPropertyAssignment(property)) + ts.suppressLeadingAndTrailingTrivia(property.initializer); copyComments(arg, property); return property; }); @@ -119813,14 +120006,14 @@ var ts; return objectLiteral; } function createNewParameters(functionDeclaration, program, host) { + var checker = program.getTypeChecker(); var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration); var objectParameterName = ts.createObjectBindingPattern(bindingElements); var objectParameterType = createParameterTypeNode(refactorableParameters); - var checker = program.getTypeChecker(); var objectInitializer; // If every parameter in the original function was optional, add an empty object initializer to the new object parameter - if (ts.every(refactorableParameters, checker.isOptionalParameter)) { + if (ts.every(refactorableParameters, isOptionalParameter)) { objectInitializer = ts.createObjectLiteral(); } var objectParameter = ts.createParameter( @@ -119844,6 +120037,16 @@ var ts; return ts.createNodeArray([newThisParameter, objectParameter]); } return ts.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + var element = ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); + ts.suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } function createParameterTypeNode(parameters) { var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration); var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */); @@ -119855,7 +120058,7 @@ var ts; parameterType = getTypeNode(parameterDeclaration); } var propertySignature = ts.createPropertySignature( - /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, + /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); copyComments(parameterDeclaration.name, propertySignature.name); @@ -119865,20 +120068,16 @@ var ts; return propertySignature; } function getTypeNode(node) { - var checker = program.getTypeChecker(); var type = checker.getTypeAtLocation(node); return ts.getTypeNodeIfAccessible(type, node, program, host); } - } - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - var element = ts.createBindingElement( - /*dotDotDotToken*/ undefined, - /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); - ts.suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + function isOptionalParameter(parameterDeclaration) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); } - return element; } function copyComments(sourceNode, targetNode) { var sourceFile = sourceNode.getSourceFile(); @@ -120844,7 +121043,7 @@ var ts; function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { - throw new Error("Could not find file: '" + fileName + "'."); + throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + "."); } return sourceFile; } @@ -128989,16 +129188,31 @@ var ts; msg += "\n" + server.indent(err.stack); } } - if (fileRequest && this.logger.hasLevel(server.LogLevel.verbose)) { - try { - var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; - var scriptInfo = project.getScriptInfoForNormalizedPath(file); - if (scriptInfo) { - var text = ts.getSnapshotText(scriptInfo.getSnapshot()); - msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + if (this.logger.hasLevel(server.LogLevel.verbose)) { + if (fileRequest) { + try { + var _a = this.getFileAndProject(fileRequest), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + if (scriptInfo) { + var text = ts.getSnapshotText(scriptInfo.getSnapshot()); + msg += "\n\nFile text of " + fileRequest.file + ":" + server.indent(text) + "\n"; + } } + catch (_b) { } // tslint:disable-line no-empty + } + if (err.message && err.message.indexOf("Could not find sourceFile:") !== -1) { + msg += "\n\nProjects::\n"; + var counter_1 = 0; + var addProjectInfo = function (project) { + msg += "\nProject '" + project.projectName + "' (" + server.ProjectKind[project.projectKind] + ") " + counter_1 + "\n"; + msg += project.filesToString(/*writeProjectFileNames*/ true); + msg += "\n-----------------------------------------------\n"; + counter_1++; + }; + this.projectService.externalProjects.forEach(addProjectInfo); + this.projectService.configuredProjects.forEach(addProjectInfo); + this.projectService.inferredProjects.forEach(addProjectInfo); } - catch (_b) { } // tslint:disable-line no-empty } this.logger.msg(msg, server.Msg.Err); }; diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 2b8056735a476..314ccf298cf28 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -2382,8 +2382,8 @@ declare namespace ts { root: ConditionalRoot; checkType: Type; extendsType: Type; - resolvedTrueType?: Type; - resolvedFalseType?: Type; + trueType: Type; + falseType: Type; } interface SubstitutionType extends InstantiableType { typeVariable: TypeVariable; diff --git a/lib/typescript.js b/lib/typescript.js index 45298df2ccaad..af0dc4daef56d 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -75,7 +75,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.4"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-rc"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -31311,6 +31311,7 @@ var ts; return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */); }, getExpandedParameters: getExpandedParameters, + hasEffectiveRestParameter: hasEffectiveRestParameter, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; @@ -31372,6 +31373,8 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, getObjectFlags: ts.getObjectFlags, + isArrayType: isArrayType, + isTupleType: isTupleType, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -32454,7 +32457,13 @@ var ts; // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. // } // - if (location.parent && ts.isClassElement(location.parent)) { + // class Decorators are resolved outside of the class to avoid referencing type parameters of that class. + // + // type T = number; + // declare function y(x: T): any; + // @param(1 as T) // <-- T should resolve to the type alias outside of class C + // class C {} + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) { location = location.parent; } break; @@ -33252,20 +33261,12 @@ var ts; return undefined; } if (moduleNotFoundError) { - // For relative paths, see if this was possibly a projectReference redirect - if (ts.pathIsRelative(moduleReference)) { - var sourceFile_1 = ts.getSourceFileOfNode(location); - var redirects = sourceFile_1.redirectedReferences; - if (redirects) { - var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); - for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { - var ext = _a[_i]; - var probePath = normalizedTargetPath + ext; - if (redirects.indexOf(probePath) >= 0) { - error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); - return undefined; - } - } + // See if this was possibly a projectReference redirect + if (resolvedModule) { + var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return undefined; } } if (resolutionDiagnostic) { @@ -34297,8 +34298,8 @@ var ts; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); - var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); + var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } @@ -36105,9 +36106,6 @@ var ts; } return type_1; } - if (declaration.kind === 254 /* ExportAssignment */) { - return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` @@ -36117,7 +36115,10 @@ var ts; return reportCircularityError(symbol); } var type; - if (ts.isInJSFile(declaration) && + if (declaration.kind === 254 /* ExportAssignment */) { + type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + else if (ts.isInJSFile(declaration) && (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } @@ -37642,6 +37643,15 @@ var ts; var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); + if (symbol === globalThisSymbol) { + var varsOnly_1 = ts.createMap(); + members.forEach(function (p) { + if (!(p.flags & 418 /* BlockScoped */)) { + varsOnly_1.set(p.escapedName, p); + } + }); + members = varsOnly_1; + } } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { @@ -37974,6 +37984,9 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined; + } + function getConstraintFromIndexedAccess(type) { var objectType = getConstraintOfType(type.objectType) || type.objectType; if (objectType !== type.objectType) { var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); @@ -37984,23 +37997,14 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } - function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { - var rootTrueType = root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - return instantiateType(rootTrueConstraint, combinedMapper || mapper); - } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, // in effect treating `any` like `never` rather than `unknown` in this location. - var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); - var falseConstraint = getFalseTypeFromConditionalType(type); + var trueConstraint = getInferredTrueTypeFromConditionalType(type); + var falseConstraint = type.falseType; type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; @@ -38030,9 +38034,12 @@ var ts; } return undefined; } - function getConstraintOfConditionalType(type) { + function getConstraintFromConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined; + } function getUnionConstraintOfIntersection(type, targetIsUnion) { var constraints; var hasDisjointDomainType = false; @@ -38106,7 +38113,7 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } - if (constraintDepth === 50) { + if (constraintDepth >= 50) { // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a // very high likelyhood we're dealing with an infinite generic type that perpetually generates // new type identities as we descend into it. We stop the recursion here and mark this type @@ -38172,8 +38179,11 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 16777216 /* Conditional */) { - var constraint = getConstraintOfConditionalType(t); - return constraint && getBaseConstraint(constraint); + var constraint = getConstraintFromConditionalType(t); + constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward) + var result = constraint && getBaseConstraint(constraint); + constraintDepth--; + return result; } if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -38260,7 +38270,7 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var props; + var propSet = ts.createMap(); var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; @@ -38276,7 +38286,10 @@ var ts; var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - props = ts.appendIfUnique(props, prop); + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | @@ -38298,9 +38311,10 @@ var ts; } } } - if (!props) { + if (!propSet.size) { return undefined; } + var props = ts.arrayFrom(propSet.values()); if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } @@ -38743,32 +38757,23 @@ var ts; } } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type, signature.declaration) : + createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } - function createTypePredicateFromTypePredicateNode(node, func) { + function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 72 /* Identifier */) { - return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } else { return createThisTypePredicate(type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - return -1; - } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -39245,6 +39250,9 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { + if (substitute.flags & 3 /* AnyOrUnknown */) { + return typeVariable; + } var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; @@ -40223,7 +40231,10 @@ var ts; return anyType; } if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) { + error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); } @@ -40426,24 +40437,11 @@ var ts; var trueType = instantiateType(root.trueType, mapper); var falseType = instantiateType(root.falseType, mapper); var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); - if (conditionalTypes.has(instantiationId)) { - var result = conditionalTypes.get(instantiationId); - if (result !== undefined) { - return result; - } - // Somehow the conditional type depends on itself - usually via `infer` types in the `extends` clause - // paired with a (potentially deferred) circularly constrained type. - // The conditional _must_ be deferred. - var deferred = getDeferredConditionalType(root, mapper, /*combinedMapper*/ undefined, checkType, extendsType, trueType, falseType); - conditionalTypes.set(instantiationId, deferred); - return deferred; + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; } - conditionalTypes.set(instantiationId, undefined); var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); - var cachedRecursiveResult = conditionalTypes.get(instantiationId); - if (cachedRecursiveResult) { - return cachedRecursiveResult; - } conditionalTypes.set(instantiationId, newResult); return newResult; } @@ -40451,7 +40449,7 @@ var ts; // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true - return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + return trueType; } else if (isIntersectionEmpty(checkType, extendsType)) { // Always false return neverType; @@ -40462,7 +40460,7 @@ var ts; return neverType; } else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false - return falseType; // TODO: Intersect negated `extends` type here + return falseType; } } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); @@ -40515,19 +40513,14 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; - if (!combinedMapper) { - result.resolvedTrueType = trueType; - result.resolvedFalseType = falseType; - } + result.trueType = trueType; + result.falseType = falseType; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } - function getTrueTypeFromConditionalType(type) { - return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); - } - function getFalseTypeFromConditionalType(type) { - return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper)); } function getInferTypeParameters(node) { var result; @@ -41388,7 +41381,11 @@ var ts; return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); } else { - return maybeVariable; + var sub = instantiateType(type.substitute, mapper); + if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + return maybeVariable; + } + return sub; } } return type; @@ -41945,6 +41942,14 @@ var ts; return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } + /** + * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` + */ + function isAnySignature(s) { + return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && + s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + isTypeAny(getReturnTypeOfSignature(s)); + } /** * See signatureRelatedTo, compareSignaturesIdentical */ @@ -41953,6 +41958,9 @@ var ts; if (source === target) { return -1 /* True */; } + if (isAnySignature(target)) { + return -1 /* True */; + } var targetCount = getParameterCount(target); if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; @@ -42030,7 +42038,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -42049,7 +42057,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -42058,12 +42066,9 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var targetPredicate = target; - var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); - var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); - if (sourceIndex !== targetIndex) { + if (source.parameterIndex !== target.parameterIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -42871,8 +42876,8 @@ var ts; if (source.root.isDistributive === target.root.isDistributive) { if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { return result_3; } } @@ -43021,8 +43026,8 @@ var ts; // and Y1 is related to Y2. if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { - if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { + result &= isRelatedTo(source.falseType, target.falseType, reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -44347,7 +44352,7 @@ var ts; } } } - function forEachMatchingParameterType(source, target, callback) { + function applyToParameterTypes(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); var sourceRestType = getEffectiveRestType(source); @@ -44368,6 +44373,17 @@ var ts; callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } + function applyToReturnTypes(source, target, callback) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind && + (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } function createInferenceContext(typeParameters, signature, flags, compareTypes) { return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); } @@ -44582,11 +44598,11 @@ var ts; inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : emptyObjectType; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } + if (contravariant === void 0) { contravariant = false; } var symbolStack; var visited; - var contravariant = false; var bivariant = false; var propagationType; var allowComplexConstraintInference = true; @@ -44678,9 +44694,11 @@ var ts; var candidate = propagationType || source; // We make contravariant inferences only if we are in a pure contravariant position, // i.e. only if we have not descended into a bivariant position. - if (contravariant && !bivariant && !ts.contains(inference.contraCandidates, candidate)) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); - inference.inferredType = undefined; + if (contravariant && !bivariant) { + if (!ts.contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + inference.inferredType = undefined; + } } else if (!ts.contains(inference.candidates, candidate)) { inference.candidates = ts.append(inference.candidates, candidate); @@ -44752,12 +44770,12 @@ var ts; else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes(source.trueType, target.trueType); + inferFromTypes(source.falseType, target.falseType); } else if (target.flags & 16777216 /* Conditional */ && !contravariant) { - inferFromTypes(source, getTrueTypeFromConditionalType(target)); - inferFromTypes(source, getFalseTypeFromConditionalType(target)); + inferFromTypes(source, target.trueType); + inferFromTypes(source, target.falseType); } else if (target.flags & 3145728 /* UnionOrIntersection */) { for (var _d = 0, _e = target.types; _d < _e.length; _d++) { @@ -44981,17 +44999,10 @@ var ts; var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; // Once we descend into a bivariant signature we remain bivariant for all nested inferences bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } - var sourceTypePredicate = getTypePredicateOfSignature(source); - var targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { - inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); @@ -46539,7 +46550,7 @@ var ts; return type; } if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); @@ -49193,7 +49204,10 @@ var ts; return anyType; } if (leftType.symbol === globalThisSymbol) { - if (noImplicitAny) { + if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } + else if (noImplicitAny) { error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; @@ -49772,18 +49786,14 @@ var ts; var restType = getEffectiveRestType(contextualSignature); var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; - forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + applyToParameterTypes(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, source, target); }); if (!inferenceContext) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); - var signaturePredicate = getTypePredicateOfSignature(signature); - var contextualPredicate = getTypePredicateOfSignature(sourceSignature); - if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind && - (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) { - inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */); - } + applyToReturnTypes(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target, 8 /* ReturnType */); + }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } @@ -52807,23 +52817,30 @@ var ts; // potentially add inferred type parameters to the outer function return type. var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature)); if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) { - // Instantiate the expression type with its own type parameters as type arguments. This - // ensures that the type parameters are not erased to type any during type inference such - // that they can be inferred as actual types. + // Instantiate the signature with its own type parameters as type arguments, possibly + // renaming the type parameters to ensure they have unique names. var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); - var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters)); - // Infer from the stripped expression type to the contextual type starting with an empty - // set of inference candidates. - var inferences = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); - inferTypes(inferences, strippedType, contextualType); - // If we produced some inference candidates and if the type parameters for which we produced - // candidates do not already have existing inferences, we adopt the new inference candidates and - // add the type parameters of the expression type to the set of inferred type parameters for - // the outer function return type. - if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) { - mergeInferences(context.inferences, inferences); - context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); - return strippedType; + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + // Infer from the parameters of the instantiated signature to the parameters of the + // contextual signature starting with an empty set of inference candidates. + var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); + applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true); + }); + if (ts.some(inferences_2, hasInferenceCandidates)) { + // We have inference candidates, indicating that one or more type parameters are referenced + // in the parameter types of the contextual signature. Now also infer from the return type. + applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target); + }); + // If the type parameters for which we produced candidates do not have any inferences yet, + // we adopt the new inference candidates and add the type parameters of the expression type + // to the set of inferred type parameters for the outer function return type. + if (!hasOverlappingInferences(context.inferences, inferences_2)) { + mergeInferences(context.inferences, inferences_2); + context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } } } return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context)); @@ -53146,7 +53163,8 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + var signature = getSignatureFromDeclaration(parent); + var typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) { return; } @@ -53157,12 +53175,12 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -56820,8 +56838,8 @@ var ts; var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 && !inAmbientContext + && symbol.declarations.length > 1 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -68333,11 +68351,14 @@ var ts; var decorators; if (node) { var parameters = node.parameters; - for (var i = 0; i < parameters.length; i++) { - var parameter = parameters[i]; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array(numParameters); } decorators[i] = parameter.decorators; } @@ -70467,8 +70488,10 @@ var ts; } var savedCapturedSuperProperties = capturedSuperProperties; var savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = ts.createUnderscoreEscapedMap(); - hasSuperElementAccess = false; + if (!isArrowFunction) { + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + } var result; if (!isArrowFunction) { var statements = []; @@ -70480,9 +70503,11 @@ var ts; var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); - substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + if (ts.hasEntries(capturedSuperProperties)) { + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70509,8 +70534,10 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; - capturedSuperProperties = savedCapturedSuperProperties; - hasSuperElementAccess = savedHasSuperElementAccess; + if (!isArrowFunction) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + } return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -70663,7 +70690,7 @@ var ts; /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */)))); if (hasBinding) { getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( /* modifiers */ undefined, @@ -70678,7 +70705,7 @@ var ts; /* initializer */ undefined) ], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v"))))); } accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); }); @@ -87723,11 +87750,7 @@ var ts; function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); function getSourceFile(fileName, languageVersion, onError) { var text; try { @@ -89598,7 +89621,6 @@ var ts; if (refFile) { var redirect = getProjectReferenceRedirect(fileName); if (redirect) { - (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); fileName = redirect; // Once we start redirecting to a file, we can potentially come back to it // via a back-reference from another file in the .d.ts folder. If that happens we'll @@ -90590,7 +90612,7 @@ var ts; // Create the reference map, and set the file infos for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var version_1 = sourceFile.version; + var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -91599,8 +91621,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_2 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -93061,6 +93083,32 @@ var ts; return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); } ts.readBuilderProgram = readBuilderProgram; + function createIncrementalCompilerHost(options, system) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); + host.createHash = ts.maybeBind(system, system.createHash); + setGetSourceFileAsHashVersioned(host, system); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); + return host; + } + ts.createIncrementalCompilerHost = createIncrementalCompilerHost; + function createIncrementalProgram(_a) { + var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram; + host = host || createIncrementalCompilerHost(options); + createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram; + var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); }); + return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + } + function performIncrementalCompilation(input) { + var system = input.system || ts.sys; + var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + var builderProgram = createIncrementalProgram(input); + var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + if (input.afterProgramEmitAndDiagnostics) + input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; + } + ts.performIncrementalCompilation = performIncrementalCompilation; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -93978,6 +94026,16 @@ var ts; newerInputFileName: newestInputFileName }; } + else { + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + } if (!buildInfoChecked.hasKey(project.options.configFilePath)) { buildInfoChecked.setValue(project.options.configFilePath, true); var buildInfoPath = ts.getOutputPathForBuildInfo(project.options); @@ -94010,6 +94068,17 @@ var ts; oldestOutputFileName: oldestOutputFileName }; } + function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) { + // Check tsconfig time + var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + if (oldestOutputFileTime < tsconfigTime) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } + } function invalidateProject(configFileName, reloadLevel) { invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } @@ -94320,6 +94389,8 @@ var ts; } } function getOldProgram(proj, parsed) { + if (options.force) + return undefined; var value = builderPrograms.getValue(proj); if (value) return value; @@ -98815,6 +98886,7 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -98860,7 +98932,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression; if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. @@ -98891,7 +98963,7 @@ var ts; } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); - for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; if (!entryNames.has(keywordEntry.name)) { entries.push(keywordEntry); @@ -99458,7 +99530,22 @@ var ts; var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { + kind: 0 /* Data */, + symbols: symbols, + completionKind: completionKind, + isInSnippetScope: isInSnippetScope, + propertyAccessToConvert: propertyAccessToConvert, + isNewIdentifierLocation: isNewIdentifierLocation, + location: location, + keywordFilters: keywordFilters, + literals: literals, + symbolToOriginInfoMap: symbolToOriginInfoMap, + recommendedCompletion: recommendedCompletion, + previousToken: previousToken, + isJsxInitializer: isJsxInitializer, + insideJsDocTagTypeExpression: insideJsDocTagTypeExpression + }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 304 /* JSDocParameterTag */: @@ -99505,7 +99592,9 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + if (!isTypeLocation && + symbol.declarations && + symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -100428,7 +100517,15 @@ var ts; } return res; }); - function getKeywordCompletions(keywordFilter) { + function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { + if (!filterOutTsOnlyKeywords) + return getTypescriptKeywordCompletions(keywordFilter); + var index = keywordFilter + 6 /* Last */ + 1; + return _keywordCompletions[index] || + (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter) + .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); })); + } + function getTypescriptKeywordCompletions(keywordFilter) { return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { var kind = ts.stringToToken(entry.name); switch (keywordFilter) { @@ -100452,6 +100549,39 @@ var ts; } })); } + function isTypeScriptOnlyKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 120 /* AnyKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 145 /* GlobalKeyword */: + case 109 /* ImplementsKeyword */: + case 127 /* InferKeyword */: + case 110 /* InterfaceKeyword */: + case 128 /* IsKeyword */: + case 129 /* KeyOfKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 132 /* NeverKeyword */: + case 135 /* NumberKeyword */: + case 136 /* ObjectKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + case 138 /* StringKeyword */: + case 139 /* SymbolKeyword */: + case 140 /* TypeKeyword */: + case 142 /* UniqueKeyword */: + case 143 /* UnknownKeyword */: + return true; + default: + return false; + } + } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { return kind === 133 /* ReadonlyKeyword */; } @@ -102229,23 +102359,26 @@ var ts; } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); - } - else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); - } - } + getReferencesInContainerOrFiles(symbol, state, search); } return result; } + function getReferencesInContainerOrFiles(symbol, state, search) { + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } function getSpecialSearchKind(node) { switch (node.kind) { case 124 /* ConstructorKeyword */: @@ -102297,9 +102430,7 @@ var ts; * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { - function State(sourceFiles, sourceFilesSet, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.sourceFilesSet = sourceFilesSet; this.specialSearchKind = specialSearchKind; @@ -102853,6 +102984,7 @@ var ts; var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); if (classExtending) { findSuperConstructorAccesses(classExtending, pusher()); + findInheritedConstructorReferences(classExtending, state); } } } @@ -102885,33 +103017,41 @@ var ts; * Reference the constructor and all calls to `new this()`. */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); - addNode(ctrKeyword); - } - classSymbol.exports.forEach(function (member) { - var decl = member.valueDeclaration; - if (decl && decl.kind === 156 /* MethodDeclaration */) { - var body = decl.body; - if (body) { - forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { - if (ts.isNewExpressionTarget(thisKeyword)) { - addNode(thisKeyword); - } - }); - } + var constructorSymbol = getClassConstructorSymbol(classSymbol); + if (constructorSymbol) { + for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); } - }); + } + if (classSymbol.exports) { + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + } + function getClassConstructorSymbol(classSymbol) { + return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */); } /** Find references to `super` in the constructor of an extending class. */ - function findSuperConstructorAccesses(cls, addNode) { - var ctr = cls.symbol.members.get("__constructor" /* Constructor */); - if (!ctr) { + function findSuperConstructorAccesses(classDeclaration, addNode) { + var constructor = getClassConstructorSymbol(classDeclaration.symbol); + if (!constructor) { return; } - for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; @@ -102924,6 +103064,16 @@ var ts; } } } + function hasOwnConstructor(classDeclaration) { + return !!getClassConstructorSymbol(classDeclaration.symbol); + } + function findInheritedConstructorReferences(classDeclaration, state) { + if (hasOwnConstructor(classDeclaration)) + return; + var classSymbol = classDeclaration.symbol; + var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined); + getReferencesInContainerOrFiles(classSymbol, state, search); + } function addImplementationReferences(refNode, addReference, state) { // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { @@ -106924,7 +107074,7 @@ var ts; return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - var isVariadic = candidateSignature.hasRestParameter; + var isVariadic = checker.hasEffectiveRestParameter(candidateSignature); var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { @@ -119594,7 +119744,7 @@ var ts; var checker = program.getTypeChecker(); var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); }); var groupedReferences = groupReferences(references); - if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) { + if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) { groupedReferences.valid = false; } return groupedReferences; @@ -119610,7 +119760,18 @@ var ts; groupedReferences.valid = false; continue; } - if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) { + /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. + Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: + class A { foo(a: number, b: number) { return a + b; } } + class B { foo(c: number, d: number) { return c + d; } } + declare const ab: A | B; + ab.foo(1, 2); + Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`. + When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol. + So we need to add a special case for this because when calling a constructor of a class through one of its subclasses, + the symbols are going to be different. + */ + if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) { var decl = entryToDeclaration(entry); if (decl) { groupedReferences.declarations.push(decl); @@ -119734,6 +119895,9 @@ var ts; function getFunctionDeclarationAtPosition(file, startPosition, checker) { var node = ts.getTouchingToken(file, startPosition); var functionDeclaration = ts.getContainingFunction(node); + // don't offer refactor on top-level JSDoc + if (isTopLevelJSDoc(node)) + return undefined; if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && ts.rangeContainsRange(functionDeclaration, node) @@ -119741,19 +119905,33 @@ var ts; return functionDeclaration; return undefined; } + function isTopLevelJSDoc(node) { + var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode); + if (containingJSDoc) { + var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); }); + return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; + } function isValidFunctionDeclaration(functionDeclaration, checker) { - if (!isValidParameterNodeArray(functionDeclaration.parameters)) + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { case 239 /* FunctionDeclaration */: case 156 /* MethodDeclaration */: - return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.name + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); case 157 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { - return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.body + && !!functionDeclaration.parent.name + && !checker.isImplementationOfOverload(functionDeclaration); } else { - return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return isValidVariableDeclaration(functionDeclaration.parent.parent) + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); } case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: @@ -119761,11 +119939,17 @@ var ts; } return false; } - function isValidParameterNodeArray(parameters) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration); + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength + && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); }); } - function isValidParameterDeclaration(paramDeclaration) { - return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name); + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -119785,13 +119969,22 @@ var ts; } return parameters; } + function createPropertyOrShorthandAssignment(name, initializer) { + if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) { + return ts.createShorthandPropertyAssignment(name); + } + return ts.createPropertyAssignment(name, initializer); + } function createNewArgument(functionDeclaration, functionArguments) { var parameters = getRefactorableParameters(functionDeclaration.parameters); var hasRestParameter = ts.isRestParameter(ts.last(parameters)); var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments; var properties = ts.map(nonRestArguments, function (arg, i) { - var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg); - ts.suppressLeadingAndTrailingTrivia(property.initializer); + var parameterName = getParameterName(parameters[i]); + var property = createPropertyOrShorthandAssignment(parameterName, arg); + ts.suppressLeadingAndTrailingTrivia(property.name); + if (ts.isPropertyAssignment(property)) + ts.suppressLeadingAndTrailingTrivia(property.initializer); copyComments(arg, property); return property; }); @@ -119804,14 +119997,14 @@ var ts; return objectLiteral; } function createNewParameters(functionDeclaration, program, host) { + var checker = program.getTypeChecker(); var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration); var objectParameterName = ts.createObjectBindingPattern(bindingElements); var objectParameterType = createParameterTypeNode(refactorableParameters); - var checker = program.getTypeChecker(); var objectInitializer; // If every parameter in the original function was optional, add an empty object initializer to the new object parameter - if (ts.every(refactorableParameters, checker.isOptionalParameter)) { + if (ts.every(refactorableParameters, isOptionalParameter)) { objectInitializer = ts.createObjectLiteral(); } var objectParameter = ts.createParameter( @@ -119835,6 +120028,16 @@ var ts; return ts.createNodeArray([newThisParameter, objectParameter]); } return ts.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + var element = ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); + ts.suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } function createParameterTypeNode(parameters) { var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration); var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */); @@ -119846,7 +120049,7 @@ var ts; parameterType = getTypeNode(parameterDeclaration); } var propertySignature = ts.createPropertySignature( - /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, + /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); copyComments(parameterDeclaration.name, propertySignature.name); @@ -119856,20 +120059,16 @@ var ts; return propertySignature; } function getTypeNode(node) { - var checker = program.getTypeChecker(); var type = checker.getTypeAtLocation(node); return ts.getTypeNodeIfAccessible(type, node, program, host); } - } - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - var element = ts.createBindingElement( - /*dotDotDotToken*/ undefined, - /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); - ts.suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + function isOptionalParameter(parameterDeclaration) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); } - return element; } function copyComments(sourceNode, targetNode) { var sourceFile = sourceNode.getSourceFile(); @@ -120835,7 +121034,7 @@ var ts; function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { - throw new Error("Could not find file: '" + fileName + "'."); + throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + "."); } return sourceFile; } diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 806ed4f1bb285..b9b02d5591f4d 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -2382,8 +2382,8 @@ declare namespace ts { root: ConditionalRoot; checkType: Type; extendsType: Type; - resolvedTrueType?: Type; - resolvedFalseType?: Type; + trueType: Type; + falseType: Type; } interface SubstitutionType extends InstantiableType { typeVariable: TypeVariable; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 406d3c5fd20bb..835a9569babcb 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -75,7 +75,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.4"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-rc"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -31311,6 +31311,7 @@ var ts; return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */); }, getExpandedParameters: getExpandedParameters, + hasEffectiveRestParameter: hasEffectiveRestParameter, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; @@ -31372,6 +31373,8 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, getObjectFlags: ts.getObjectFlags, + isArrayType: isArrayType, + isTupleType: isTupleType, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -32454,7 +32457,13 @@ var ts; // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. // } // - if (location.parent && ts.isClassElement(location.parent)) { + // class Decorators are resolved outside of the class to avoid referencing type parameters of that class. + // + // type T = number; + // declare function y(x: T): any; + // @param(1 as T) // <-- T should resolve to the type alias outside of class C + // class C {} + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) { location = location.parent; } break; @@ -33252,20 +33261,12 @@ var ts; return undefined; } if (moduleNotFoundError) { - // For relative paths, see if this was possibly a projectReference redirect - if (ts.pathIsRelative(moduleReference)) { - var sourceFile_1 = ts.getSourceFileOfNode(location); - var redirects = sourceFile_1.redirectedReferences; - if (redirects) { - var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); - for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { - var ext = _a[_i]; - var probePath = normalizedTargetPath + ext; - if (redirects.indexOf(probePath) >= 0) { - error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); - return undefined; - } - } + // See if this was possibly a projectReference redirect + if (resolvedModule) { + var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return undefined; } } if (resolutionDiagnostic) { @@ -34297,8 +34298,8 @@ var ts; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); - var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); + var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } @@ -36105,9 +36106,6 @@ var ts; } return type_1; } - if (declaration.kind === 254 /* ExportAssignment */) { - return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` @@ -36117,7 +36115,10 @@ var ts; return reportCircularityError(symbol); } var type; - if (ts.isInJSFile(declaration) && + if (declaration.kind === 254 /* ExportAssignment */) { + type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + else if (ts.isInJSFile(declaration) && (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } @@ -37642,6 +37643,15 @@ var ts; var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); + if (symbol === globalThisSymbol) { + var varsOnly_1 = ts.createMap(); + members.forEach(function (p) { + if (!(p.flags & 418 /* BlockScoped */)) { + varsOnly_1.set(p.escapedName, p); + } + }); + members = varsOnly_1; + } } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { @@ -37974,6 +37984,9 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined; + } + function getConstraintFromIndexedAccess(type) { var objectType = getConstraintOfType(type.objectType) || type.objectType; if (objectType !== type.objectType) { var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); @@ -37984,23 +37997,14 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } - function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { - var rootTrueType = root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - return instantiateType(rootTrueConstraint, combinedMapper || mapper); - } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, // in effect treating `any` like `never` rather than `unknown` in this location. - var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); - var falseConstraint = getFalseTypeFromConditionalType(type); + var trueConstraint = getInferredTrueTypeFromConditionalType(type); + var falseConstraint = type.falseType; type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; @@ -38030,9 +38034,12 @@ var ts; } return undefined; } - function getConstraintOfConditionalType(type) { + function getConstraintFromConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined; + } function getUnionConstraintOfIntersection(type, targetIsUnion) { var constraints; var hasDisjointDomainType = false; @@ -38106,7 +38113,7 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } - if (constraintDepth === 50) { + if (constraintDepth >= 50) { // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a // very high likelyhood we're dealing with an infinite generic type that perpetually generates // new type identities as we descend into it. We stop the recursion here and mark this type @@ -38172,8 +38179,11 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 16777216 /* Conditional */) { - var constraint = getConstraintOfConditionalType(t); - return constraint && getBaseConstraint(constraint); + var constraint = getConstraintFromConditionalType(t); + constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward) + var result = constraint && getBaseConstraint(constraint); + constraintDepth--; + return result; } if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -38260,7 +38270,7 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var props; + var propSet = ts.createMap(); var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; @@ -38276,7 +38286,10 @@ var ts; var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - props = ts.appendIfUnique(props, prop); + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | @@ -38298,9 +38311,10 @@ var ts; } } } - if (!props) { + if (!propSet.size) { return undefined; } + var props = ts.arrayFrom(propSet.values()); if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } @@ -38743,32 +38757,23 @@ var ts; } } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type, signature.declaration) : + createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } - function createTypePredicateFromTypePredicateNode(node, func) { + function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 72 /* Identifier */) { - return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } else { return createThisTypePredicate(type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - return -1; - } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -39245,6 +39250,9 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { + if (substitute.flags & 3 /* AnyOrUnknown */) { + return typeVariable; + } var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; @@ -40223,7 +40231,10 @@ var ts; return anyType; } if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) { + error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); } @@ -40426,24 +40437,11 @@ var ts; var trueType = instantiateType(root.trueType, mapper); var falseType = instantiateType(root.falseType, mapper); var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); - if (conditionalTypes.has(instantiationId)) { - var result = conditionalTypes.get(instantiationId); - if (result !== undefined) { - return result; - } - // Somehow the conditional type depends on itself - usually via `infer` types in the `extends` clause - // paired with a (potentially deferred) circularly constrained type. - // The conditional _must_ be deferred. - var deferred = getDeferredConditionalType(root, mapper, /*combinedMapper*/ undefined, checkType, extendsType, trueType, falseType); - conditionalTypes.set(instantiationId, deferred); - return deferred; + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; } - conditionalTypes.set(instantiationId, undefined); var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); - var cachedRecursiveResult = conditionalTypes.get(instantiationId); - if (cachedRecursiveResult) { - return cachedRecursiveResult; - } conditionalTypes.set(instantiationId, newResult); return newResult; } @@ -40451,7 +40449,7 @@ var ts; // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true - return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + return trueType; } else if (isIntersectionEmpty(checkType, extendsType)) { // Always false return neverType; @@ -40462,7 +40460,7 @@ var ts; return neverType; } else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false - return falseType; // TODO: Intersect negated `extends` type here + return falseType; } } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); @@ -40515,19 +40513,14 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; - if (!combinedMapper) { - result.resolvedTrueType = trueType; - result.resolvedFalseType = falseType; - } + result.trueType = trueType; + result.falseType = falseType; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } - function getTrueTypeFromConditionalType(type) { - return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); - } - function getFalseTypeFromConditionalType(type) { - return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper)); } function getInferTypeParameters(node) { var result; @@ -41388,7 +41381,11 @@ var ts; return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); } else { - return maybeVariable; + var sub = instantiateType(type.substitute, mapper); + if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + return maybeVariable; + } + return sub; } } return type; @@ -41945,6 +41942,14 @@ var ts; return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } + /** + * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` + */ + function isAnySignature(s) { + return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && + s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + isTypeAny(getReturnTypeOfSignature(s)); + } /** * See signatureRelatedTo, compareSignaturesIdentical */ @@ -41953,6 +41958,9 @@ var ts; if (source === target) { return -1 /* True */; } + if (isAnySignature(target)) { + return -1 /* True */; + } var targetCount = getParameterCount(target); if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; @@ -42030,7 +42038,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -42049,7 +42057,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -42058,12 +42066,9 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var targetPredicate = target; - var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); - var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); - if (sourceIndex !== targetIndex) { + if (source.parameterIndex !== target.parameterIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -42871,8 +42876,8 @@ var ts; if (source.root.isDistributive === target.root.isDistributive) { if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { return result_3; } } @@ -43021,8 +43026,8 @@ var ts; // and Y1 is related to Y2. if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { - if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { + result &= isRelatedTo(source.falseType, target.falseType, reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -44347,7 +44352,7 @@ var ts; } } } - function forEachMatchingParameterType(source, target, callback) { + function applyToParameterTypes(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); var sourceRestType = getEffectiveRestType(source); @@ -44368,6 +44373,17 @@ var ts; callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } + function applyToReturnTypes(source, target, callback) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind && + (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } function createInferenceContext(typeParameters, signature, flags, compareTypes) { return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); } @@ -44582,11 +44598,11 @@ var ts; inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : emptyObjectType; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } + if (contravariant === void 0) { contravariant = false; } var symbolStack; var visited; - var contravariant = false; var bivariant = false; var propagationType; var allowComplexConstraintInference = true; @@ -44678,9 +44694,11 @@ var ts; var candidate = propagationType || source; // We make contravariant inferences only if we are in a pure contravariant position, // i.e. only if we have not descended into a bivariant position. - if (contravariant && !bivariant && !ts.contains(inference.contraCandidates, candidate)) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); - inference.inferredType = undefined; + if (contravariant && !bivariant) { + if (!ts.contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + inference.inferredType = undefined; + } } else if (!ts.contains(inference.candidates, candidate)) { inference.candidates = ts.append(inference.candidates, candidate); @@ -44752,12 +44770,12 @@ var ts; else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes(source.trueType, target.trueType); + inferFromTypes(source.falseType, target.falseType); } else if (target.flags & 16777216 /* Conditional */ && !contravariant) { - inferFromTypes(source, getTrueTypeFromConditionalType(target)); - inferFromTypes(source, getFalseTypeFromConditionalType(target)); + inferFromTypes(source, target.trueType); + inferFromTypes(source, target.falseType); } else if (target.flags & 3145728 /* UnionOrIntersection */) { for (var _d = 0, _e = target.types; _d < _e.length; _d++) { @@ -44981,17 +44999,10 @@ var ts; var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; // Once we descend into a bivariant signature we remain bivariant for all nested inferences bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } - var sourceTypePredicate = getTypePredicateOfSignature(source); - var targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { - inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); @@ -46539,7 +46550,7 @@ var ts; return type; } if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); @@ -49193,7 +49204,10 @@ var ts; return anyType; } if (leftType.symbol === globalThisSymbol) { - if (noImplicitAny) { + if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } + else if (noImplicitAny) { error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; @@ -49772,18 +49786,14 @@ var ts; var restType = getEffectiveRestType(contextualSignature); var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; - forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + applyToParameterTypes(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, source, target); }); if (!inferenceContext) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); - var signaturePredicate = getTypePredicateOfSignature(signature); - var contextualPredicate = getTypePredicateOfSignature(sourceSignature); - if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind && - (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) { - inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */); - } + applyToReturnTypes(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target, 8 /* ReturnType */); + }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } @@ -52807,23 +52817,30 @@ var ts; // potentially add inferred type parameters to the outer function return type. var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature)); if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) { - // Instantiate the expression type with its own type parameters as type arguments. This - // ensures that the type parameters are not erased to type any during type inference such - // that they can be inferred as actual types. + // Instantiate the signature with its own type parameters as type arguments, possibly + // renaming the type parameters to ensure they have unique names. var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); - var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters)); - // Infer from the stripped expression type to the contextual type starting with an empty - // set of inference candidates. - var inferences = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); - inferTypes(inferences, strippedType, contextualType); - // If we produced some inference candidates and if the type parameters for which we produced - // candidates do not already have existing inferences, we adopt the new inference candidates and - // add the type parameters of the expression type to the set of inferred type parameters for - // the outer function return type. - if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) { - mergeInferences(context.inferences, inferences); - context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); - return strippedType; + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + // Infer from the parameters of the instantiated signature to the parameters of the + // contextual signature starting with an empty set of inference candidates. + var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); + applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true); + }); + if (ts.some(inferences_2, hasInferenceCandidates)) { + // We have inference candidates, indicating that one or more type parameters are referenced + // in the parameter types of the contextual signature. Now also infer from the return type. + applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target); + }); + // If the type parameters for which we produced candidates do not have any inferences yet, + // we adopt the new inference candidates and add the type parameters of the expression type + // to the set of inferred type parameters for the outer function return type. + if (!hasOverlappingInferences(context.inferences, inferences_2)) { + mergeInferences(context.inferences, inferences_2); + context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } } } return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context)); @@ -53146,7 +53163,8 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + var signature = getSignatureFromDeclaration(parent); + var typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) { return; } @@ -53157,12 +53175,12 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -56820,8 +56838,8 @@ var ts; var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 && !inAmbientContext + && symbol.declarations.length > 1 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -68333,11 +68351,14 @@ var ts; var decorators; if (node) { var parameters = node.parameters; - for (var i = 0; i < parameters.length; i++) { - var parameter = parameters[i]; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array(numParameters); } decorators[i] = parameter.decorators; } @@ -70467,8 +70488,10 @@ var ts; } var savedCapturedSuperProperties = capturedSuperProperties; var savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = ts.createUnderscoreEscapedMap(); - hasSuperElementAccess = false; + if (!isArrowFunction) { + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + } var result; if (!isArrowFunction) { var statements = []; @@ -70480,9 +70503,11 @@ var ts; var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); - substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + if (ts.hasEntries(capturedSuperProperties)) { + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70509,8 +70534,10 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; - capturedSuperProperties = savedCapturedSuperProperties; - hasSuperElementAccess = savedHasSuperElementAccess; + if (!isArrowFunction) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + } return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -70663,7 +70690,7 @@ var ts; /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */)))); if (hasBinding) { getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( /* modifiers */ undefined, @@ -70678,7 +70705,7 @@ var ts; /* initializer */ undefined) ], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v"))))); } accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); }); @@ -87723,11 +87750,7 @@ var ts; function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); function getSourceFile(fileName, languageVersion, onError) { var text; try { @@ -89598,7 +89621,6 @@ var ts; if (refFile) { var redirect = getProjectReferenceRedirect(fileName); if (redirect) { - (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); fileName = redirect; // Once we start redirecting to a file, we can potentially come back to it // via a back-reference from another file in the .d.ts folder. If that happens we'll @@ -90590,7 +90612,7 @@ var ts; // Create the reference map, and set the file infos for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var version_1 = sourceFile.version; + var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -91599,8 +91621,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_2 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -93061,6 +93083,32 @@ var ts; return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); } ts.readBuilderProgram = readBuilderProgram; + function createIncrementalCompilerHost(options, system) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); + host.createHash = ts.maybeBind(system, system.createHash); + setGetSourceFileAsHashVersioned(host, system); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); + return host; + } + ts.createIncrementalCompilerHost = createIncrementalCompilerHost; + function createIncrementalProgram(_a) { + var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram; + host = host || createIncrementalCompilerHost(options); + createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram; + var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); }); + return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + } + function performIncrementalCompilation(input) { + var system = input.system || ts.sys; + var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + var builderProgram = createIncrementalProgram(input); + var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + if (input.afterProgramEmitAndDiagnostics) + input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; + } + ts.performIncrementalCompilation = performIncrementalCompilation; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -93978,6 +94026,16 @@ var ts; newerInputFileName: newestInputFileName }; } + else { + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + } if (!buildInfoChecked.hasKey(project.options.configFilePath)) { buildInfoChecked.setValue(project.options.configFilePath, true); var buildInfoPath = ts.getOutputPathForBuildInfo(project.options); @@ -94010,6 +94068,17 @@ var ts; oldestOutputFileName: oldestOutputFileName }; } + function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) { + // Check tsconfig time + var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + if (oldestOutputFileTime < tsconfigTime) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } + } function invalidateProject(configFileName, reloadLevel) { invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } @@ -94320,6 +94389,8 @@ var ts; } } function getOldProgram(proj, parsed) { + if (options.force) + return undefined; var value = builderPrograms.getValue(proj); if (value) return value; @@ -98815,6 +98886,7 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 4] = "ConstructorParameterKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 5] = "FunctionLikeBodyKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["TypeKeywords"] = 6] = "TypeKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["Last"] = 6] = "Last"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); var GlobalsSearch; (function (GlobalsSearch) { @@ -98860,7 +98932,7 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, preferences) { - var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer; + var symbols = completionData.symbols, completionKind = completionData.completionKind, isInSnippetScope = completionData.isInSnippetScope, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, literals = completionData.literals, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion, isJsxInitializer = completionData.isJsxInitializer, insideJsDocTagTypeExpression = completionData.insideJsDocTagTypeExpression; if (location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. @@ -98891,7 +98963,7 @@ var ts; } if (keywordFilters !== 0 /* None */) { var entryNames = ts.arrayToSet(entries, function (e) { return e.name; }); - for (var _i = 0, _a = getKeywordCompletions(keywordFilters); _i < _a.length; _i++) { + for (var _i = 0, _a = getKeywordCompletions(keywordFilters, !insideJsDocTagTypeExpression && ts.isSourceFileJS(sourceFile)); _i < _a.length; _i++) { var keywordEntry = _a[_i]; if (!entryNames.has(keywordEntry.name)) { entries.push(keywordEntry); @@ -99458,7 +99530,22 @@ var ts; var contextualType = previousToken && getContextualType(previousToken, position, sourceFile, typeChecker); var literals = ts.mapDefined(contextualType && (contextualType.isUnion() ? contextualType.types : [contextualType]), function (t) { return t.isLiteral() ? t.value : undefined; }); var recommendedCompletion = previousToken && contextualType && getRecommendedCompletion(previousToken, contextualType, typeChecker); - return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, isInSnippetScope: isInSnippetScope, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, literals: literals, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken, isJsxInitializer: isJsxInitializer }; + return { + kind: 0 /* Data */, + symbols: symbols, + completionKind: completionKind, + isInSnippetScope: isInSnippetScope, + propertyAccessToConvert: propertyAccessToConvert, + isNewIdentifierLocation: isNewIdentifierLocation, + location: location, + keywordFilters: keywordFilters, + literals: literals, + symbolToOriginInfoMap: symbolToOriginInfoMap, + recommendedCompletion: recommendedCompletion, + previousToken: previousToken, + isJsxInitializer: isJsxInitializer, + insideJsDocTagTypeExpression: insideJsDocTagTypeExpression + }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 304 /* JSDocParameterTag */: @@ -99505,7 +99592,9 @@ var ts; } } // If the module is merged with a value, we must get the type of the class and add its propertes (for inherited static methods). - if (!isTypeLocation && symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { + if (!isTypeLocation && + symbol.declarations && + symbol.declarations.some(function (d) { return d.kind !== 284 /* SourceFile */ && d.kind !== 244 /* ModuleDeclaration */ && d.kind !== 243 /* EnumDeclaration */; })) { addTypeProperties(typeChecker.getTypeOfSymbolAtLocation(symbol, node)); } return; @@ -100428,7 +100517,15 @@ var ts; } return res; }); - function getKeywordCompletions(keywordFilter) { + function getKeywordCompletions(keywordFilter, filterOutTsOnlyKeywords) { + if (!filterOutTsOnlyKeywords) + return getTypescriptKeywordCompletions(keywordFilter); + var index = keywordFilter + 6 /* Last */ + 1; + return _keywordCompletions[index] || + (_keywordCompletions[index] = getTypescriptKeywordCompletions(keywordFilter) + .filter(function (entry) { return !isTypeScriptOnlyKeyword(ts.stringToToken(entry.name)); })); + } + function getTypescriptKeywordCompletions(keywordFilter) { return _keywordCompletions[keywordFilter] || (_keywordCompletions[keywordFilter] = allKeywordsCompletions().filter(function (entry) { var kind = ts.stringToToken(entry.name); switch (keywordFilter) { @@ -100452,6 +100549,39 @@ var ts; } })); } + function isTypeScriptOnlyKeyword(kind) { + switch (kind) { + case 118 /* AbstractKeyword */: + case 120 /* AnyKeyword */: + case 146 /* BigIntKeyword */: + case 123 /* BooleanKeyword */: + case 125 /* DeclareKeyword */: + case 84 /* EnumKeyword */: + case 145 /* GlobalKeyword */: + case 109 /* ImplementsKeyword */: + case 127 /* InferKeyword */: + case 110 /* InterfaceKeyword */: + case 128 /* IsKeyword */: + case 129 /* KeyOfKeyword */: + case 130 /* ModuleKeyword */: + case 131 /* NamespaceKeyword */: + case 132 /* NeverKeyword */: + case 135 /* NumberKeyword */: + case 136 /* ObjectKeyword */: + case 113 /* PrivateKeyword */: + case 114 /* ProtectedKeyword */: + case 115 /* PublicKeyword */: + case 133 /* ReadonlyKeyword */: + case 138 /* StringKeyword */: + case 139 /* SymbolKeyword */: + case 140 /* TypeKeyword */: + case 142 /* UniqueKeyword */: + case 143 /* UnknownKeyword */: + return true; + default: + return false; + } + } function isInterfaceOrTypeLiteralCompletionKeyword(kind) { return kind === 133 /* ReadonlyKeyword */; } @@ -102229,23 +102359,26 @@ var ts; } else { var search = state.createSearch(node, symbol, /*comingFrom*/ undefined, { allSearchSymbols: node ? populateSearchSymbolSet(symbol, node, checker, !!options.isForRename, !!options.providePrefixAndSuffixTextForRename, !!options.implementations) : [symbol] }); - // Try to get the smallest valid scope that we can limit our search to; - // otherwise we'll need to search globally (i.e. include each file). - var scope = getSymbolScope(symbol); - if (scope) { - getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(sourceFiles, scope))); - } - else { - // Global search - for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { - var sourceFile = _a[_i]; - state.cancellationToken.throwIfCancellationRequested(); - searchForName(sourceFile, search, state); - } - } + getReferencesInContainerOrFiles(symbol, state, search); } return result; } + function getReferencesInContainerOrFiles(symbol, state, search) { + // Try to get the smallest valid scope that we can limit our search to; + // otherwise we'll need to search globally (i.e. include each file). + var scope = getSymbolScope(symbol); + if (scope) { + getReferencesInContainer(scope, scope.getSourceFile(), search, state, /*addReferencesHere*/ !(ts.isSourceFile(scope) && !ts.contains(state.sourceFiles, scope))); + } + else { + // Global search + for (var _i = 0, _a = state.sourceFiles; _i < _a.length; _i++) { + var sourceFile = _a[_i]; + state.cancellationToken.throwIfCancellationRequested(); + searchForName(sourceFile, search, state); + } + } + } function getSpecialSearchKind(node) { switch (node.kind) { case 124 /* ConstructorKeyword */: @@ -102297,9 +102430,7 @@ var ts; * Unlike `Search`, there is only one `State`. */ var State = /** @class */ (function () { - function State(sourceFiles, sourceFilesSet, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + function State(sourceFiles, sourceFilesSet, specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.sourceFilesSet = sourceFilesSet; this.specialSearchKind = specialSearchKind; @@ -102853,6 +102984,7 @@ var ts; var classExtending = tryGetClassByExtendingIdentifier(referenceLocation); if (classExtending) { findSuperConstructorAccesses(classExtending, pusher()); + findInheritedConstructorReferences(classExtending, state); } } } @@ -102885,33 +103017,41 @@ var ts; * Reference the constructor and all calls to `new this()`. */ function findOwnConstructorReferences(classSymbol, sourceFile, addNode) { - for (var _i = 0, _a = classSymbol.members.get("__constructor" /* Constructor */).declarations; _i < _a.length; _i++) { - var decl = _a[_i]; - var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); - ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); - addNode(ctrKeyword); - } - classSymbol.exports.forEach(function (member) { - var decl = member.valueDeclaration; - if (decl && decl.kind === 156 /* MethodDeclaration */) { - var body = decl.body; - if (body) { - forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { - if (ts.isNewExpressionTarget(thisKeyword)) { - addNode(thisKeyword); - } - }); - } + var constructorSymbol = getClassConstructorSymbol(classSymbol); + if (constructorSymbol) { + for (var _i = 0, _a = constructorSymbol.declarations; _i < _a.length; _i++) { + var decl = _a[_i]; + var ctrKeyword = ts.findChildOfKind(decl, 124 /* ConstructorKeyword */, sourceFile); + ts.Debug.assert(decl.kind === 157 /* Constructor */ && !!ctrKeyword); + addNode(ctrKeyword); } - }); + } + if (classSymbol.exports) { + classSymbol.exports.forEach(function (member) { + var decl = member.valueDeclaration; + if (decl && decl.kind === 156 /* MethodDeclaration */) { + var body = decl.body; + if (body) { + forEachDescendantOfKind(body, 100 /* ThisKeyword */, function (thisKeyword) { + if (ts.isNewExpressionTarget(thisKeyword)) { + addNode(thisKeyword); + } + }); + } + } + }); + } + } + function getClassConstructorSymbol(classSymbol) { + return classSymbol.members && classSymbol.members.get("__constructor" /* Constructor */); } /** Find references to `super` in the constructor of an extending class. */ - function findSuperConstructorAccesses(cls, addNode) { - var ctr = cls.symbol.members.get("__constructor" /* Constructor */); - if (!ctr) { + function findSuperConstructorAccesses(classDeclaration, addNode) { + var constructor = getClassConstructorSymbol(classDeclaration.symbol); + if (!constructor) { return; } - for (var _i = 0, _a = ctr.declarations; _i < _a.length; _i++) { + for (var _i = 0, _a = constructor.declarations; _i < _a.length; _i++) { var decl = _a[_i]; ts.Debug.assert(decl.kind === 157 /* Constructor */); var body = decl.body; @@ -102924,6 +103064,16 @@ var ts; } } } + function hasOwnConstructor(classDeclaration) { + return !!getClassConstructorSymbol(classDeclaration.symbol); + } + function findInheritedConstructorReferences(classDeclaration, state) { + if (hasOwnConstructor(classDeclaration)) + return; + var classSymbol = classDeclaration.symbol; + var search = state.createSearch(/*location*/ undefined, classSymbol, /*comingFrom*/ undefined); + getReferencesInContainerOrFiles(classSymbol, state, search); + } function addImplementationReferences(refNode, addReference, state) { // Check if we found a function/propertyAssignment/method with an implementation or initializer if (ts.isDeclarationName(refNode) && isImplementation(refNode.parent)) { @@ -106924,7 +107074,7 @@ var ts; return { isVariadic: false, parameters: parameters, prefix: [ts.punctuationPart(28 /* LessThanToken */)], suffix: [ts.punctuationPart(30 /* GreaterThanToken */)].concat(parameterParts) }; } function itemInfoForParameters(candidateSignature, checker, enclosingDeclaration, sourceFile) { - var isVariadic = candidateSignature.hasRestParameter; + var isVariadic = checker.hasEffectiveRestParameter(candidateSignature); var printer = ts.createPrinter({ removeComments: true }); var typeParameterParts = ts.mapToDisplayParts(function (writer) { if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { @@ -119594,7 +119744,7 @@ var ts; var checker = program.getTypeChecker(); var references = ts.flatMap(names, /*mapfn*/ function (/*mapfn*/ name) { return ts.FindAllReferences.getReferenceEntriesForNode(-1, name, program, program.getSourceFiles(), cancellationToken); }); var groupedReferences = groupReferences(references); - if (!ts.every(groupedReferences.declarations, function (decl) { return ts.contains(names, decl); })) { + if (!ts.every(groupedReferences.declarations, /*callback*/ function (/*callback*/ decl) { return ts.contains(names, decl); })) { groupedReferences.valid = false; } return groupedReferences; @@ -119610,7 +119760,18 @@ var ts; groupedReferences.valid = false; continue; } - if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer)) { + /* We compare symbols because in some cases find all references wil return a reference that may or may not be to the refactored function. + Example from the refactorConvertParamsToDestructuredObject_methodCallUnion.ts test: + class A { foo(a: number, b: number) { return a + b; } } + class B { foo(c: number, d: number) { return c + d; } } + declare const ab: A | B; + ab.foo(1, 2); + Find all references will return `ab.foo(1, 2)` as a reference to A's `foo` but we could be calling B's `foo`. + When looking for constructor calls, however, the symbol on the constructor call reference is going to be the corresponding class symbol. + So we need to add a special case for this because when calling a constructor of a class through one of its subclasses, + the symbols are going to be different. + */ + if (ts.contains(functionSymbols, checker.getSymbolAtLocation(entry.node), symbolComparer) || ts.isNewExpressionTarget(entry.node)) { var decl = entryToDeclaration(entry); if (decl) { groupedReferences.declarations.push(decl); @@ -119734,6 +119895,9 @@ var ts; function getFunctionDeclarationAtPosition(file, startPosition, checker) { var node = ts.getTouchingToken(file, startPosition); var functionDeclaration = ts.getContainingFunction(node); + // don't offer refactor on top-level JSDoc + if (isTopLevelJSDoc(node)) + return undefined; if (functionDeclaration && isValidFunctionDeclaration(functionDeclaration, checker) && ts.rangeContainsRange(functionDeclaration, node) @@ -119741,19 +119905,33 @@ var ts; return functionDeclaration; return undefined; } + function isTopLevelJSDoc(node) { + var containingJSDoc = ts.findAncestor(node, ts.isJSDocNode); + if (containingJSDoc) { + var containingNonJSDoc = ts.findAncestor(containingJSDoc, function (n) { return !ts.isJSDocNode(n); }); + return !!containingNonJSDoc && ts.isFunctionLikeDeclaration(containingNonJSDoc); + } + return false; + } function isValidFunctionDeclaration(functionDeclaration, checker) { - if (!isValidParameterNodeArray(functionDeclaration.parameters)) + if (!isValidParameterNodeArray(functionDeclaration.parameters, checker)) return false; switch (functionDeclaration.kind) { case 239 /* FunctionDeclaration */: case 156 /* MethodDeclaration */: - return !!functionDeclaration.name && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.name + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); case 157 /* Constructor */: if (ts.isClassDeclaration(functionDeclaration.parent)) { - return !!functionDeclaration.body && !!functionDeclaration.parent.name && !checker.isImplementationOfOverload(functionDeclaration); + return !!functionDeclaration.body + && !!functionDeclaration.parent.name + && !checker.isImplementationOfOverload(functionDeclaration); } else { - return isValidVariableDeclaration(functionDeclaration.parent.parent) && !!functionDeclaration.body && !checker.isImplementationOfOverload(functionDeclaration); + return isValidVariableDeclaration(functionDeclaration.parent.parent) + && !!functionDeclaration.body + && !checker.isImplementationOfOverload(functionDeclaration); } case 196 /* FunctionExpression */: case 197 /* ArrowFunction */: @@ -119761,11 +119939,17 @@ var ts; } return false; } - function isValidParameterNodeArray(parameters) { - return getRefactorableParametersLength(parameters) >= minimumParameterLength && ts.every(parameters, isValidParameterDeclaration); + function isValidParameterNodeArray(parameters, checker) { + return getRefactorableParametersLength(parameters) >= minimumParameterLength + && ts.every(parameters, /*callback*/ function (/*callback*/ paramDecl) { return isValidParameterDeclaration(paramDecl, checker); }); } - function isValidParameterDeclaration(paramDeclaration) { - return !paramDeclaration.modifiers && !paramDeclaration.decorators && ts.isIdentifier(paramDeclaration.name); + function isValidParameterDeclaration(parameterDeclaration, checker) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + if (!checker.isArrayType(type) && !checker.isTupleType(type)) + return false; + } + return !parameterDeclaration.modifiers && !parameterDeclaration.decorators && ts.isIdentifier(parameterDeclaration.name); } function isValidVariableDeclaration(node) { return ts.isVariableDeclaration(node) && ts.isVarConst(node) && ts.isIdentifier(node.name) && !node.type; // TODO: GH#30113 @@ -119785,13 +119969,22 @@ var ts; } return parameters; } + function createPropertyOrShorthandAssignment(name, initializer) { + if (ts.isIdentifier(initializer) && ts.getTextOfIdentifierOrLiteral(initializer) === name) { + return ts.createShorthandPropertyAssignment(name); + } + return ts.createPropertyAssignment(name, initializer); + } function createNewArgument(functionDeclaration, functionArguments) { var parameters = getRefactorableParameters(functionDeclaration.parameters); var hasRestParameter = ts.isRestParameter(ts.last(parameters)); var nonRestArguments = hasRestParameter ? functionArguments.slice(0, parameters.length - 1) : functionArguments; var properties = ts.map(nonRestArguments, function (arg, i) { - var property = ts.createPropertyAssignment(getParameterName(parameters[i]), arg); - ts.suppressLeadingAndTrailingTrivia(property.initializer); + var parameterName = getParameterName(parameters[i]); + var property = createPropertyOrShorthandAssignment(parameterName, arg); + ts.suppressLeadingAndTrailingTrivia(property.name); + if (ts.isPropertyAssignment(property)) + ts.suppressLeadingAndTrailingTrivia(property.initializer); copyComments(arg, property); return property; }); @@ -119804,14 +119997,14 @@ var ts; return objectLiteral; } function createNewParameters(functionDeclaration, program, host) { + var checker = program.getTypeChecker(); var refactorableParameters = getRefactorableParameters(functionDeclaration.parameters); var bindingElements = ts.map(refactorableParameters, createBindingElementFromParameterDeclaration); var objectParameterName = ts.createObjectBindingPattern(bindingElements); var objectParameterType = createParameterTypeNode(refactorableParameters); - var checker = program.getTypeChecker(); var objectInitializer; // If every parameter in the original function was optional, add an empty object initializer to the new object parameter - if (ts.every(refactorableParameters, checker.isOptionalParameter)) { + if (ts.every(refactorableParameters, isOptionalParameter)) { objectInitializer = ts.createObjectLiteral(); } var objectParameter = ts.createParameter( @@ -119835,6 +120028,16 @@ var ts; return ts.createNodeArray([newThisParameter, objectParameter]); } return ts.createNodeArray([objectParameter]); + function createBindingElementFromParameterDeclaration(parameterDeclaration) { + var element = ts.createBindingElement( + /*dotDotDotToken*/ undefined, + /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) && isOptionalParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); + ts.suppressLeadingAndTrailingTrivia(element); + if (parameterDeclaration.initializer && element.initializer) { + copyComments(parameterDeclaration.initializer, element.initializer); + } + return element; + } function createParameterTypeNode(parameters) { var members = ts.map(parameters, createPropertySignatureFromParameterDeclaration); var typeNode = ts.addEmitFlags(ts.createTypeLiteralNode(members), 1 /* SingleLine */); @@ -119846,7 +120049,7 @@ var ts; parameterType = getTypeNode(parameterDeclaration); } var propertySignature = ts.createPropertySignature( - /*modifiers*/ undefined, getParameterName(parameterDeclaration), parameterDeclaration.initializer || ts.isRestParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, + /*modifiers*/ undefined, getParameterName(parameterDeclaration), isOptionalParameter(parameterDeclaration) ? ts.createToken(56 /* QuestionToken */) : parameterDeclaration.questionToken, parameterType, /*initializer*/ undefined); ts.suppressLeadingAndTrailingTrivia(propertySignature); copyComments(parameterDeclaration.name, propertySignature.name); @@ -119856,20 +120059,16 @@ var ts; return propertySignature; } function getTypeNode(node) { - var checker = program.getTypeChecker(); var type = checker.getTypeAtLocation(node); return ts.getTypeNodeIfAccessible(type, node, program, host); } - } - function createBindingElementFromParameterDeclaration(parameterDeclaration) { - var element = ts.createBindingElement( - /*dotDotDotToken*/ undefined, - /*propertyName*/ undefined, getParameterName(parameterDeclaration), ts.isRestParameter(parameterDeclaration) ? ts.createArrayLiteral() : parameterDeclaration.initializer); - ts.suppressLeadingAndTrailingTrivia(element); - if (parameterDeclaration.initializer && element.initializer) { - copyComments(parameterDeclaration.initializer, element.initializer); + function isOptionalParameter(parameterDeclaration) { + if (ts.isRestParameter(parameterDeclaration)) { + var type = checker.getTypeAtLocation(parameterDeclaration); + return !checker.isTupleType(type); + } + return checker.isOptionalParameter(parameterDeclaration); } - return element; } function copyComments(sourceNode, targetNode) { var sourceFile = sourceNode.getSourceFile(); @@ -120835,7 +121034,7 @@ var ts; function getValidSourceFile(fileName) { var sourceFile = program.getSourceFile(fileName); if (!sourceFile) { - throw new Error("Could not find file: '" + fileName + "'."); + throw new Error("Could not find sourceFile: '" + fileName + "' in " + (program && JSON.stringify(program.getSourceFiles().map(function (f) { return f.fileName; }))) + "."); } return sourceFile; } diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 7d963029b4d33..2a959a8a4126e 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -76,7 +76,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "3.4"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-rc"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { /* @internal */ @@ -31312,6 +31312,7 @@ var ts; return getResolvedSignatureWorker(node, candidatesOutArray, agumentCount, 16 /* IsForSignatureHelp */); }, getExpandedParameters: getExpandedParameters, + hasEffectiveRestParameter: hasEffectiveRestParameter, getConstantValue: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue); return node ? getConstantValue(node) : undefined; @@ -31373,6 +31374,8 @@ var ts; getNeverType: function () { return neverType; }, isSymbolAccessible: isSymbolAccessible, getObjectFlags: ts.getObjectFlags, + isArrayType: isArrayType, + isTupleType: isTupleType, isArrayLikeType: isArrayLikeType, isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant, getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes, @@ -32455,7 +32458,13 @@ var ts; // @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method. // } // - if (location.parent && ts.isClassElement(location.parent)) { + // class Decorators are resolved outside of the class to avoid referencing type parameters of that class. + // + // type T = number; + // declare function y(x: T): any; + // @param(1 as T) // <-- T should resolve to the type alias outside of class C + // class C {} + if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 240 /* ClassDeclaration */)) { location = location.parent; } break; @@ -33253,20 +33262,12 @@ var ts; return undefined; } if (moduleNotFoundError) { - // For relative paths, see if this was possibly a projectReference redirect - if (ts.pathIsRelative(moduleReference)) { - var sourceFile_1 = ts.getSourceFileOfNode(location); - var redirects = sourceFile_1.redirectedReferences; - if (redirects) { - var normalizedTargetPath = ts.getNormalizedAbsolutePath(moduleReference, ts.getDirectoryPath(sourceFile_1.fileName)); - for (var _i = 0, _a = [".ts" /* Ts */, ".tsx" /* Tsx */]; _i < _a.length; _i++) { - var ext = _a[_i]; - var probePath = normalizedTargetPath + ext; - if (redirects.indexOf(probePath) >= 0) { - error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, moduleReference, probePath); - return undefined; - } - } + // See if this was possibly a projectReference redirect + if (resolvedModule) { + var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName); + if (redirect) { + error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName); + return undefined; } } if (resolutionDiagnostic) { @@ -34298,8 +34299,8 @@ var ts; context.inferTypeParameters = type.root.inferTypeParameters; var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context); context.inferTypeParameters = saveInferTypeParameters; - var trueTypeNode = typeToTypeNodeHelper(getTrueTypeFromConditionalType(type), context); - var falseTypeNode = typeToTypeNodeHelper(getFalseTypeFromConditionalType(type), context); + var trueTypeNode = typeToTypeNodeHelper(type.trueType, context); + var falseTypeNode = typeToTypeNodeHelper(type.falseType, context); context.approximateLength += 15; return ts.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode); } @@ -36106,9 +36107,6 @@ var ts; } return type_1; } - if (declaration.kind === 254 /* ExportAssignment */) { - return widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); - } // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` @@ -36118,7 +36116,10 @@ var ts; return reportCircularityError(symbol); } var type; - if (ts.isInJSFile(declaration) && + if (declaration.kind === 254 /* ExportAssignment */) { + type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration); + } + else if (ts.isInJSFile(declaration) && (ts.isCallExpression(declaration) || ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) && ts.isBinaryExpression(declaration.parent))) { type = getWidenedTypeFromAssignmentDeclaration(symbol); } @@ -37643,6 +37644,15 @@ var ts; var stringIndexInfo = void 0; if (symbol.exports) { members = getExportsOfSymbol(symbol); + if (symbol === globalThisSymbol) { + var varsOnly_1 = ts.createMap(); + members.forEach(function (p) { + if (!(p.flags & 418 /* BlockScoped */)) { + varsOnly_1.set(p.escapedName, p); + } + }); + members = varsOnly_1; + } } setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined); if (symbol.flags & 32 /* Class */) { @@ -37975,6 +37985,9 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined; + } + function getConstraintFromIndexedAccess(type) { var objectType = getConstraintOfType(type.objectType) || type.objectType; if (objectType !== type.objectType) { var constraint = getIndexedAccessType(objectType, type.indexType, /*accessNode*/ undefined, errorType); @@ -37985,23 +37998,14 @@ var ts; var baseConstraint = getBaseConstraintOfType(type); return baseConstraint && baseConstraint !== type ? baseConstraint : undefined; } - function getDefaultConstraintOfTrueBranchOfConditionalType(root, combinedMapper, mapper) { - var rootTrueType = root.trueType; - var rootTrueConstraint = !(rootTrueType.flags & 33554432 /* Substitution */) - ? rootTrueType - : instantiateType((rootTrueType.substitute), combinedMapper || mapper).flags & 3 /* AnyOrUnknown */ - ? rootTrueType.typeVariable - : getIntersectionType([rootTrueType.substitute, rootTrueType.typeVariable]); - return instantiateType(rootTrueConstraint, combinedMapper || mapper); - } function getDefaultConstraintOfConditionalType(type) { if (!type.resolvedDefaultConstraint) { // An `any` branch of a conditional type would normally be viral - specifically, without special handling here, // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type, // in effect treating `any` like `never` rather than `unknown` in this location. - var trueConstraint = getDefaultConstraintOfTrueBranchOfConditionalType(type.root, type.combinedMapper, type.mapper); - var falseConstraint = getFalseTypeFromConditionalType(type); + var trueConstraint = getInferredTrueTypeFromConditionalType(type); + var falseConstraint = type.falseType; type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]); } return type.resolvedDefaultConstraint; @@ -38031,9 +38035,12 @@ var ts; } return undefined; } - function getConstraintOfConditionalType(type) { + function getConstraintFromConditionalType(type) { return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type); } + function getConstraintOfConditionalType(type) { + return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined; + } function getUnionConstraintOfIntersection(type, targetIsUnion) { var constraints; var hasDisjointDomainType = false; @@ -38107,7 +38114,7 @@ var ts; if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) { return circularConstraintType; } - if (constraintDepth === 50) { + if (constraintDepth >= 50) { // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a // very high likelyhood we're dealing with an infinite generic type that perpetually generates // new type identities as we descend into it. We stop the recursion here and mark this type @@ -38173,8 +38180,11 @@ var ts; return baseIndexedAccess && baseIndexedAccess !== errorType ? getBaseConstraint(baseIndexedAccess) : undefined; } if (t.flags & 16777216 /* Conditional */) { - var constraint = getConstraintOfConditionalType(t); - return constraint && getBaseConstraint(constraint); + var constraint = getConstraintFromConditionalType(t); + constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward) + var result = constraint && getBaseConstraint(constraint); + constraintDepth--; + return result; } if (t.flags & 33554432 /* Substitution */) { return getBaseConstraint(t.substitute); @@ -38261,7 +38271,7 @@ var ts; t; } function createUnionOrIntersectionProperty(containingType, name) { - var props; + var propSet = ts.createMap(); var indexTypes; var isUnion = containingType.flags & 1048576 /* Union */; var excludeModifiers = isUnion ? 24 /* NonPublicAccessibilityModifier */ : 0; @@ -38277,7 +38287,10 @@ var ts; var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0; if (prop && !(modifiers & excludeModifiers)) { commonFlags &= prop.flags; - props = ts.appendIfUnique(props, prop); + var id = "" + getSymbolId(prop); + if (!propSet.has(id)) { + propSet.set(id, prop); + } checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) | (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 128 /* ContainsPublic */ : 0) | (modifiers & 16 /* Protected */ ? 256 /* ContainsProtected */ : 0) | @@ -38299,9 +38312,10 @@ var ts; } } } - if (!props) { + if (!propSet.size) { return undefined; } + var props = ts.arrayFrom(propSet.values()); if (props.length === 1 && !(checkFlags & 16 /* Partial */) && !indexTypes) { return props[0]; } @@ -38744,32 +38758,23 @@ var ts; } } signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ? - createTypePredicateFromTypePredicateNode(type, signature.declaration) : + createTypePredicateFromTypePredicateNode(type, signature) : jsdocPredicate || noTypePredicate; } ts.Debug.assert(!!signature.resolvedTypePredicate); } return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate; } - function createTypePredicateFromTypePredicateNode(node, func) { + function createTypePredicateFromTypePredicateNode(node, signature) { var parameterName = node.parameterName; var type = getTypeFromTypeNode(node.type); if (parameterName.kind === 72 /* Identifier */) { - return createIdentifierTypePredicate(parameterName.escapedText, getTypePredicateParameterIndex(func.parameters, parameterName), type); + return createIdentifierTypePredicate(parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type); } else { return createThisTypePredicate(type); } } - function getTypePredicateParameterIndex(parameterList, parameter) { - for (var i = 0; i < parameterList.length; i++) { - var param = parameterList[i]; - if (param.name.kind === 72 /* Identifier */ && param.name.escapedText === parameter.escapedText) { - return i; - } - } - return -1; - } function getReturnTypeOfSignature(signature) { if (!signature.resolvedReturnType) { if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) { @@ -39246,6 +39251,9 @@ var ts; } } function getSubstitutionType(typeVariable, substitute) { + if (substitute.flags & 3 /* AnyOrUnknown */) { + return typeVariable; + } var result = createType(33554432 /* Substitution */); result.typeVariable = typeVariable; result.substitute = substitute; @@ -40224,7 +40232,10 @@ var ts; return anyType; } if (accessExpression && !isConstEnumObjectType(objectType)) { - if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { + if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) { + error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType)); + } + else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors) { if (propName !== undefined && typeHasStaticProperty(propName, objectType)) { error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType)); } @@ -40427,24 +40438,11 @@ var ts; var trueType = instantiateType(root.trueType, mapper); var falseType = instantiateType(root.falseType, mapper); var instantiationId = "" + (root.isDistributive ? "d" : "") + getTypeId(checkType) + ">" + getTypeId(extendsType) + "?" + getTypeId(trueType) + ":" + getTypeId(falseType); - if (conditionalTypes.has(instantiationId)) { - var result = conditionalTypes.get(instantiationId); - if (result !== undefined) { - return result; - } - // Somehow the conditional type depends on itself - usually via `infer` types in the `extends` clause - // paired with a (potentially deferred) circularly constrained type. - // The conditional _must_ be deferred. - var deferred = getDeferredConditionalType(root, mapper, /*combinedMapper*/ undefined, checkType, extendsType, trueType, falseType); - conditionalTypes.set(instantiationId, deferred); - return deferred; + var result = conditionalTypes.get(instantiationId); + if (result) { + return result; } - conditionalTypes.set(instantiationId, undefined); var newResult = getConditionalTypeWorker(root, mapper, checkType, extendsType, trueType, falseType); - var cachedRecursiveResult = conditionalTypes.get(instantiationId); - if (cachedRecursiveResult) { - return cachedRecursiveResult; - } conditionalTypes.set(instantiationId, newResult); return newResult; } @@ -40452,7 +40450,7 @@ var ts; // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`. if (falseType.flags & 131072 /* Never */ && isTypeIdenticalTo(getActualTypeVariable(trueType), getActualTypeVariable(checkType))) { if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true - return getDefaultConstraintOfTrueBranchOfConditionalType(root, /*combinedMapper*/ undefined, mapper); + return trueType; } else if (isIntersectionEmpty(checkType, extendsType)) { // Always false return neverType; @@ -40463,7 +40461,7 @@ var ts; return neverType; } else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false - return falseType; // TODO: Intersect negated `extends` type here + return falseType; } } var checkTypeInstantiable = maybeTypeOfKind(checkType, 63176704 /* Instantiable */ | 131072 /* GenericMappedType */); @@ -40516,19 +40514,14 @@ var ts; result.extendsType = extendsType; result.mapper = mapper; result.combinedMapper = combinedMapper; - if (!combinedMapper) { - result.resolvedTrueType = trueType; - result.resolvedFalseType = falseType; - } + result.trueType = trueType; + result.falseType = falseType; result.aliasSymbol = root.aliasSymbol; result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217 return result; } - function getTrueTypeFromConditionalType(type) { - return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(type.root.trueType, type.mapper)); - } - function getFalseTypeFromConditionalType(type) { - return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(type.root.falseType, type.mapper)); + function getInferredTrueTypeFromConditionalType(type) { + return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = instantiateType(type.root.trueType, type.combinedMapper || type.mapper)); } function getInferTypeParameters(node) { var result; @@ -41389,7 +41382,11 @@ var ts; return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper)); } else { - return maybeVariable; + var sub = instantiateType(type.substitute, mapper); + if (sub.flags & 3 /* AnyOrUnknown */ || isTypeSubtypeOf(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) { + return maybeVariable; + } + return sub; } } return type; @@ -41946,6 +41943,14 @@ var ts; return compareSignaturesRelated(source, target, 0 /* None */, ignoreReturnTypes, /*reportErrors*/ false, /*errorReporter*/ undefined, compareTypesAssignable) !== 0 /* False */; } + /** + * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any` + */ + function isAnySignature(s) { + return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && + s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + isTypeAny(getReturnTypeOfSignature(s)); + } /** * See signatureRelatedTo, compareSignaturesIdentical */ @@ -41954,6 +41959,9 @@ var ts; if (source === target) { return -1 /* True */; } + if (isAnySignature(target)) { + return -1 /* True */; + } var targetCount = getParameterCount(target); if (!hasEffectiveRestParameter(target) && getMinArgumentCount(source) > targetCount) { return 0 /* False */; @@ -42031,7 +42039,7 @@ var ts; if (targetTypePredicate) { var sourceTypePredicate = getTypePredicateOfSignature(source); if (sourceTypePredicate) { - result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, source.declaration, target.declaration, reportErrors, errorReporter, compareTypes); // TODO: GH#18217 + result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes); } else if (ts.isIdentifierTypePredicate(targetTypePredicate)) { if (reportErrors) { @@ -42050,7 +42058,7 @@ var ts; } return result; } - function compareTypePredicateRelatedTo(source, target, sourceDeclaration, targetDeclaration, reportErrors, errorReporter, compareTypes) { + function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) { if (source.kind !== target.kind) { if (reportErrors) { errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard); @@ -42059,12 +42067,9 @@ var ts; return 0 /* False */; } if (source.kind === 1 /* Identifier */) { - var targetPredicate = target; - var sourceIndex = source.parameterIndex - (ts.getThisParameter(sourceDeclaration) ? 1 : 0); - var targetIndex = targetPredicate.parameterIndex - (ts.getThisParameter(targetDeclaration) ? 1 : 0); - if (sourceIndex !== targetIndex) { + if (source.parameterIndex !== target.parameterIndex) { if (reportErrors) { - errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, targetPredicate.parameterName); + errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName); errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target)); } return 0 /* False */; @@ -42872,8 +42877,8 @@ var ts; if (source.root.isDistributive === target.root.isDistributive) { if (result_3 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) { if (result_3 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) { - if (result_3 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.trueType, target.trueType, /*reportErrors*/ false)) { + if (result_3 &= isRelatedTo(source.falseType, target.falseType, /*reportErrors*/ false)) { return result_3; } } @@ -43022,8 +43027,8 @@ var ts; // and Y1 is related to Y2. if (isTypeIdenticalTo(source.extendsType, target.extendsType) && (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) { - if (result = isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), reportErrors)) { - result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors); + if (result = isRelatedTo(source.trueType, target.trueType, reportErrors)) { + result &= isRelatedTo(source.falseType, target.falseType, reportErrors); } if (result) { errorInfo = saveErrorInfo; @@ -44348,7 +44353,7 @@ var ts; } } } - function forEachMatchingParameterType(source, target, callback) { + function applyToParameterTypes(source, target, callback) { var sourceCount = getParameterCount(source); var targetCount = getParameterCount(target); var sourceRestType = getEffectiveRestType(source); @@ -44369,6 +44374,17 @@ var ts; callback(getRestTypeAtPosition(source, paramCount), targetRestType); } } + function applyToReturnTypes(source, target, callback) { + var sourceTypePredicate = getTypePredicateOfSignature(source); + var targetTypePredicate = getTypePredicateOfSignature(target); + if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind && + (sourceTypePredicate.kind === 0 /* This */ || sourceTypePredicate.parameterIndex === targetTypePredicate.parameterIndex)) { + callback(sourceTypePredicate.type, targetTypePredicate.type); + } + else { + callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); + } + } function createInferenceContext(typeParameters, signature, flags, compareTypes) { return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable); } @@ -44583,11 +44599,11 @@ var ts; inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : emptyObjectType; } - function inferTypes(inferences, originalSource, originalTarget, priority) { + function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) { if (priority === void 0) { priority = 0; } + if (contravariant === void 0) { contravariant = false; } var symbolStack; var visited; - var contravariant = false; var bivariant = false; var propagationType; var allowComplexConstraintInference = true; @@ -44679,9 +44695,11 @@ var ts; var candidate = propagationType || source; // We make contravariant inferences only if we are in a pure contravariant position, // i.e. only if we have not descended into a bivariant position. - if (contravariant && !bivariant && !ts.contains(inference.contraCandidates, candidate)) { - inference.contraCandidates = ts.append(inference.contraCandidates, candidate); - inference.inferredType = undefined; + if (contravariant && !bivariant) { + if (!ts.contains(inference.contraCandidates, candidate)) { + inference.contraCandidates = ts.append(inference.contraCandidates, candidate); + inference.inferredType = undefined; + } } else if (!ts.contains(inference.candidates, candidate)) { inference.candidates = ts.append(inference.candidates, candidate); @@ -44753,12 +44771,12 @@ var ts; else if (source.flags & 16777216 /* Conditional */ && target.flags & 16777216 /* Conditional */) { inferFromTypes(source.checkType, target.checkType); inferFromTypes(source.extendsType, target.extendsType); - inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target)); - inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target)); + inferFromTypes(source.trueType, target.trueType); + inferFromTypes(source.falseType, target.falseType); } else if (target.flags & 16777216 /* Conditional */ && !contravariant) { - inferFromTypes(source, getTrueTypeFromConditionalType(target)); - inferFromTypes(source, getFalseTypeFromConditionalType(target)); + inferFromTypes(source, target.trueType); + inferFromTypes(source, target.falseType); } else if (target.flags & 3145728 /* UnionOrIntersection */) { for (var _d = 0, _e = target.types; _d < _e.length; _d++) { @@ -44982,17 +45000,10 @@ var ts; var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */; // Once we descend into a bivariant signature we remain bivariant for all nested inferences bivariant = bivariant || kind === 156 /* MethodDeclaration */ || kind === 155 /* MethodSignature */ || kind === 157 /* Constructor */; - forEachMatchingParameterType(source, target, inferFromContravariantTypes); + applyToParameterTypes(source, target, inferFromContravariantTypes); bivariant = saveBivariant; } - var sourceTypePredicate = getTypePredicateOfSignature(source); - var targetTypePredicate = getTypePredicateOfSignature(target); - if (sourceTypePredicate && targetTypePredicate && sourceTypePredicate.kind === targetTypePredicate.kind) { - inferFromTypes(sourceTypePredicate.type, targetTypePredicate.type); - } - else { - inferFromTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target)); - } + applyToReturnTypes(source, target, inferFromTypes); } function inferFromIndexTypes(source, target) { var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */); @@ -46540,7 +46551,7 @@ var ts; return type; } if (ts.isIdentifierTypePredicate(predicate)) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex - (signature.thisParameter ? 1 : 0)]; + var predicateArgument = callExpression.arguments[predicate.parameterIndex]; if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); @@ -49194,7 +49205,10 @@ var ts; return anyType; } if (leftType.symbol === globalThisSymbol) { - if (noImplicitAny) { + if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) { + error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType)); + } + else if (noImplicitAny) { error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType)); } return anyType; @@ -49773,18 +49787,14 @@ var ts; var restType = getEffectiveRestType(contextualSignature); var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper); var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature; - forEachMatchingParameterType(sourceSignature, signature, function (source, target) { + applyToParameterTypes(sourceSignature, signature, function (source, target) { // Type parameters from outer context referenced by source type are fixed by instantiation of the source type inferTypes(context.inferences, source, target); }); if (!inferenceContext) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); - var signaturePredicate = getTypePredicateOfSignature(signature); - var contextualPredicate = getTypePredicateOfSignature(sourceSignature); - if (signaturePredicate && contextualPredicate && signaturePredicate.kind === contextualPredicate.kind && - (signaturePredicate.kind === 0 /* This */ || signaturePredicate.parameterIndex === contextualPredicate.parameterIndex)) { - inferTypes(context.inferences, contextualPredicate.type, signaturePredicate.type, 8 /* ReturnType */); - } + applyToReturnTypes(contextualSignature, signature, function (source, target) { + inferTypes(context.inferences, source, target, 8 /* ReturnType */); + }); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration)); } @@ -52808,23 +52818,30 @@ var ts; // potentially add inferred type parameters to the outer function return type. var returnSignature = context.signature && getSingleCallSignature(getReturnTypeOfSignature(context.signature)); if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) { - // Instantiate the expression type with its own type parameters as type arguments. This - // ensures that the type parameters are not erased to type any during type inference such - // that they can be inferred as actual types. + // Instantiate the signature with its own type parameters as type arguments, possibly + // renaming the type parameters to ensure they have unique names. var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters); - var strippedType = getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters)); - // Infer from the stripped expression type to the contextual type starting with an empty - // set of inference candidates. - var inferences = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); - inferTypes(inferences, strippedType, contextualType); - // If we produced some inference candidates and if the type parameters for which we produced - // candidates do not already have existing inferences, we adopt the new inference candidates and - // add the type parameters of the expression type to the set of inferred type parameters for - // the outer function return type. - if (ts.some(inferences, hasInferenceCandidates) && !hasOverlappingInferences(context.inferences, inferences)) { - mergeInferences(context.inferences, inferences); - context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); - return strippedType; + var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters); + // Infer from the parameters of the instantiated signature to the parameters of the + // contextual signature starting with an empty set of inference candidates. + var inferences_2 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); }); + applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target, /*priority*/ 0, /*contravariant*/ true); + }); + if (ts.some(inferences_2, hasInferenceCandidates)) { + // We have inference candidates, indicating that one or more type parameters are referenced + // in the parameter types of the contextual signature. Now also infer from the return type. + applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) { + inferTypes(inferences_2, source, target); + }); + // If the type parameters for which we produced candidates do not have any inferences yet, + // we adopt the new inference candidates and add the type parameters of the expression type + // to the set of inferred type parameters for the outer function return type. + if (!hasOverlappingInferences(context.inferences, inferences_2)) { + mergeInferences(context.inferences, inferences_2); + context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters); + return getOrCreateTypeFromSignature(instantiatedSignature); + } } } return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context)); @@ -53147,7 +53164,8 @@ var ts; error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods); return; } - var typePredicate = getTypePredicateOfSignature(getSignatureFromDeclaration(parent)); + var signature = getSignatureFromDeclaration(parent); + var typePredicate = getTypePredicateOfSignature(signature); if (!typePredicate) { return; } @@ -53158,12 +53176,12 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (parent.parameters[typePredicate.parameterIndex].dotDotDotToken) { + if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; - checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, + checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } } @@ -56821,8 +56839,8 @@ var ts; var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. if (symbol.flags & 512 /* ValueModule */ - && symbol.declarations.length > 1 && !inAmbientContext + && symbol.declarations.length > 1 && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) { var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol); if (firstNonAmbientClassOrFunc) { @@ -68334,11 +68352,14 @@ var ts; var decorators; if (node) { var parameters = node.parameters; - for (var i = 0; i < parameters.length; i++) { - var parameter = parameters[i]; + var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]); + var firstParameterOffset = firstParameterIsThis ? 1 : 0; + var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length; + for (var i = 0; i < numParameters; i++) { + var parameter = parameters[i + firstParameterOffset]; if (decorators || parameter.decorators) { if (!decorators) { - decorators = new Array(parameters.length); + decorators = new Array(numParameters); } decorators[i] = parameter.decorators; } @@ -70468,8 +70489,10 @@ var ts; } var savedCapturedSuperProperties = capturedSuperProperties; var savedHasSuperElementAccess = hasSuperElementAccess; - capturedSuperProperties = ts.createUnderscoreEscapedMap(); - hasSuperElementAccess = false; + if (!isArrowFunction) { + capturedSuperProperties = ts.createUnderscoreEscapedMap(); + hasSuperElementAccess = false; + } var result; if (!isArrowFunction) { var statements = []; @@ -70481,9 +70504,11 @@ var ts; var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */); if (emitSuperHelpers) { enableSubstitutionForAsyncMethodsWithSuper(); - var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); - substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; - ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + if (ts.hasEntries(capturedSuperProperties)) { + var variableStatement = createSuperAccessVariableStatement(resolver, node, capturedSuperProperties); + substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true; + ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]); + } } var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -70510,8 +70535,10 @@ var ts; } } enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; - capturedSuperProperties = savedCapturedSuperProperties; - hasSuperElementAccess = savedHasSuperElementAccess; + if (!isArrowFunction) { + capturedSuperProperties = savedCapturedSuperProperties; + hasSuperElementAccess = savedHasSuperElementAccess; + } return result; } function transformAsyncFunctionBodyWorker(body, start) { @@ -70664,7 +70691,7 @@ var ts; /* typeParameters */ undefined, /* parameters */ [], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createPropertyAccess(ts.createSuper(), name)))); + /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */)))); if (hasBinding) { getterAndSetter.push(ts.createPropertyAssignment("set", ts.createArrowFunction( /* modifiers */ undefined, @@ -70679,7 +70706,7 @@ var ts; /* initializer */ undefined) ], /* type */ undefined, - /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.createPropertyAccess(ts.createSuper(), name), ts.createIdentifier("v"))))); + /* equalsGreaterThanToken */ undefined, ts.createAssignment(ts.setEmitFlags(ts.createPropertyAccess(ts.setEmitFlags(ts.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), ts.createIdentifier("v"))))); } accessors.push(ts.createPropertyAssignment(name, ts.createObjectLiteral(getterAndSetter))); }); @@ -87724,11 +87751,7 @@ var ts; function createCompilerHostWorker(options, setParentNodes, system) { if (system === void 0) { system = ts.sys; } var existingDirectories = ts.createMap(); - function getCanonicalFileName(fileName) { - // if underlying system can distinguish between two files whose names differs only in cases then file name already in canonical form. - // otherwise use toLowerCase as a canonical form. - return system.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - } + var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); function getSourceFile(fileName, languageVersion, onError) { var text; try { @@ -89599,7 +89622,6 @@ var ts; if (refFile) { var redirect = getProjectReferenceRedirect(fileName); if (redirect) { - (refFile.redirectedReferences || (refFile.redirectedReferences = [])).push(fileName); fileName = redirect; // Once we start redirecting to a file, we can potentially come back to it // via a back-reference from another file in the .d.ts folder. If that happens we'll @@ -90591,7 +90613,7 @@ var ts; // Create the reference map, and set the file infos for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { var sourceFile = _a[_i]; - var version_1 = sourceFile.version; + var version_1 = ts.Debug.assertDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set"); var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.path) : undefined; if (referencedMap) { var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); @@ -91600,8 +91622,8 @@ var ts; } var diagnostics; for (var _i = 0, _a = ts.Debug.assertDefined(state.program).getSourceFiles(); _i < _a.length; _i++) { - var sourceFile_2 = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_2, cancellationToken)); + var sourceFile_1 = _a[_i]; + diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken)); } return diagnostics || ts.emptyArray; } @@ -93062,6 +93084,32 @@ var ts; return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program); } ts.readBuilderProgram = readBuilderProgram; + function createIncrementalCompilerHost(options, system) { + if (system === void 0) { system = ts.sys; } + var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system); + host.createHash = ts.maybeBind(system, system.createHash); + setGetSourceFileAsHashVersioned(host, system); + ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); }); + return host; + } + ts.createIncrementalCompilerHost = createIncrementalCompilerHost; + function createIncrementalProgram(_a) { + var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram; + host = host || createIncrementalCompilerHost(options); + createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram; + var oldProgram = readBuilderProgram(options, function (path) { return host.readFile(path); }); + return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + } + function performIncrementalCompilation(input) { + var system = input.system || ts.sys; + var host = input.host || (input.host = createIncrementalCompilerHost(input.options, system)); + var builderProgram = createIncrementalProgram(input); + var exitStatus = emitFilesAndReportErrors(builderProgram, input.reportDiagnostic || createDiagnosticReporter(system), function (s) { return host.trace && host.trace(s); }, input.reportErrorSummary || input.options.pretty ? function (errorCount) { return system.write(getErrorSummaryText(errorCount, system.newLine)); } : undefined); + if (input.afterProgramEmitAndDiagnostics) + input.afterProgramEmitAndDiagnostics(builderProgram); + return exitStatus; + } + ts.performIncrementalCompilation = performIncrementalCompilation; })(ts || (ts = {})); (function (ts) { function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferences) { @@ -93979,6 +94027,16 @@ var ts; newerInputFileName: newestInputFileName }; } + else { + // Check tsconfig time + var configStatus = checkConfigFileUpToDateStatus(project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName); + if (configStatus) + return configStatus; + // Check extended config time + var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName); }); + if (extendedConfigStatus) + return extendedConfigStatus; + } if (!buildInfoChecked.hasKey(project.options.configFilePath)) { buildInfoChecked.setValue(project.options.configFilePath, true); var buildInfoPath = ts.getOutputPathForBuildInfo(project.options); @@ -94011,6 +94069,17 @@ var ts; oldestOutputFileName: oldestOutputFileName }; } + function checkConfigFileUpToDateStatus(configFile, oldestOutputFileTime, oldestOutputFileName) { + // Check tsconfig time + var tsconfigTime = host.getModifiedTime(configFile) || ts.missingFileModifiedTime; + if (oldestOutputFileTime < tsconfigTime) { + return { + type: UpToDateStatusType.OutOfDateWithSelf, + outOfDateOutputFileName: oldestOutputFileName, + newerInputFileName: configFile + }; + } + } function invalidateProject(configFileName, reloadLevel) { invalidateResolvedProject(resolveProjectName(configFileName), reloadLevel); } @@ -94321,6 +94390,8 @@ var ts; } } function getOldProgram(proj, parsed) { + if (options.force) + return undefined; var value = builderPrograms.getValue(proj); if (value) return value;