ngth; i++) {
        const related = compareSignaturesIdentical(
          sourceSignatures[i],
          targetSignatures[i],
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          false,
          /*ignoreReturnTypes*/
          false,
          isRelatedTo
        );
        if (!related) {
          return 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function membersRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState) {
      let result2 = -1 /* True */;
      const keyType = targetInfo.keyType;
      const props = source2.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source2) : getPropertiesOfObjectType(source2);
      for (const prop of props) {
        if (isIgnoredJsxProperty(source2, prop)) {
          continue;
        }
        if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), keyType)) {
          const propType = getNonMissingTypeOfSymbol(prop);
          const type = exactOptionalPropertyTypes || propType.flags & 32768 /* Undefined */ || keyType === numberType || !(prop.flags & 16777216 /* Optional */) ? propType : getTypeWithFacts(propType, 524288 /* NEUndefined */);
          const related = isRelatedTo(
            type,
            targetInfo.type,
            3 /* Both */,
            reportErrors2,
            /*headMessage*/
            void 0,
            intersectionState
          );
          if (!related) {
            if (reportErrors2) {
              reportError(Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
            }
            return 0 /* False */;
          }
          result2 &= related;
        }
      }
      for (const info of getIndexInfosOfType(source2)) {
        if (isApplicableIndexType(info.keyType, keyType)) {
          const related = indexInfoRelatedTo(info, targetInfo, reportErrors2, intersectionState);
          if (!related) {
            return 0 /* False */;
          }
          result2 &= related;
        }
      }
      return result2;
    }
    function indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors2, intersectionState) {
      const related = isRelatedTo(
        sourceInfo.type,
        targetInfo.type,
        3 /* Both */,
        reportErrors2,
        /*headMessage*/
        void 0,
        intersectionState
      );
      if (!related && reportErrors2) {
        if (sourceInfo.keyType === targetInfo.keyType) {
          reportError(Diagnostics._0_index_signatures_are_incompatible, typeToString(sourceInfo.keyType));
        } else {
          reportError(Diagnostics._0_and_1_index_signatures_are_incompatible, typeToString(sourceInfo.keyType), typeToString(targetInfo.keyType));
        }
      }
      return related;
    }
    function indexSignaturesRelatedTo(source2, target2, sourceIsPrimitive, reportErrors2, intersectionState) {
      if (relation === identityRelation) {
        return indexSignaturesIdenticalTo(source2, target2);
      }
      const indexInfos = getIndexInfosOfType(target2);
      const targetHasStringIndex = some(indexInfos, (info) => info.keyType === stringType);
      let result2 = -1 /* True */;
      for (const targetInfo of indexInfos) {
        const related = relation !== strictSubtypeRelation && !sourceIsPrimitive && targetHasStringIndex && targetInfo.type.flags & 1 /* Any */ ? -1 /* True */ : isGenericMappedType(source2) && targetHasStringIndex ? isRelatedTo(getTemplateTypeFromMappedType(source2), targetInfo.type, 3 /* Both */, reportErrors2) : typeRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState);
        if (!related) {
          return 0 /* False */;
        }
        result2 &= related;
      }
      return result2;
    }
    function typeRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState) {
      const sourceInfo = getApplicableIndexInfo(source2, targetInfo.keyType);
      if (sourceInfo) {
        return indexInfoRelatedTo(sourceInfo, targetInfo, reportErrors2, intersectionState);
      }
      if (!(intersectionState & 1 /* Source */) && (relation !== strictSubtypeRelation || getObjectFlags(source2) & 8192 /* FreshLiteral */) && isObjectTypeWithInferableIndex(source2)) {
        return membersRelatedToIndexInfo(source2, targetInfo, reportErrors2, intersectionState);
      }
      if (reportErrors2) {
        reportError(Diagnostics.Index_signature_for_type_0_is_missing_in_type_1, typeToString(targetInfo.keyType), typeToString(source2));
      }
      return 0 /* False */;
    }
    function indexSignaturesIdenticalTo(source2, target2) {
      const sourceInfos = getIndexInfosOfType(source2);
      const targetInfos = getIndexInfosOfType(target2);
      if (sourceInfos.length !== targetInfos.length) {
        return 0 /* False */;
      }
      for (const targetInfo of targetInfos) {
        const sourceInfo = getIndexInfoOfType(source2, targetInfo.keyType);
        if (!(sourceInfo && isRelatedTo(sourceInfo.type, targetInfo.type, 3 /* Both */) && sourceInfo.isReadonly === targetInfo.isReadonly)) {
          return 0 /* False */;
        }
      }
      return -1 /* True */;
    }
    function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors2) {
      if (!sourceSignature.declaration || !targetSignature.declaration) {
        return true;
      }
      const sourceAccessibility = getSelectedEffectiveModifierFlags(sourceSignature.declaration, 6 /* NonPublicAccessibilityModifier */);
      const targetAccessibility = getSelectedEffectiveModifierFlags(targetSignature.declaration, 6 /* NonPublicAccessibilityModifier */);
      if (targetAccessibility === 2 /* Private */) {
        return true;
      }
      if (targetAccessibility === 4 /* Protected */ && sourceAccessibility !== 2 /* Private */) {
        return true;
      }
      if (targetAccessibility !== 4 /* Protected */ && !sourceAccessibility) {
        return true;
      }
      if (reportErrors2) {
        reportError(Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
      }
      return false;
    }
  }
  function typeCouldHaveTopLevelSingletonTypes(type) {
    if (type.flags & 16 /* Boolean */) {
      return false;
    }
    if (type.flags & 3145728 /* UnionOrIntersection */) {
      return !!forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
    }
    if (type.flags & 465829888 /* Instantiable */) {
      const constraint = getConstraintOfType(type);
      if (constraint && constraint !== type) {
        return typeCouldHaveTopLevelSingletonTypes(constraint);
      }
    }
    return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */) || !!(type.flags & 268435456 /* StringMapping */);
  }
  function getExactOptionalUnassignableProperties(source, target) {
    if (isTupleType(source) && isTupleType(target)) return emptyArray;
    return getPropertiesOfType(target).filter((targetProp) => isExactOptionalPropertyMismatch(getTypeOfPropertyOfType(source, targetProp.escapedName), getTypeOfSymbol(targetProp)));
  }
  function isExactOptionalPropertyMismatch(source, target) {
    return !!source && !!target && maybeTypeOfKind(source, 32768 /* Undefined */) && !!containsMissingType(target);
  }
  function getExactOptionalProperties(type) {
    return getPropertiesOfType(type).filter((targetProp) => containsMissingType(getTypeOfSymbol(targetProp)));
  }
  function getBestMatchingType(source, target, isRelatedTo = compareTypesAssignable) {
    return findMatchingDiscriminantType(source, target, isRelatedTo) || findMatchingTypeReferenceOrTypeAliasReference(source, target) || findBestTypeForObjectLiteral(source, target) || findBestTypeForInvokable(source, target) || findMostOverlappyType(source, target);
  }
  function discriminateTypeByDiscriminableItems(target, discriminators, related) {
    const types = target.types;
    const include = types.map((t) => t.flags & 402784252 /* Primitive */ ? 0 /* False */ : -1 /* True */);
    for (const [getDiscriminatingType, propertyName] of discriminators) {
      let matched = false;
      for (let i = 0; i < types.length; i++) {
        if (include[i]) {
          const targetType = getTypeOfPropertyOrIndexSignatureOfType(types[i], propertyName);
          if (targetType && someType(getDiscriminatingType(), (t) => !!related(t, targetType))) {
            matched = true;
          } else {
            include[i] = 3 /* Maybe */;
          }
        }
      }
      for (let i = 0; i < types.length; i++) {
        if (include[i] === 3 /* Maybe */) {
          include[i] = matched ? 0 /* False */ : -1 /* True */;
        }
      }
    }
    const filtered = contains(include, 0 /* False */) ? getUnionType(types.filter((_, i) => include[i]), 0 /* None */) : target;
    return filtered.flags & 131072 /* Never */ ? target : filtered;
  }
  function isWeakType(type) {
    if (type.flags & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 && resolved.indexInfos.length === 0 && resolved.properties.length > 0 && every(resolved.properties, (p) => !!(p.flags & 16777216 /* Optional */));
    }
    if (type.flags & 33554432 /* Substitution */) {
      return isWeakType(type.baseType);
    }
    if (type.flags & 2097152 /* Intersection */) {
      return every(type.types, isWeakType);
    }
    return false;
  }
  function hasCommonProperties(source, target, isComparingJsxAttributes) {
    for (const prop of getPropertiesOfType(source)) {
      if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
        return true;
      }
    }
    return false;
  }
  function getVariances(type) {
    return type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */ ? arrayVariances : getVariancesWorker(type.symbol, type.typeParameters);
  }
  function getAliasVariances(symbol) {
    return getVariancesWorker(symbol, getSymbolLinks(symbol).typeParameters);
  }
  function getVariancesWorker(symbol, typeParameters = emptyArray) {
    var _a, _b;
    const links = getSymbolLinks(symbol);
    if (!links.variances) {
      (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "getVariancesWorker", { arity: typeParameters.length, id: getTypeId(getDeclaredTypeOfSymbol(symbol)) });
      const oldVarianceComputation = inVarianceComputation;
      const saveResolutionStart = resolutionStart;
      if (!inVarianceComputation) {
        inVarianceComputation = true;
        resolutionStart = resolutionTargets.length;
      }
      links.variances = emptyArray;
      const variances = [];
      for (const tp of typeParameters) {
        const modifiers = getTypeParameterModifiers(tp);
        let variance = modifiers & 16384 /* Out */ ? modifiers & 8192 /* In */ ? 0 /* Invariant */ : 1 /* Covariant */ : modifiers & 8192 /* In */ ? 2 /* Contravariant */ : void 0;
        if (variance === void 0) {
          let unmeasurable = false;
          let unreliable = false;
          const oldHandler = outofbandVarianceMarkerHandler;
          outofbandVarianceMarkerHandler = (onlyUnreliable) => onlyUnreliable ? unreliable = true : unmeasurable = true;
          const typeWithSuper = createMarkerType(symbol, tp, markerSuperType);
          const typeWithSub = createMarkerType(symbol, tp, markerSubType);
          variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) | (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
          if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(symbol, tp, markerOtherType), typeWithSuper)) {
            variance = 4 /* Independent */;
          }
          outofbandVarianceMarkerHandler = oldHandler;
          if (unmeasurable || unreliable) {
            if (unmeasurable) {
              variance |= 8 /* Unmeasurable */;
            }
            if (unreliable) {
              variance |= 16 /* Unreliable */;
            }
          }
        }
        variances.push(variance);
      }
      if (!oldVarianceComputation) {
        inVarianceComputation = false;
        resolutionStart = saveResolutionStart;
      }
      links.variances = variances;
      (_b = tracing) == null ? void 0 : _b.pop({ variances: variances.map(Debug.formatVariance) });
    }
    return links.variances;
  }
  function createMarkerType(symbol, source, target) {
    const mapper = makeUnaryTypeMapper(source, target);
    const type = getDeclaredTypeOfSymbol(symbol);
    if (isErrorType(type)) {
      return type;
    }
    const result = symbol.flags & 524288 /* TypeAlias */ ? getTypeAliasInstantiation(symbol, instantiateTypes(getSymbolLinks(symbol).typeParameters, mapper)) : createTypeReference(type, instantiateTypes(type.typeParameters, mapper));
    markerTypes.add(getTypeId(result));
    return result;
  }
  function isMarkerType(type) {
    return markerTypes.has(getTypeId(type));
  }
  function getTypeParameterModifiers(tp) {
    var _a;
    return reduceLeft((_a = tp.symbol) == null ? void 0 : _a.declarations, (modifiers, d) => modifiers | getEffectiveModifierFlags(d), 0 /* None */) & (8192 /* In */ | 16384 /* Out */ | 4096 /* Const */);
  }
  function hasCovariantVoidArgument(typeArguments, variances) {
    for (let i = 0; i < variances.length; i++) {
      if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
        return true;
      }
    }
    return false;
  }
  function isUnconstrainedTypeParameter(type) {
    return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
  }
  function isNonDeferredTypeReference(type) {
    return !!(getObjectFlags(type) & 4 /* Reference */) && !type.node;
  }
  function isTypeReferenceWithGenericArguments(type) {
    return isNonDeferredTypeReference(type) && some(getTypeArguments(type), (t) => !!(t.flags & 262144 /* TypeParameter */) || isTypeReferenceWithGenericArguments(t));
  }
  function getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) {
    const typeParameters = [];
    let constraintMarker = "";
    const sourceId = getTypeReferenceId(source, 0);
    const targetId = getTypeReferenceId(target, 0);
    return `${constraintMarker}${sourceId},${targetId}${postFix}`;
    function getTypeReferenceId(type, depth = 0) {
      let result = "" + type.target.id;
      for (const t of getTypeArguments(type)) {
        if (t.flags & 262144 /* TypeParameter */) {
          if (ignoreConstraints || isUnconstrainedTypeParameter(t)) {
            let index = typeParameters.indexOf(t);
            if (index < 0) {
              index = typeParameters.length;
              typeParameters.push(t);
            }
            result += "=" + index;
            continue;
          }
          constraintMarker = "*";
        } else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
          result += "<" + getTypeReferenceId(t, depth + 1) + ">";
          continue;
        }
        result += "-" + t.id;
      }
      return result;
    }
  }
  function getRelationKey(source, target, intersectionState, relation, ignoreConstraints) {
    if (relation === identityRelation && source.id > target.id) {
      const temp = source;
      source = target;
      target = temp;
    }
    const postFix = intersectionState ? ":" + intersectionState : "";
    return isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target) ? getGenericTypeReferenceRelationKey(source, target, postFix, ignoreConstraints) : `${source.id},${target.id}${postFix}`;
  }
  function forEachProperty(prop, callback) {
    if (getCheckFlags(prop) & 6 /* Synthetic */) {
      for (const t of prop.links.containingType.types) {
        const p = getPropertyOfType(t, prop.escapedName);
        const result = p && forEachProperty(p, callback);
        if (result) {
          return result;
        }
      }
      return void 0;
    }
    return callback(prop);
  }
  function getDeclaringClass(prop) {
    return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : void 0;
  }
  function getTypeOfPropertyInBaseClass(property) {
    const classType = getDeclaringClass(property);
    const baseClassType = classType && getBaseTypes(classType)[0];
    return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName);
  }
  function isPropertyInClassDerivedFrom(prop, baseClass) {
    return forEachProperty(prop, (sp) => {
      const sourceClass = getDeclaringClass(sp);
      return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
    });
  }
  function isValidOverrideOf(sourceProp, targetProp) {
    return !forEachProperty(targetProp, (tp) => getDeclarationModifierFlagsFromSymbol(tp) & 4 /* Protected */ ? !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false);
  }
  function isClassDerivedFromDeclaringClasses(checkClass, prop, writing) {
    return forEachProperty(prop, (p) => getDeclarationModifierFlagsFromSymbol(p, writing) & 4 /* Protected */ ? !hasBaseType(checkClass, getDeclaringClass(p)) : false) ? void 0 : checkClass;
  }
  function isDeeplyNestedType(type, stack, depth, maxDepth = 3) {
    if (depth >= maxDepth) {
      if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) {
        type = getMappedTargetWithSymbol(type);
      }
      if (type.flags & 2097152 /* Intersection */) {
        return some(type.types, (t) => isDeeplyNestedType(t, stack, depth, maxDepth));
      }
      const identity2 = getRecursionIdentity(type);
      let count = 0;
      let lastTypeId = 0;
      for (let i = 0; i < depth; i++) {
        const t = stack[i];
        if (hasMatchingRecursionIdentity(t, identity2)) {
          if (t.id >= lastTypeId) {
            count++;
            if (count >= maxDepth) {
              return true;
            }
          }
          lastTypeId = t.id;
        }
      }
    }
    return false;
  }
  function getMappedTargetWithSymbol(type) {
    let target;
    while ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */ && (target = getModifiersTypeFromMappedType(type)) && (target.symbol || target.flags & 2097152 /* Intersection */ && some(target.types, (t) => !!t.symbol))) {
      type = target;
    }
    return type;
  }
  function hasMatchingRecursionIdentity(type, identity2) {
    if ((getObjectFlags(type) & 96 /* InstantiatedMapped */) === 96 /* InstantiatedMapped */) {
      type = getMappedTargetWithSymbol(type);
    }
    if (type.flags & 2097152 /* Intersection */) {
      return some(type.types, (t) => hasMatchingRecursionIdentity(t, identity2));
    }
    return getRecursionIdentity(type) === identity2;
  }
  function getRecursionIdentity(type) {
    if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
      if (getObjectFlags(type) & 4 /* Reference */ && type.node) {
        return type.node;
      }
      if (type.symbol && !(getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */)) {
        return type.symbol;
      }
      if (isTupleType(type)) {
        return type.target;
      }
    }
    if (type.flags & 262144 /* TypeParameter */) {
      return type.symbol;
    }
    if (type.flags & 8388608 /* IndexedAccess */) {
      do {
        type = type.objectType;
      } while (type.flags & 8388608 /* IndexedAccess */);
      return type;
    }
    if (type.flags & 16777216 /* Conditional */) {
      return type.root;
    }
    return type;
  }
  function isPropertyIdenticalTo(sourceProp, targetProp) {
    return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
  }
  function compareProperties(sourceProp, targetProp, compareTypes) {
    if (sourceProp === targetProp) {
      return -1 /* True */;
    }
    const sourcePropAccessibility = getDeclarationModifierFlagsFromSymbol(sourceProp) & 6 /* NonPublicAccessibilityModifier */;
    const targetPropAccessibility = getDeclarationModifierFlagsFromSymbol(targetProp) & 6 /* NonPublicAccessibilityModifier */;
    if (sourcePropAccessibility !== targetPropAccessibility) {
      return 0 /* False */;
    }
    if (sourcePropAccessibility) {
      if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
        return 0 /* False */;
      }
    } else {
      if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
        return 0 /* False */;
      }
    }
    if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
      return 0 /* False */;
    }
    return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
  }
  function isMatchingSignature(source, target, partialMatch) {
    const sourceParameterCount = getParameterCount(source);
    const targetParameterCount = getParameterCount(target);
    const sourceMinArgumentCount = getMinArgumentCount(source);
    const targetMinArgumentCount = getMinArgumentCount(target);
    const sourceHasRestParameter = hasEffectiveRestParameter(source);
    const targetHasRestParameter = hasEffectiveRestParameter(target);
    if (sourceParameterCount === targetParameterCount && sourceMinArgumentCount === targetMinArgumentCount && sourceHasRestParameter === targetHasRestParameter) {
      return true;
    }
    if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
      return true;
    }
    return false;
  }
  function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
    if (source === target) {
      return -1 /* True */;
    }
    if (!isMatchingSignature(source, target, partialMatch)) {
      return 0 /* False */;
    }
    if (length(source.typeParameters) !== length(target.typeParameters)) {
      return 0 /* False */;
    }
    if (target.typeParameters) {
      const mapper = createTypeMapper(source.typeParameters, target.typeParameters);
      for (let i = 0; i < target.typeParameters.length; i++) {
        const s = source.typeParameters[i];
        const t = target.typeParameters[i];
        if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) && compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
          return 0 /* False */;
        }
      }
      source = instantiateSignature(
        source,
        mapper,
        /*eraseTypeParameters*/
        true
      );
    }
    let result = -1 /* True */;
    if (!ignoreThisTypes) {
      const sourceThisType = getThisTypeOfSignature(source);
      if (sourceThisType) {
        const targetThisType = getThisTypeOfSignature(target);
        if (targetThisType) {
          const related = compareTypes(sourceThisType, targetThisType);
          if (!related) {
            return 0 /* False */;
          }
          result &= related;
        }
      }
    }
    const targetLen = getParameterCount(target);
    for (let i = 0; i < targetLen; i++) {
      const s = getTypeAtPosition(source, i);
      const t = getTypeAtPosition(target, i);
      const related = compareTypes(t, s);
      if (!related) {
        return 0 /* False */;
      }
      result &= related;
    }
    if (!ignoreReturnTypes) {
      const sourceTypePredicate = getTypePredicateOfSignature(source);
      const targetTypePredicate = getTypePredicateOfSignature(target);
      result &= sourceTypePredicate || targetTypePredicate ? compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) : compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
    }
    return result;
  }
  function compareTypePredicatesIdentical(source, target, compareTypes) {
    return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ : source.type === target.type ? -1 /* True */ : source.type && target.type ? compareTypes(source.type, target.type) : 0 /* False */;
  }
  function literalTypesWithSameBaseType(types) {
    let commonBaseType;
    for (const t of types) {
      if (!(t.flags & 131072 /* Never */)) {
        const baseType = getBaseTypeOfLiteralType(t);
        commonBaseType ?? (commonBaseType = baseType);
        if (baseType === t || baseType !== commonBaseType) {
          return false;
        }
      }
    }
    return true;
  }
  function getCombinedTypeFlags(types) {
    return reduceLeft(types, (flags, t) => flags | (t.flags & 1048576 /* Union */ ? getCombinedTypeFlags(t.types) : t.flags), 0);
  }
  function getCommonSupertype(types) {
    if (types.length === 1) {
      return types[0];
    }
    const primaryTypes = strictNullChecks ? sameMap(types, (t) => filterType(t, (u) => !(u.flags & 98304 /* Nullable */))) : types;
    const superTypeOrUnion = literalTypesWithSameBaseType(primaryTypes) ? getUnionType(primaryTypes) : reduceLeft(primaryTypes, (s, t) => isTypeSubtypeOf(s, t) ? t : s);
    return primaryTypes === types ? superTypeOrUnion : getNullableType(superTypeOrUnion, getCombinedTypeFlags(types) & 98304 /* Nullable */);
  }
  function getCommonSubtype(types) {
    return reduceLeft(types, (s, t) => isTypeSubtypeOf(t, s) ? t : s);
  }
  function isArrayType(type) {
    return !!(getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
  }
  function isReadonlyArrayType(type) {
    return !!(getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
  }
  function isArrayOrTupleType(type) {
    return isArrayType(type) || isTupleType(type);
  }
  function isMutableArrayOrTuple(type) {
    return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
  }
  function getElementTypeOfArrayType(type) {
    return isArrayType(type) ? getTypeArguments(type)[0] : void 0;
  }
  function isArrayLikeType(type) {
    return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
  }
  function isMutableArrayLikeType(type) {
    return isMutableArrayOrTuple(type) || !(type.flags & (1 /* Any */ | 98304 /* Nullable */)) && isTypeAssignableTo(type, anyArrayType);
  }
  function getSingleBaseForNonAugmentingSubtype(type) {
    if (!(getObjectFlags(type) & 4 /* Reference */) || !(getObjectFlags(type.target) & 3 /* ClassOrInterface */)) {
      return void 0;
    }
    if (getObjectFlags(type) & 33554432 /* IdenticalBaseTypeCalculated */) {
      return getObjectFlags(type) & 67108864 /* IdenticalBaseTypeExists */ ? type.cachedEquivalentBaseType : void 0;
    }
    type.objectFlags |= 33554432 /* IdenticalBaseTypeCalculated */;
    const target = type.target;
    if (getObjectFlags(target) & 1 /* Class */) {
      const baseTypeNode = getBaseTypeNodeOfClass(target);
      if (baseTypeNode && baseTypeNode.expression.kind !== 80 /* Identifier */ && baseTypeNode.expression.kind !== 211 /* PropertyAccessExpression */) {
        return void 0;
      }
    }
    const bases = getBaseTypes(target);
    if (bases.length !== 1) {
      return void 0;
    }
    if (getMembersOfSymbol(type.symbol).size) {
      return void 0;
    }
    let instantiatedBase = !length(target.typeParameters) ? bases[0] : instantiateType(bases[0], createTypeMapper(target.typeParameters, getTypeArguments(type).slice(0, target.typeParameters.length)));
    if (length(getTypeArguments(type)) > length(target.typeParameters)) {
      instantiatedBase = getTypeWithThisArgument(instantiatedBase, last(getTypeArguments(type)));
    }
    type.objectFlags |= 67108864 /* IdenticalBaseTypeExists */;
    return type.cachedEquivalentBaseType = instantiatedBase;
  }
  function isEmptyLiteralType(type) {
    return strictNullChecks ? type === implicitNeverType : type === undefinedWideningType;
  }
  function isEmptyArrayLiteralType(type) {
    const elementType = getElementTypeOfArrayType(type);
    return !!elementType && isEmptyLiteralType(elementType);
  }
  function isTupleLikeType(type) {
    let lengthType;
    return isTupleType(type) || !!getPropertyOfType(type, "0") || isArrayLikeType(type) && !!(lengthType = getTypeOfPropertyOfType(type, "length")) && everyType(lengthType, (t) => !!(t.flags & 256 /* NumberLiteral */));
  }
  function isArrayOrTupleLikeType(type) {
    return isArrayLikeType(type) || isTupleLikeType(type);
  }
  function getTupleElementType(type, index) {
    const propType = getTypeOfPropertyOfType(type, "" + index);
    if (propType) {
      return propType;
    }
    if (everyType(type, isTupleType)) {
      return getTupleElementTypeOutOfStartCount(type, index, compilerOptions.noUncheckedIndexedAccess ? undefinedType : void 0);
    }
    return void 0;
  }
  function isNeitherUnitTypeNorNever(type) {
    return !(type.flags & (109472 /* Unit */ | 131072 /* Never */));
  }
  function isUnitType(type) {
    return !!(type.flags & 109472 /* Unit */);
  }
  function isUnitLikeType(type) {
    const t = getBaseConstraintOrType(type);
    return t.flags & 2097152 /* Intersection */ ? some(t.types, isUnitType) : isUnitType(t);
  }
  function extractUnitType(type) {
    return type.flags & 2097152 /* Intersection */ ? find(type.types, isUnitType) || type : type;
  }
  function isLiteralType(type) {
    return type.flags & 16 /* Boolean */ ? true : type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : every(type.types, isUnitType) : isUnitType(type);
  }
  function getBaseTypeOfLiteralType(type) {
    return type.flags & 1056 /* EnumLike */ ? getBaseTypeOfEnumLikeType(type) : type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & 256 /* NumberLiteral */ ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? getBaseTypeOfLiteralTypeUnion(type) : type;
  }
  function getBaseTypeOfLiteralTypeUnion(type) {
    const key = `B${getTypeId(type)}`;
    return getCachedType(key) ?? setCachedType(key, mapType(type, getBaseTypeOfLiteralType));
  }
  function getBaseTypeOfLiteralTypeForComparison(type) {
    return type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? stringType : type.flags & (256 /* NumberLiteral */ | 32 /* Enum */) ? numberType : type.flags & 2048 /* BigIntLiteral */ ? bigintType : type.flags & 512 /* BooleanLiteral */ ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getBaseTypeOfLiteralTypeForComparison) : type;
  }
  function getWidenedLiteralType(type) {
    return type.flags & 1056 /* EnumLike */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLikeType(type) : type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType : type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType : type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType : type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType : type.flags & 1048576 /* Union */ ? mapType(type, getWidenedLiteralType) : type;
  }
  function getWidenedUniqueESSymbolType(type) {
    return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType : type.flags & 1048576 /* Union */ ? mapType(type, getWidenedUniqueESSymbolType) : type;
  }
  function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
    if (!isLiteralOfContextualType(type, contextualType)) {
      type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
    }
    return getRegularTypeOfLiteralType(type);
  }
  function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
    if (type && isUnitType(type)) {
      const contextualType = !contextualSignatureReturnType ? void 0 : isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) : contextualSignatureReturnType;
      type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
    }
    return type;
  }
  function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
    if (type && isUnitType(type)) {
      const contextualType = !contextualSignatureReturnType ? void 0 : getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
      type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
    }
    return type;
  }
  function isTupleType(type) {
    return !!(getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
  }
  function isGenericTupleType(type) {
    return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */);
  }
  function isSingleElementGenericTupleType(type) {
    return isGenericTupleType(type) && type.target.elementFlags.length === 1;
  }
  function getRestTypeOfTupleType(type) {
    return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength);
  }
  function getTupleElementTypeOutOfStartCount(type, index, undefinedOrMissingType2) {
    return mapType(type, (t) => {
      const tupleType = t;
      const restType = getRestTypeOfTupleType(tupleType);
      if (!restType) {
        return undefinedType;
      }
      if (undefinedOrMissingType2 && index >= getTotalFixedElementCount(tupleType.target)) {
        return getUnionType([restType, undefinedOrMissingType2]);
      }
      return restType;
    });
  }
  function getRestArrayTypeOfTupleType(type) {
    const restType = getRestTypeOfTupleType(type);
    return restType && createArrayType(restType);
  }
  function getElementTypeOfSliceOfTupleType(type, index, endSkipCount = 0, writing = false, noReductions = false) {
    const length2 = getTypeReferenceArity(type) - endSkipCount;
    if (index < length2) {
      const typeArguments = getTypeArguments(type);
      const elementTypes = [];
      for (let i = index; i < length2; i++) {
        const t = typeArguments[i];
        elementTypes.push(type.target.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
      }
      return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
    }
    return void 0;
  }
  function isTupleTypeStructureMatching(t1, t2) {
    return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) && every(t1.target.elementFlags, (f, i) => (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */));
  }
  function isZeroBigInt({ value }) {
    return value.base10Value === "0";
  }
  function removeDefinitelyFalsyTypes(type) {
    return filterType(type, (t) => hasTypeFacts(t, 4194304 /* Truthy */));
  }
  function extractDefinitelyFalsyTypes(type) {
    return mapType(type, getDefinitelyFalsyPartOfType);
  }
  function getDefinitelyFalsyPartOfType(type) {
    return type.flags & 4 /* String */ ? emptyStringType : type.flags & 8 /* Number */ ? zeroType : type.flags & 64 /* BigInt */ ? zeroBigIntType : type === regularFalseType || type === falseType || type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */ | 3 /* AnyOrUnknown */) || type.flags & 128 /* StringLiteral */ && type.value === "" || type.flags & 256 /* NumberLiteral */ && type.value === 0 || type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type : neverType;
  }
  function getNullableType(type, flags) {
    const missing = flags & ~type.flags & (32768 /* Undefined */ | 65536 /* Null */);
    return missing === 0 ? type : missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) : missing === 65536 /* Null */ ? getUnionType([type, nullType]) : getUnionType([type, undefinedType, nullType]);
  }
  function getOptionalType(type, isProperty = false) {
    Debug.assert(strictNullChecks);
    const missingOrUndefined = isProperty ? undefinedOrMissingType : undefinedType;
    return type === missingOrUndefined || type.flags & 1048576 /* Union */ && type.types[0] === missingOrUndefined ? type : getUnionType([type, missingOrUndefined]);
  }
  function getGlobalNonNullableTypeInstantiation(type) {
    if (!deferredGlobalNonNullableTypeAlias) {
      deferredGlobalNonNullableTypeAlias = getGlobalSymbol(
        "NonNullable",
        524288 /* TypeAlias */,
        /*diagnostic*/
        void 0
      ) || unknownSymbol;
    }
    return deferredGlobalNonNullableTypeAlias !== unknownSymbol ? getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]) : getIntersectionType([type, emptyObjectType]);
  }
  function getNonNullableType(type) {
    return strictNullChecks ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
  }
  function addOptionalTypeMarker(type) {
    return strictNullChecks ? getUnionType([type, optionalType]) : type;
  }
  function removeOptionalTypeMarker(type) {
    return strictNullChecks ? removeType(type, optionalType) : type;
  }
  function propagateOptionalTypeMarker(type, node, wasOptional) {
    return wasOptional ? isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
  }
  function getOptionalExpressionType(exprType, expression) {
    return isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : exprType;
  }
  function removeMissingType(type, isOptional) {
    return exactOptionalPropertyTypes && isOptional ? removeType(type, missingType) : type;
  }
  function containsMissingType(type) {
    return type === missingType || !!(type.flags & 1048576 /* Union */) && type.types[0] === missingType;
  }
  function removeMissingOrUndefinedType(type) {
    return exactOptionalPropertyTypes ? removeType(type, missingType) : getTypeWithFacts(type, 524288 /* NEUndefined */);
  }
  function isCoercibleUnderDoubleEquals(source, target) {
    return (source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0 && (target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0;
  }
  function isObjectTypeWithInferableIndex(type) {
    const objectFlags = getObjectFlags(type);
    return type.flags & 2097152 /* Intersection */ ? every(type.types, isObjectTypeWithInferableIndex) : !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 && !(type.symbol.flags & 32 /* Class */) && !typeHasCallOrConstructSignatures(type)) || !!(objectFlags & 4194304 /* ObjectRestType */) || !!(objectFlags & 1024 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
  }
  function createSymbolWithType(source, type) {
    const symbol = createSymbol(source.flags, source.escapedName, getCheckFlags(source) & 8 /* Readonly */);
    symbol.declarations = source.declarations;
    symbol.parent = source.parent;
    symbol.links.type = type;
    symbol.links.target = source;
    if (source.valueDeclaration) {
      symbol.valueDeclaration = source.valueDeclaration;
    }
    const nameType = getSymbolLinks(source).nameType;
    if (nameType) {
      symbol.links.nameType = nameType;
    }
    return symbol;
  }
  function transformTypeOfMembers(type, f) {
    const members = createSymbolTable();
    for (const property of getPropertiesOfObjectType(type)) {
      const original = getTypeOfSymbol(property);
      const updated = f(original);
      members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
    }
    return members;
  }
  function getRegularTypeOfObjectLiteral(type) {
    if (!(isObjectLiteralType(type) && getObjectFlags(type) & 8192 /* FreshLiteral */)) {
      return type;
    }
    const regularType = type.regularType;
    if (regularType) {
      return regularType;
    }
    const resolved = type;
    const members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
    const regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.indexInfos);
    regularNew.flags = resolved.flags;
    regularNew.objectFlags |= resolved.objectFlags & ~8192 /* FreshLiteral */;
    type.regularType = regularNew;
    return regularNew;
  }
  function createWideningContext(parent, propertyName, siblings) {
    return { parent, propertyName, siblings, resolvedProperties: void 0 };
  }
  function getSiblingsOfContext(context) {
    if (!context.siblings) {
      const siblings = [];
      for (const type of getSiblingsOfContext(context.parent)) {
        if (isObjectLiteralType(type)) {
          const prop = getPropertyOfObjectType(type, context.propertyName);
          if (prop) {
            forEachType(getTypeOfSymbol(prop), (t) => {
              siblings.push(t);
            });
          }
        }
      }
      context.siblings = siblings;
    }
    return context.siblings;
  }
  function getPropertiesOfContext(context) {
    if (!context.resolvedProperties) {
      const names = /* @__PURE__ */ new Map();
      for (const t of getSiblingsOfContext(context)) {
        if (isObjectLiteralType(t) && !(getObjectFlags(t) & 2097152 /* ContainsSpread */)) {
          for (const prop of getPropertiesOfType(t)) {
            names.set(prop.escapedName, prop);
          }
        }
      }
      context.resolvedProperties = arrayFrom(names.values());
    }
    return context.resolvedProperties;
  }
  function getWidenedProperty(prop, context) {
    if (!(prop.flags & 4 /* Property */)) {
      return prop;
    }
    const original = getTypeOfSymbol(prop);
    const propContext = context && createWideningContext(
      context,
      prop.escapedName,
      /*siblings*/
      void 0
    );
    const widened = getWidenedTypeWithContext(original, propContext);
    return widened === original ? prop : createSymbolWithType(prop, widened);
  }
  function getUndefinedProperty(prop) {
    const cached = undefinedProperties.get(prop.escapedName);
    if (cached) {
      return cached;
    }
    const result = createSymbolWithType(prop, undefinedOrMissingType);
    result.flags |= 16777216 /* Optional */;
    undefinedProperties.set(prop.escapedName, result);
    return result;
  }
  function getWidenedTypeOfObjectLiteral(type, context) {
    const members = createSymbolTable();
    for (const prop of getPropertiesOfObjectType(type)) {
      members.set(prop.escapedName, getWidenedProperty(prop, context));
    }
    if (context) {
      for (const prop of getPropertiesOfContext(context)) {
        if (!members.has(prop.escapedName)) {
          members.set(prop.escapedName, getUndefinedProperty(prop));
        }
      }
    }
    const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, sameMap(getIndexInfosOfType(type), (info) => createIndexInfo(info.keyType, getWidenedType(info.type), info.isReadonly)));
    result.objectFlags |= getObjectFlags(type) & (4096 /* JSLiteral */ | 262144 /* NonInferrableType */);
    return result;
  }
  function getWidenedType(type) {
    return getWidenedTypeWithContext(
      type,
      /*context*/
      void 0
    );
  }
  function getWidenedTypeWithContext(type, context) {
    if (getObjectFlags(type) & 196608 /* RequiresWidening */) {
      if (context === void 0 && type.widened) {
        return type.widened;
      }
      let result;
      if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
        result = anyType;
      } else if (isObjectLiteralType(type)) {
        result = getWidenedTypeOfObjectLiteral(type, context);
      } else if (type.flags & 1048576 /* Union */) {
        const unionContext = context || createWideningContext(
          /*parent*/
          void 0,
          /*propertyName*/
          void 0,
          type.types
        );
        const widenedTypes = sameMap(type.types, (t) => t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext));
        result = getUnionType(widenedTypes, some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
      } else if (type.flags & 2097152 /* Intersection */) {
        result = getIntersectionType(sameMap(type.types, getWidenedType));
      } else if (isArrayOrTupleType(type)) {
        result = createTypeReference(type.target, sameMap(getTypeArguments(type), getWidenedType));
      }
      if (result && context === void 0) {
        type.widened = result;
      }
      return result || type;
    }
    return type;
  }
  function reportWideningErrorsInType(type) {
    var _a;
    let errorReported = false;
    if (getObjectFlags(type) & 65536 /* ContainsWideningType */) {
      if (type.flags & 1048576 /* Union */) {
        if (some(type.types, isEmptyObjectType)) {
          errorReported = true;
        } else {
          for (const t of type.types) {
            errorReported || (errorReported = reportWideningErrorsInType(t));
          }
        }
      } else if (isArrayOrTupleType(type)) {
        for (const t of getTypeArguments(type)) {
          errorReported || (errorReported = reportWideningErrorsInType(t));
        }
      } else if (isObjectLiteralType(type)) {
        for (const p of getPropertiesOfObjectType(type)) {
          const t = getTypeOfSymbol(p);
          if (getObjectFlags(t) & 65536 /* ContainsWideningType */) {
            errorReported = reportWideningErrorsInType(t);
            if (!errorReported) {
              const valueDeclaration = (_a = p.declarations) == null ? void 0 : _a.find((d) => {
                var _a2;
                return ((_a2 = d.symbol.valueDeclaration) == null ? void 0 : _a2.parent) === type.symbol.valueDeclaration;
              });
              if (valueDeclaration) {
                error(valueDeclaration, Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
                errorReported = true;
              }
            }
          }
        }
      }
    }
    return errorReported;
  }
  function reportImplicitAny(declaration, type, wideningKind) {
    const typeAsString = typeToString(getWidenedType(type));
    if (isInJSFile(declaration) && !isCheckJsEnabledForFile(getSourceFileOfNode(declaration), compilerOptions)) {
      return;
    }
    let diagnostic;
    switch (declaration.kind) {
      case 226 /* BinaryExpression */:
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
        diagnostic = noImplicitAny ? Diagnostics.Member_0_implicitly_has_an_1_type : Diagnostics.Member_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
        break;
      case 169 /* Parameter */:
        const param = declaration;
        if (isIdentifier(param.name)) {
          const originalKeywordKind = identifierToKeywordKind(param.name);
          if ((isCallSignatureDeclaration(param.parent) || isMethodSignature(param.parent) || isFunctionTypeNode(param.parent)) && param.parent.parameters.includes(param) && (resolveName(
            param,
            param.name.escapedText,
            788968 /* Type */,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            true
          ) || originalKeywordKind && isTypeNodeKind(originalKeywordKind))) {
            const newName = "arg" + param.parent.parameters.indexOf(param);
            const typeName = declarationNameToString(param.name) + (param.dotDotDotToken ? "[]" : "");
            errorOrSuggestion(noImplicitAny, declaration, Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, typeName);
            return;
          }
        }
        diagnostic = declaration.dotDotDotToken ? noImplicitAny ? Diagnostics.Rest_parameter_0_implicitly_has_an_any_type : Diagnostics.Rest_parameter_0_implicitly_has_an_any_type_but_a_better_type_may_be_inferred_from_usage : noImplicitAny ? Diagnostics.Parameter_0_implicitly_has_an_1_type : Diagnostics.Parameter_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
        break;
      case 208 /* BindingElement */:
        diagnostic = Diagnostics.Binding_element_0_implicitly_has_an_1_type;
        if (!noImplicitAny) {
          return;
        }
        break;
      case 317 /* JSDocFunctionType */:
        error(declaration, Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
        return;
      case 323 /* JSDocSignature */:
        if (noImplicitAny && isJSDocOverloadTag(declaration.parent)) {
          error(declaration.parent.tagName, Diagnostics.This_overload_implicitly_returns_the_type_0_because_it_lacks_a_return_type_annotation, typeAsString);
        }
        return;
      case 262 /* FunctionDeclaration */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        if (noImplicitAny && !declaration.name) {
          if (wideningKind === 3 /* GeneratorYield */) {
            error(declaration, Diagnostics.Generator_implicitly_has_yield_type_0_Consider_supplying_a_return_type_annotation, typeAsString);
          } else {
            error(declaration, Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
          }
          return;
        }
        diagnostic = !noImplicitAny ? Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage : wideningKind === 3 /* GeneratorYield */ ? Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type : Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
        break;
      case 200 /* MappedType */:
        if (noImplicitAny) {
          error(declaration, Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
        }
        return;
      default:
        diagnostic = noImplicitAny ? Diagnostics.Variable_0_implicitly_has_an_1_type : Diagnostics.Variable_0_implicitly_has_an_1_type_but_a_better_type_may_be_inferred_from_usage;
    }
    errorOrSuggestion(noImplicitAny, declaration, diagnostic, declarationNameToString(getNameOfDeclaration(declaration)), typeAsString);
  }
  function shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind) {
    const signature = getContextualSignatureForFunctionLikeDeclaration(declaration);
    if (!signature) {
      return true;
    }
    let returnType = getReturnTypeOfSignature(signature);
    const flags = getFunctionFlags(declaration);
    switch (wideningKind) {
      case 1 /* FunctionReturn */:
        if (flags & 1 /* Generator */) {
          returnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, !!(flags & 2 /* Async */)) ?? returnType;
        } else if (flags & 2 /* Async */) {
          returnType = getAwaitedTypeNoAlias(returnType) ?? returnType;
        }
        return isGenericType(returnType);
      case 3 /* GeneratorYield */:
        const yieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, !!(flags & 2 /* Async */));
        return !!yieldType && isGenericType(yieldType);
      case 2 /* GeneratorNext */:
        const nextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, !!(flags & 2 /* Async */));
        return !!nextType && isGenericType(nextType);
    }
    return false;
  }
  function reportErrorsFromWidening(declaration, type, wideningKind) {
    addLazyDiagnostic(() => {
      if (noImplicitAny && getObjectFlags(type) & 65536 /* ContainsWideningType */) {
        if (!wideningKind || isFunctionLikeDeclaration(declaration) && shouldReportErrorsFromWideningWithContextualSignature(declaration, wideningKind)) {
          if (!reportWideningErrorsInType(type)) {
            reportImplicitAny(declaration, type, wideningKind);
          }
        }
      }
    });
  }
  function applyToParameterTypes(source, target, callback) {
    const sourceCount = getParameterCount(source);
    const targetCount = getParameterCount(target);
    const sourceRestType = getEffectiveRestType(source);
    const targetRestType = getEffectiveRestType(target);
    const targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
    const paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
    const sourceThisType = getThisTypeOfSignature(source);
    if (sourceThisType) {
      const targetThisType = getThisTypeOfSignature(target);
      if (targetThisType) {
        callback(sourceThisType, targetThisType);
      }
    }
    for (let i = 0; i < paramCount; i++) {
      callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
    }
    if (targetRestType) {
      callback(getRestTypeAtPosition(
        source,
        paramCount,
        /*readonly*/
        isConstTypeVariable(targetRestType) && !someType(targetRestType, isMutableArrayLikeType)
      ), targetRestType);
    }
  }
  function applyToReturnTypes(source, target, callback) {
    const targetTypePredicate = getTypePredicateOfSignature(target);
    if (targetTypePredicate) {
      const sourceTypePredicate = getTypePredicateOfSignature(source);
      if (sourceTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
        callback(sourceTypePredicate.type, targetTypePredicate.type);
        return;
      }
    }
    const targetReturnType = getReturnTypeOfSignature(target);
    if (couldContainTypeVariables(targetReturnType)) {
      callback(getReturnTypeOfSignature(source), targetReturnType);
    }
  }
  function createInferenceContext(typeParameters, signature, flags, compareTypes) {
    return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
  }
  function cloneInferenceContext(context, extraFlags = 0) {
    return context && createInferenceContextWorker(map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
  }
  function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
    const context = {
      inferences,
      signature,
      flags,
      compareTypes,
      mapper: reportUnmeasurableMapper,
      // initialize to a noop mapper so the context object is available, but the underlying object shape is right upon construction
      nonFixingMapper: reportUnmeasurableMapper
    };
    context.mapper = makeFixingMapperForContext(context);
    context.nonFixingMapper = makeNonFixingMapperForContext(context);
    return context;
  }
  function makeFixingMapperForContext(context) {
    return makeDeferredTypeMapper(
      map(context.inferences, (i) => i.typeParameter),
      map(context.inferences, (inference, i) => () => {
        if (!inference.isFixed) {
          inferFromIntraExpressionSites(context);
          clearCachedInferences(context.inferences);
          inference.isFixed = true;
        }
        return getInferredType(context, i);
      })
    );
  }
  function makeNonFixingMapperForContext(context) {
    return makeDeferredTypeMapper(
      map(context.inferences, (i) => i.typeParameter),
      map(context.inferences, (_, i) => () => {
        return getInferredType(context, i);
      })
    );
  }
  function clearCachedInferences(inferences) {
    for (const inference of inferences) {
      if (!inference.isFixed) {
        inference.inferredType = void 0;
      }
    }
  }
  function addIntraExpressionInferenceSite(context, node, type) {
    (context.intraExpressionInferenceSites ?? (context.intraExpressionInferenceSites = [])).push({ node, type });
  }
  function inferFromIntraExpressionSites(context) {
    if (context.intraExpressionInferenceSites) {
      for (const { node, type } of context.intraExpressionInferenceSites) {
        const contextualType = node.kind === 174 /* MethodDeclaration */ ? getContextualTypeForObjectLiteralMethod(node, 2 /* NoConstraints */) : getContextualType(node, 2 /* NoConstraints */);
        if (contextualType) {
          inferTypes(context.inferences, type, contextualType);
        }
      }
      context.intraExpressionInferenceSites = void 0;
    }
  }
  function createInferenceInfo(typeParameter) {
    return {
      typeParameter,
      candidates: void 0,
      contraCandidates: void 0,
      inferredType: void 0,
      priority: void 0,
      topLevel: true,
      isFixed: false,
      impliedArity: void 0
    };
  }
  function cloneInferenceInfo(inference) {
    return {
      typeParameter: inference.typeParameter,
      candidates: inference.candidates && inference.candidates.slice(),
      contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
      inferredType: inference.inferredType,
      priority: inference.priority,
      topLevel: inference.topLevel,
      isFixed: inference.isFixed,
      impliedArity: inference.impliedArity
    };
  }
  function cloneInferredPartOfContext(context) {
    const inferences = filter(context.inferences, hasInferenceCandidates);
    return inferences.length ? createInferenceContextWorker(map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) : void 0;
  }
  function getMapperFromContext(context) {
    return context && context.mapper;
  }
  function couldContainTypeVariables(type) {
    const objectFlags = getObjectFlags(type);
    if (objectFlags & 524288 /* CouldContainTypeVariablesComputed */) {
      return !!(objectFlags & 1048576 /* CouldContainTypeVariables */);
    }
    const result = !!(type.flags & 465829888 /* Instantiable */ || type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || some(getTypeArguments(type), couldContainTypeVariables)) || objectFlags & 134217728 /* SingleSignatureType */ && !!length(type.outerTypeParameters) || objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations || objectFlags & (32 /* Mapped */ | 1024 /* ReverseMapped */ | 4194304 /* ObjectRestType */ | 8388608 /* InstantiationExpressionType */)) || type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && some(type.types, couldContainTypeVariables));
    if (type.flags & 3899393 /* ObjectFlagsType */) {
      type.objectFlags |= 524288 /* CouldContainTypeVariablesComputed */ | (result ? 1048576 /* CouldContainTypeVariables */ : 0);
    }
    return result;
  }
  function isNonGenericTopLevelType(type) {
    if (type.aliasSymbol && !type.aliasTypeArguments) {
      const declaration = getDeclarationOfKind(type.aliasSymbol, 265 /* TypeAliasDeclaration */);
      return !!(declaration && findAncestor(declaration.parent, (n) => n.kind === 307 /* SourceFile */ ? true : n.kind === 267 /* ModuleDeclaration */ ? false : "quit"));
    }
    return false;
  }
  function isTypeParameterAtTopLevel(type, tp, depth = 0) {
    return !!(type === tp || type.flags & 3145728 /* UnionOrIntersection */ && some(type.types, (t) => isTypeParameterAtTopLevel(t, tp, depth)) || depth < 3 && type.flags & 16777216 /* Conditional */ && (isTypeParameterAtTopLevel(getTrueTypeFromConditionalType(type), tp, depth + 1) || isTypeParameterAtTopLevel(getFalseTypeFromConditionalType(type), tp, depth + 1)));
  }
  function isTypeParameterAtTopLevelInReturnType(signature, typeParameter) {
    const typePredicate = getTypePredicateOfSignature(signature);
    return typePredicate ? !!typePredicate.type && isTypeParameterAtTopLevel(typePredicate.type, typeParameter) : isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), typeParameter);
  }
  function createEmptyObjectTypeFromStringLiteral(type) {
    const members = createSymbolTable();
    forEachType(type, (t) => {
      if (!(t.flags & 128 /* StringLiteral */)) {
        return;
      }
      const name = escapeLeadingUnderscores(t.value);
      const literalProp = createSymbol(4 /* Property */, name);
      literalProp.links.type = anyType;
      if (t.symbol) {
        literalProp.declarations = t.symbol.declarations;
        literalProp.valueDeclaration = t.symbol.valueDeclaration;
      }
      members.set(name, literalProp);
    });
    const indexInfos = type.flags & 4 /* String */ ? [createIndexInfo(
      stringType,
      emptyObjectType,
      /*isReadonly*/
      false
    )] : emptyArray;
    return createAnonymousType(
      /*symbol*/
      void 0,
      members,
      emptyArray,
      emptyArray,
      indexInfos
    );
  }
  function inferTypeForHomomorphicMappedType(source, target, constraint) {
    const cacheKey = source.id + "," + target.id + "," + constraint.id;
    if (reverseHomomorphicMappedCache.has(cacheKey)) {
      return reverseHomomorphicMappedCache.get(cacheKey);
    }
    const type = createReverseMappedType(source, target, constraint);
    reverseHomomorphicMappedCache.set(cacheKey, type);
    return type;
  }
  function isPartiallyInferableType(type) {
    return !(getObjectFlags(type) & 262144 /* NonInferrableType */) || isObjectLiteralType(type) && some(getPropertiesOfType(type), (prop) => isPartiallyInferableType(getTypeOfSymbol(prop))) || isTupleType(type) && some(getElementTypes(type), isPartiallyInferableType);
  }
  function createReverseMappedType(source, target, constraint) {
    if (!(getIndexInfoOfType(source, stringType) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
      return void 0;
    }
    if (isArrayType(source)) {
      const elementType = inferReverseMappedType(getTypeArguments(source)[0], target, constraint);
      if (!elementType) {
        return void 0;
      }
      return createArrayType(elementType, isReadonlyArrayType(source));
    }
    if (isTupleType(source)) {
      const elementTypes = map(getElementTypes(source), (t) => inferReverseMappedType(t, target, constraint));
      if (!every(elementTypes, (t) => !!t)) {
        return void 0;
      }
      const elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ? sameMap(source.target.elementFlags, (f) => f & 2 /* Optional */ ? 1 /* Required */ : f) : source.target.elementFlags;
      return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
    }
    const reversed = createObjectType(
      1024 /* ReverseMapped */ | 16 /* Anonymous */,
      /*symbol*/
      void 0
    );
    reversed.source = source;
    reversed.mappedType = target;
    reversed.constraintType = constraint;
    return reversed;
  }
  function getTypeOfReverseMappedSymbol(symbol) {
    const links = getSymbolLinks(symbol);
    if (!links.type) {
      links.type = inferReverseMappedType(symbol.links.propertyType, symbol.links.mappedType, symbol.links.constraintType) || unknownType;
    }
    return links.type;
  }
  function inferReverseMappedTypeWorker(sourceType, target, constraint) {
    const typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
    const templateType = getTemplateTypeFromMappedType(target);
    const inference = createInferenceInfo(typeParameter);
    inferTypes([inference], sourceType, templateType);
    return getTypeFromInference(inference) || unknownType;
  }
  function inferReverseMappedType(source, target, constraint) {
    const cacheKey = source.id + "," + target.id + "," + constraint.id;
    if (reverseMappedCache.has(cacheKey)) {
      return reverseMappedCache.get(cacheKey) || unknownType;
    }
    reverseMappedSourceStack.push(source);
    reverseMappedTargetStack.push(target);
    const saveExpandingFlags = reverseExpandingFlags;
    if (isDeeplyNestedType(source, reverseMappedSourceStack, reverseMappedSourceStack.length, 2)) reverseExpandingFlags |= 1 /* Source */;
    if (isDeeplyNestedType(target, reverseMappedTargetStack, reverseMappedTargetStack.length, 2)) reverseExpandingFlags |= 2 /* Target */;
    let type;
    if (reverseExpandingFlags !== 3 /* Both */) {
      type = inferReverseMappedTypeWorker(source, target, constraint);
    }
    reverseMappedSourceStack.pop();
    reverseMappedTargetStack.pop();
    reverseExpandingFlags = saveExpandingFlags;
    reverseMappedCache.set(cacheKey, type);
    return type;
  }
  function* getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
    const properties = getPropertiesOfType(target);
    for (const targetProp of properties) {
      if (isStaticPrivateIdentifierProperty(targetProp)) {
        continue;
      }
      if (requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || getCheckFlags(targetProp) & 48 /* Partial */)) {
        const sourceProp = getPropertyOfType(source, targetProp.escapedName);
        if (!sourceProp) {
          yield targetProp;
        } else if (matchDiscriminantProperties) {
          const targetType = getTypeOfSymbol(targetProp);
          if (targetType.flags & 109472 /* Unit */) {
            const sourceType = getTypeOfSymbol(sourceProp);
            if (!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) {
              yield targetProp;
            }
          }
        }
      }
    }
  }
  function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
    return firstOrUndefinedIterator(getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties));
  }
  function tupleTypesDefinitelyUnrelated(source, target) {
    return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength || !(target.target.combinedFlags & 12 /* Variable */) && (!!(source.target.combinedFlags & 12 /* Variable */) || target.target.fixedLength < source.target.fixedLength);
  }
  function typesDefinitelyUnrelated(source, target) {
    return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) : !!getUnmatchedProperty(
      source,
      target,
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      true
    ) && !!getUnmatchedProperty(
      target,
      source,
      /*requireOptionalProperties*/
      false,
      /*matchDiscriminantProperties*/
      false
    );
  }
  function getTypeFromInference(inference) {
    return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : inference.contraCandidates ? getIntersectionType(inference.contraCandidates) : void 0;
  }
  function hasSkipDirectInferenceFlag(node) {
    return !!getNodeLinks(node).skipDirectInference;
  }
  function isFromInferenceBlockedSource(type) {
    return !!(type.symbol && some(type.symbol.declarations, hasSkipDirectInferenceFlag));
  }
  function templateLiteralTypesDefinitelyUnrelated(source, target) {
    const sourceStart = source.texts[0];
    const targetStart = target.texts[0];
    const sourceEnd = source.texts[source.texts.length - 1];
    const targetEnd = target.texts[target.texts.length - 1];
    const startLen = Math.min(sourceStart.length, targetStart.length);
    const endLen = Math.min(sourceEnd.length, targetEnd.length);
    return sourceStart.slice(0, startLen) !== targetStart.slice(0, startLen) || sourceEnd.slice(sourceEnd.length - endLen) !== targetEnd.slice(targetEnd.length - endLen);
  }
  function isValidNumberString(s, roundTripOnly) {
    if (s === "") return false;
    const n = +s;
    return isFinite(n) && (!roundTripOnly || "" + n === s);
  }
  function parseBigIntLiteralType(text) {
    return getBigIntLiteralType(parseValidBigInt(text));
  }
  function isMemberOfStringMapping(source, target) {
    if (target.flags & 1 /* Any */) {
      return true;
    }
    if (target.flags & (4 /* String */ | 134217728 /* TemplateLiteral */)) {
      return isTypeAssignableTo(source, target);
    }
    if (target.flags & 268435456 /* StringMapping */) {
      const mappingStack = [];
      while (target.flags & 268435456 /* StringMapping */) {
        mappingStack.unshift(target.symbol);
        target = target.type;
      }
      const mappedSource = reduceLeft(mappingStack, (memo, value) => getStringMappingType(value, memo), source);
      return mappedSource === source && isMemberOfStringMapping(source, target);
    }
    return false;
  }
  function isValidTypeForTemplateLiteralPlaceholder(source, target) {
    if (target.flags & 2097152 /* Intersection */) {
      return every(target.types, (t) => t === emptyTypeLiteralType || isValidTypeForTemplateLiteralPlaceholder(source, t));
    }
    if (target.flags & 4 /* String */ || isTypeAssignableTo(source, target)) {
      return true;
    }
    if (source.flags & 128 /* StringLiteral */) {
      const value = source.value;
      return !!(target.flags & 8 /* Number */ && isValidNumberString(
        value,
        /*roundTripOnly*/
        false
      ) || target.flags & 64 /* BigInt */ && isValidBigIntString(
        value,
        /*roundTripOnly*/
        false
      ) || target.flags & (512 /* BooleanLiteral */ | 98304 /* Nullable */) && value === target.intrinsicName || target.flags & 268435456 /* StringMapping */ && isMemberOfStringMapping(getStringLiteralType(value), target) || target.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source, target));
    }
    if (source.flags & 134217728 /* TemplateLiteral */) {
      const texts = source.texts;
      return texts.length === 2 && texts[0] === "" && texts[1] === "" && isTypeAssignableTo(source.types[0], target);
    }
    return false;
  }
  function inferTypesFromTemplateLiteralType(source, target) {
    return source.flags & 128 /* StringLiteral */ ? inferFromLiteralPartsToTemplateLiteral([source.value], emptyArray, target) : source.flags & 134217728 /* TemplateLiteral */ ? arrayIsEqualTo(source.texts, target.texts) ? map(source.types, (s, i) => {
      return isTypeAssignableTo(getBaseConstraintOrType(s), getBaseConstraintOrType(target.types[i])) ? s : getStringLikeTypeForType(s);
    }) : inferFromLiteralPartsToTemplateLiteral(source.texts, source.types, target) : void 0;
  }
  function isTypeMatchedByTemplateLiteralType(source, target) {
    const inferences = inferTypesFromTemplateLiteralType(source, target);
    return !!inferences && every(inferences, (r, i) => isValidTypeForTemplateLiteralPlaceholder(r, target.types[i]));
  }
  function getStringLikeTypeForType(type) {
    return type.flags & (1 /* Any */ | 402653316 /* StringLike */) ? type : getTemplateLiteralType(["", ""], [type]);
  }
  function inferFromLiteralPartsToTemplateLiteral(sourceTexts, sourceTypes, target) {
    const lastSourceIndex = sourceTexts.length - 1;
    const sourceStartText = sourceTexts[0];
    const sourceEndText = sourceTexts[lastSourceIndex];
    const targetTexts = target.texts;
    const lastTargetIndex = targetTexts.length - 1;
    const targetStartText = targetTexts[0];
    const targetEndText = targetTexts[lastTargetIndex];
    if (lastSourceIndex === 0 && sourceStartText.length < targetStartText.length + targetEndText.length || !sourceStartText.startsWith(targetStartText) || !sourceEndText.endsWith(targetEndText)) return void 0;
    const remainingEndText = sourceEndText.slice(0, sourceEndText.length - targetEndText.length);
    const matches = [];
    let seg = 0;
    let pos = targetStartText.length;
    for (let i = 1; i < lastTargetIndex; i++) {
      const delim = targetTexts[i];
      if (delim.length > 0) {
        let s = seg;
        let p = pos;
        while (true) {
          p = getSourceText(s).indexOf(delim, p);
          if (p >= 0) break;
          s++;
          if (s === sourceTexts.length) return void 0;
          p = 0;
        }
        addMatch(s, p);
        pos += delim.length;
      } else if (pos < getSourceText(seg).length) {
        addMatch(seg, pos + 1);
      } else if (seg < lastSourceIndex) {
        addMatch(seg + 1, 0);
      } else {
        return void 0;
      }
    }
    addMatch(lastSourceIndex, getSourceText(lastSourceIndex).length);
    return matches;
    function getSourceText(index) {
      return index < lastSourceIndex ? sourceTexts[index] : remainingEndText;
    }
    function addMatch(s, p) {
      const matchType = s === seg ? getStringLiteralType(getSourceText(s).slice(pos, p)) : getTemplateLiteralType(
        [sourceTexts[seg].slice(pos), ...sourceTexts.slice(seg + 1, s), getSourceText(s).slice(0, p)],
        sourceTypes.slice(seg, s)
      );
      matches.push(matchType);
      seg = s;
      pos = p;
    }
  }
  function isTupleOfSelf(typeParameter, type) {
    return isTupleType(type) && getTupleElementType(type, 0) === getIndexedAccessType(typeParameter, getNumberLiteralType(0)) && !getTypeOfPropertyOfType(type, "1");
  }
  function inferTypes(inferences, originalSource, originalTarget, priority = 0 /* None */, contravariant = false) {
    let bivariant = false;
    let propagationType;
    let inferencePriority = 2048 /* MaxValue */;
    let visited;
    let sourceStack;
    let targetStack;
    let expandingFlags = 0 /* None */;
    inferFromTypes(originalSource, originalTarget);
    function inferFromTypes(source, target) {
      if (!couldContainTypeVariables(target) || isNoInferType(target)) {
        return;
      }
      if (source === wildcardType || source === blockedStringType) {
        const savePropagationType = propagationType;
        propagationType = source;
        inferFromTypes(target, target);
        propagationType = savePropagationType;
        return;
      }
      if (source.aliasSymbol && source.aliasSymbol === target.aliasSymbol) {
        if (source.aliasTypeArguments) {
          const params = getSymbolLinks(source.aliasSymbol).typeParameters;
          const minParams = getMinTypeArgumentCount(params);
          const sourceTypes = fillMissingTypeArguments(source.aliasTypeArguments, params, minParams, isInJSFile(source.aliasSymbol.valueDeclaration));
          const targetTypes = fillMissingTypeArguments(target.aliasTypeArguments, params, minParams, isInJSFile(source.aliasSymbol.valueDeclaration));
          inferFromTypeArguments(sourceTypes, targetTypes, getAliasVariances(source.aliasSymbol));
        }
        return;
      }
      if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
        for (const t of source.types) {
          inferFromTypes(t, t);
        }
        return;
      }
      if (target.flags & 1048576 /* Union */) {
        const [tempSources, tempTargets] = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo);
        const [sources, targets] = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy);
        if (targets.length === 0) {
          return;
        }
        target = getUnionType(targets);
        if (sources.length === 0) {
          inferWithPriority(source, target, 1 /* NakedTypeVariable */);
          return;
        }
        source = getUnionType(sources);
      } else if (target.flags & 2097152 /* Intersection */ && !every(target.types, isNonGenericObjectType)) {
        if (!(source.flags & 1048576 /* Union */)) {
          const [sources, targets] = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo);
          if (sources.length === 0 || targets.length === 0) {
            return;
          }
          source = getIntersectionType(sources);
          target = getIntersectionType(targets);
        }
      }
      if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
        if (isNoInferType(target)) {
          return;
        }
        target = getActualTypeVariable(target);
      }
      if (target.flags & 8650752 /* TypeVariable */) {
        if (isFromInferenceBlockedSource(source)) {
          return;
        }
        const inference = getInferenceInfoForType(target);
        if (inference) {
          if (getObjectFlags(source) & 262144 /* NonInferrableType */ || source === nonInferrableAnyType) {
            return;
          }
          if (!inference.isFixed) {
            const candidate = propagationType || source;
            if (candidate === blockedStringType) {
              return;
            }
            if (inference.priority === void 0 || priority < inference.priority) {
              inference.candidates = void 0;
              inference.contraCandidates = void 0;
              inference.topLevel = true;
              inference.priority = priority;
            }
            if (priority === inference.priority) {
              if (isTupleOfSelf(inference.typeParameter, candidate)) {
                return;
              }
              if (contravariant && !bivariant) {
                if (!contains(inference.contraCandidates, candidate)) {
                  inference.contraCandidates = append(inference.contraCandidates, candidate);
                  clearCachedInferences(inferences);
                }
              } else if (!contains(inference.candidates, candidate)) {
                inference.candidates = append(inference.candidates, candidate);
                clearCachedInferences(inferences);
              }
            }
            if (!(priority & 128 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
              inference.topLevel = false;
              clearCachedInferences(inferences);
            }
          }
          inferencePriority = Math.min(inferencePriority, priority);
          return;
        }
        const simplified = getSimplifiedType(
          target,
          /*writing*/
          false
        );
        if (simplified !== target) {
          inferFromTypes(source, simplified);
        } else if (target.flags & 8388608 /* IndexedAccess */) {
          const indexType = getSimplifiedType(
            target.indexType,
            /*writing*/
            false
          );
          if (indexType.flags & 465829888 /* Instantiable */) {
            const simplified2 = distributeIndexOverObjectType(
              getSimplifiedType(
                target.objectType,
                /*writing*/
                false
              ),
              indexType,
              /*writing*/
              false
            );
            if (simplified2 && simplified2 !== target) {
              inferFromTypes(source, simplified2);
            }
          }
        }
      }
      if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) && !(source.node && target.node)) {
        inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
      } else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
        inferFromContravariantTypes(source.type, target.type);
      } else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
        const empty = createEmptyObjectTypeFromStringLiteral(source);
        inferFromContravariantTypesWithPriority(empty, target.type, 256 /* LiteralKeyof */);
      } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
        inferFromTypes(source.objectType, target.objectType);
        inferFromTypes(source.indexType, target.indexType);
      } else if (source.flags & 268435456 /* StringMapping */ && target.flags & 268435456 /* StringMapping */) {
        if (source.symbol === target.symbol) {
          inferFromTypes(source.type, target.type);
        }
      } else if (source.flags & 33554432 /* Substitution */) {
        inferFromTypes(source.baseType, target);
        inferWithPriority(getSubstitutionIntersection(source), target, 4 /* SubstituteSource */);
      } else if (target.flags & 16777216 /* Conditional */) {
        invokeOnce(source, target, inferToConditionalType);
      } else if (target.flags & 3145728 /* UnionOrIntersection */) {
        inferToMultipleTypes(source, target.types, target.flags);
      } else if (source.flags & 1048576 /* Union */) {
        const sourceTypes = source.types;
        for (const sourceType of sourceTypes) {
          inferFromTypes(sourceType, target);
        }
      } else if (target.flags & 134217728 /* TemplateLiteral */) {
        inferToTemplateLiteralType(source, target);
      } else {
        source = getReducedType(source);
        if (isGenericMappedType(source) && isGenericMappedType(target)) {
          invokeOnce(source, target, inferFromGenericMappedTypes);
        }
        if (!(priority & 512 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) {
          const apparentSource = getApparentType(source);
          if (apparentSource !== source && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
            return inferFromTypes(apparentSource, target);
          }
          source = apparentSource;
        }
        if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
          invokeOnce(source, target, inferFromObjectTypes);
        }
      }
    }
    function inferWithPriority(source, target, newPriority) {
      const savePriority = priority;
      priority |= newPriority;
      inferFromTypes(source, target);
      priority = savePriority;
    }
    function inferFromContravariantTypesWithPriority(source, target, newPriority) {
      const savePriority = priority;
      priority |= newPriority;
      inferFromContravariantTypes(source, target);
      priority = savePriority;
    }
    function inferToMultipleTypesWithPriority(source, targets, targetFlags, newPriority) {
      const savePriority = priority;
      priority |= newPriority;
      inferToMultipleTypes(source, targets, targetFlags);
      priority = savePriority;
    }
    function invokeOnce(source, target, action) {
      const key = source.id + "," + target.id;
      const status = visited && visited.get(key);
      if (status !== void 0) {
        inferencePriority = Math.min(inferencePriority, status);
        return;
      }
      (visited || (visited = /* @__PURE__ */ new Map())).set(key, -1 /* Circularity */);
      const saveInferencePriority = inferencePriority;
      inferencePriority = 2048 /* MaxValue */;
      const saveExpandingFlags = expandingFlags;
      (sourceStack ?? (sourceStack = [])).push(source);
      (targetStack ?? (targetStack = [])).push(target);
      if (isDeeplyNestedType(source, sourceStack, sourceStack.length, 2)) expandingFlags |= 1 /* Source */;
      if (isDeeplyNestedType(target, targetStack, targetStack.length, 2)) expandingFlags |= 2 /* Target */;
      if (expandingFlags !== 3 /* Both */) {
        action(source, target);
      } else {
        inferencePriority = -1 /* Circularity */;
      }
      targetStack.pop();
      sourceStack.pop();
      expandingFlags = saveExpandingFlags;
      visited.set(key, inferencePriority);
      inferencePriority = Math.min(inferencePriority, saveInferencePriority);
    }
    function inferFromMatchingTypes(sources, targets, matches) {
      let matchedSources;
      let matchedTargets;
      for (const t of targets) {
        for (const s of sources) {
          if (matches(s, t)) {
            inferFromTypes(s, t);
            matchedSources = appendIfUnique(matchedSources, s);
            matchedTargets = appendIfUnique(matchedTargets, t);
          }
        }
      }
      return [
        matchedSources ? filter(sources, (t) => !contains(matchedSources, t)) : sources,
        matchedTargets ? filter(targets, (t) => !contains(matchedTargets, t)) : targets
      ];
    }
    function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
      const count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
      for (let i = 0; i < count; i++) {
        if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
          inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
        } else {
          inferFromTypes(sourceTypes[i], targetTypes[i]);
        }
      }
    }
    function inferFromContravariantTypes(source, target) {
      contravariant = !contravariant;
      inferFromTypes(source, target);
      contravariant = !contravariant;
    }
    function inferFromContravariantTypesIfStrictFunctionTypes(source, target) {
      if (strictFunctionTypes || priority & 1024 /* AlwaysStrict */) {
        inferFromContravariantTypes(source, target);
      } else {
        inferFromTypes(source, target);
      }
    }
    function getInferenceInfoForType(type) {
      if (type.flags & 8650752 /* TypeVariable */) {
        for (const inference of inferences) {
          if (type === inference.typeParameter) {
            return inference;
          }
        }
      }
      return void 0;
    }
    function getSingleTypeVariableFromIntersectionTypes(types) {
      let typeVariable;
      for (const type of types) {
        const t = type.flags & 2097152 /* Intersection */ && find(type.types, (t2) => !!getInferenceInfoForType(t2));
        if (!t || typeVariable && t !== typeVariable) {
          return void 0;
        }
        typeVariable = t;
      }
      return typeVariable;
    }
    function inferToMultipleTypes(source, targets, targetFlags) {
      let typeVariableCount = 0;
      if (targetFlags & 1048576 /* Union */) {
        let nakedTypeVariable;
        const sources = source.flags & 1048576 /* Union */ ? source.types : [source];
        const matched = new Array(sources.length);
        let inferenceCircularity = false;
        for (const t of targets) {
          if (getInferenceInfoForType(t)) {
            nakedTypeVariable = t;
            typeVariableCount++;
          } else {
            for (let i = 0; i < sources.length; i++) {
              const saveInferencePriority = inferencePriority;
              inferencePriority = 2048 /* MaxValue */;
              inferFromTypes(sources[i], t);
              if (inferencePriority === priority) matched[i] = true;
              inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
              inferencePriority = Math.min(inferencePriority, saveInferencePriority);
            }
          }
        }
        if (typeVariableCount === 0) {
          const intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
          if (intersectionTypeVariable) {
            inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
          }
          return;
        }
        if (typeVariableCount === 1 && !inferenceCircularity) {
          const unmatched = flatMap(sources, (s, i) => matched[i] ? void 0 : s);
          if (unmatched.length) {
            inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
            return;
          }
        }
      } else {
        for (const t of targets) {
          if (getInferenceInfoForType(t)) {
            typeVariableCount++;
          } else {
            inferFromTypes(source, t);
          }
        }
      }
      if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
        for (const t of targets) {
          if (getInferenceInfoForType(t)) {
            inferWithPriority(source, t, 1 /* NakedTypeVariable */);
          }
        }
      }
    }
    function inferToMappedType(source, target, constraintType) {
      if (constraintType.flags & 1048576 /* Union */ || constraintType.flags & 2097152 /* Intersection */) {
        let result = false;
        for (const type of constraintType.types) {
          result = inferToMappedType(source, target, type) || result;
        }
        return result;
      }
      if (constraintType.flags & 4194304 /* Index */) {
        const inference = getInferenceInfoForType(constraintType.type);
        if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
          const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
          if (inferredType) {
            inferWithPriority(
              inferredType,
              inference.typeParameter,
              getObjectFlags(source) & 262144 /* NonInferrableType */ ? 16 /* PartialHomomorphicMappedType */ : 8 /* HomomorphicMappedType */
            );
          }
        }
        return true;
      }
      if (constraintType.flags & 262144 /* TypeParameter */) {
        inferWithPriority(getIndexType(
          source,
          /*indexFlags*/
          !!source.pattern ? 2 /* NoIndexSignatures */ : 0 /* None */
        ), constraintType, 32 /* MappedTypeConstraint */);
        const extendedConstraint = getConstraintOfType(constraintType);
        if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
          return true;
        }
        const propTypes = map(getPropertiesOfType(source), getTypeOfSymbol);
        const indexTypes = map(getIndexInfosOfType(source), (info) => info !== enumNumberIndexInfo ? info.type : neverType);
        inferFromTypes(getUnionType(concatenate(propTypes, indexTypes)), getTemplateTypeFromMappedType(target));
        return true;
      }
      return false;
    }
    function inferToConditionalType(source, target) {
      if (source.flags & 16777216 /* Conditional */) {
        inferFromTypes(source.checkType, target.checkType);
        inferFromTypes(source.extendsType, target.extendsType);
        inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
        inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
      } else {
        const targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
        inferToMultipleTypesWithPriority(source, targetTypes, target.flags, contravariant ? 64 /* ContravariantConditional */ : 0);
      }
    }
    function inferToTemplateLiteralType(source, target) {
      const matches = inferTypesFromTemplateLiteralType(source, target);
      const types = target.types;
      if (matches || every(target.texts, (s) => s.length === 0)) {
        for (let i = 0; i < types.length; i++) {
          const source2 = matches ? matches[i] : neverType;
          const target2 = types[i];
          if (source2.flags & 128 /* StringLiteral */ && target2.flags & 8650752 /* TypeVariable */) {
            const inferenceContext = getInferenceInfoForType(target2);
            const constraint = inferenceContext ? getBaseConstraintOfType(inferenceContext.typeParameter) : void 0;
            if (constraint && !isTypeAny(constraint)) {
              const constraintTypes = constraint.flags & 1048576 /* Union */ ? constraint.types : [constraint];
              let allTypeFlags = reduceLeft(constraintTypes, (flags, t) => flags | t.flags, 0);
              if (!(allTypeFlags & 4 /* String */)) {
                const str = source2.value;
                if (allTypeFlags & 296 /* NumberLike */ && !isValidNumberString(
                  str,
                  /*roundTripOnly*/
                  true
                )) {
                  allTypeFlags &= ~296 /* NumberLike */;
                }
                if (allTypeFlags & 2112 /* BigIntLike */ && !isValidBigIntString(
                  str,
                  /*roundTripOnly*/
                  true
                )) {
                  allTypeFlags &= ~2112 /* BigIntLike */;
                }
                const matchingType = reduceLeft(constraintTypes, (left, right) => !(right.flags & allTypeFlags) ? left : left.flags & 4 /* String */ ? left : right.flags & 4 /* String */ ? source2 : left.flags & 134217728 /* TemplateLiteral */ ? left : right.flags & 134217728 /* TemplateLiteral */ && isTypeMatchedByTemplateLiteralType(source2, right) ? source2 : left.flags & 268435456 /* StringMapping */ ? left : right.flags & 268435456 /* StringMapping */ && str === applyStringMapping(right.symbol, str) ? source2 : left.flags & 128 /* StringLiteral */ ? left : right.flags & 128 /* StringLiteral */ && right.value === str ? right : left.flags & 8 /* Number */ ? left : right.flags & 8 /* Number */ ? getNumberLiteralType(+str) : left.flags & 32 /* Enum */ ? left : right.flags & 32 /* Enum */ ? getNumberLiteralType(+str) : left.flags & 256 /* NumberLiteral */ ? left : right.flags & 256 /* NumberLiteral */ && right.value === +str ? right : left.flags & 64 /* BigInt */ ? left : right.flags & 64 /* BigInt */ ? parseBigIntLiteralType(str) : left.flags & 2048 /* BigIntLiteral */ ? left : right.flags & 2048 /* BigIntLiteral */ && pseudoBigIntToString(right.value) === str ? right : left.flags & 16 /* Boolean */ ? left : right.flags & 16 /* Boolean */ ? str === "true" ? trueType : str === "false" ? falseType : booleanType : left.flags & 512 /* BooleanLiteral */ ? left : right.flags & 512 /* BooleanLiteral */ && right.intrinsicName === str ? right : left.flags & 32768 /* Undefined */ ? left : right.flags & 32768 /* Undefined */ && right.intrinsicName === str ? right : left.flags & 65536 /* Null */ ? left : right.flags & 65536 /* Null */ && right.intrinsicName === str ? right : left, neverType);
                if (!(matchingType.flags & 131072 /* Never */)) {
                  inferFromTypes(matchingType, target2);
                  continue;
                }
              }
            }
          }
          inferFromTypes(source2, target2);
        }
      }
    }
    function inferFromGenericMappedTypes(source, target) {
      inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
      inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
      const sourceNameType = getNameTypeFromMappedType(source);
      const targetNameType = getNameTypeFromMappedType(target);
      if (sourceNameType && targetNameType) inferFromTypes(sourceNameType, targetNameType);
    }
    function inferFromObjectTypes(source, target) {
      var _a, _b;
      if (getObjectFlags(source) & 4 /* Reference */ && getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
        inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
        return;
      }
      if (isGenericMappedType(source) && isGenericMappedType(target)) {
        inferFromGenericMappedTypes(source, target);
      }
      if (getObjectFlags(target) & 32 /* Mapped */ && !target.declaration.nameType) {
        const constraintType = getConstraintTypeFromMappedType(target);
        if (inferToMappedType(source, target, constraintType)) {
          return;
        }
      }
      if (!typesDefinitelyUnrelated(source, target)) {
        if (isArrayOrTupleType(source)) {
          if (isTupleType(target)) {
            const sourceArity = getTypeReferenceArity(source);
            const targetArity = getTypeReferenceArity(target);
            const elementTypes = getTypeArguments(target);
            const elementFlags = target.target.elementFlags;
            if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
              for (let i = 0; i < targetArity; i++) {
                inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
              }
              return;
            }
            const startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
            const endLength = Math.min(isTupleType(source) ? getEndElementCount(source.target, 3 /* Fixed */) : 0, target.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(target.target, 3 /* Fixed */) : 0);
            for (let i = 0; i < startLength; i++) {
              inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
            }
            if (!isTupleType(source) || sourceArity - startLength - endLength === 1 && source.target.elementFlags[startLength] & 4 /* Rest */) {
              const restType = getTypeArguments(source)[startLength];
              for (let i = startLength; i < targetArity - endLength; i++) {
                inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(restType) : restType, elementTypes[i]);
              }
            } else {
              const middleLength = targetArity - startLength - endLength;
              if (middleLength === 2) {
                if (elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* Variadic */) {
                  const targetInfo = getInferenceInfoForType(elementTypes[startLength]);
                  if (targetInfo && targetInfo.impliedArity !== void 0) {
                    inferFromTypes(sliceTupleType(source, startLength, endLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
                    inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, endLength), elementTypes[startLength + 1]);
                  }
                } else if (elementFlags[startLength] & 8 /* Variadic */ && elementFlags[startLength + 1] & 4 /* Rest */) {
                  const param = (_a = getInferenceInfoForType(elementTypes[startLength])) == null ? void 0 : _a.typeParameter;
                  const constraint = param && getBaseConstraintOfType(param);
                  if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* Variable */)) {
                    const impliedArity = constraint.target.fixedLength;
                    inferFromTypes(sliceTupleType(source, startLength, sourceArity - (startLength + impliedArity)), elementTypes[startLength]);
                    inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength + impliedArity, endLength), elementTypes[startLength + 1]);
                  }
                } else if (elementFlags[startLength] & 4 /* Rest */ && elementFlags[startLength + 1] & 8 /* Variadic */) {
                  const param = (_b = getInferenceInfoForType(elementTypes[startLength + 1])) == null ? void 0 : _b.typeParameter;
                  const constraint = param && getBaseConstraintOfType(param);
                  if (constraint && isTupleType(constraint) && !(constraint.target.combinedFlags & 12 /* Variable */)) {
                    const impliedArity = constraint.target.fixedLength;
                    const endIndex = sourceArity - getEndElementCount(target.target, 3 /* Fixed */);
                    const startIndex = endIndex - impliedArity;
                    const trailingSlice = createTupleType(
                      getTypeArguments(source).slice(startIndex, endIndex),
                      source.target.elementFlags.slice(startIndex, endIndex),
                      /*readonly*/
                      false,
                      source.target.labeledElementDeclarations && source.target.labeledElementDeclarations.slice(startIndex, endIndex)
                    );
                    inferFromTypes(getElementTypeOfSliceOfTupleType(source, startLength, endLength + impliedArity), elementTypes[startLength]);
                    inferFromTypes(trailingSlice, elementTypes[startLength + 1]);
                  }
                }
              } else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) {
                const endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
                const sourceSlice = sliceTupleType(source, startLength, endLength);
                inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
              } else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) {
                const restType = getElementTypeOfSliceOfTupleType(source, startLength, endLength);
                if (restType) {
                  inferFromTypes(restType, elementTypes[startLength]);
                }
              }
            }
            for (let i = 0; i < endLength; i++) {
              inferFromTypes(getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
            }
            return;
          }
          if (isArrayType(target)) {
            inferFromIndexTypes(source, target);
            return;
          }
        }
        inferFromProperties(source, target);
        inferFromSignatures(source, target, 0 /* Call */);
        inferFromSignatures(source, target, 1 /* Construct */);
        inferFromIndexTypes(source, target);
      }
    }
    function inferFromProperties(source, target) {
      const properties = getPropertiesOfObjectType(target);
      for (const targetProp of properties) {
        const sourceProp = getPropertyOfType(source, targetProp.escapedName);
        if (sourceProp && !some(sourceProp.declarations, hasSkipDirectInferenceFlag)) {
          inferFromTypes(
            removeMissingType(getTypeOfSymbol(sourceProp), !!(sourceProp.flags & 16777216 /* Optional */)),
            removeMissingType(getTypeOfSymbol(targetProp), !!(targetProp.flags & 16777216 /* Optional */))
          );
        }
      }
    }
    function inferFromSignatures(source, target, kind) {
      const sourceSignatures = getSignaturesOfType(source, kind);
      const sourceLen = sourceSignatures.length;
      if (sourceLen > 0) {
        const targetSignatures = getSignaturesOfType(target, kind);
        const targetLen = targetSignatures.length;
        for (let i = 0; i < targetLen; i++) {
          const sourceIndex = Math.max(sourceLen - targetLen + i, 0);
          inferFromSignature(getBaseSignature(sourceSignatures[sourceIndex]), getErasedSignature(targetSignatures[i]));
        }
      }
    }
    function inferFromSignature(source, target) {
      if (!(source.flags & 64 /* IsNonInferrable */)) {
        const saveBivariant = bivariant;
        const kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
        bivariant = bivariant || kind === 174 /* MethodDeclaration */ || kind === 173 /* MethodSignature */ || kind === 176 /* Constructor */;
        applyToParameterTypes(source, target, inferFromContravariantTypesIfStrictFunctionTypes);
        bivariant = saveBivariant;
      }
      applyToReturnTypes(source, target, inferFromTypes);
    }
    function inferFromIndexTypes(source, target) {
      const priority2 = getObjectFlags(source) & getObjectFlags(target) & 32 /* Mapped */ ? 8 /* HomomorphicMappedType */ : 0;
      const indexInfos = getIndexInfosOfType(target);
      if (isObjectTypeWithInferableIndex(source)) {
        for (const targetInfo of indexInfos) {
          const propTypes = [];
          for (const prop of getPropertiesOfType(source)) {
            if (isApplicableIndexType(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), targetInfo.keyType)) {
              const propType = getTypeOfSymbol(prop);
              propTypes.push(prop.flags & 16777216 /* Optional */ ? removeMissingOrUndefinedType(propType) : propType);
            }
          }
          for (const info of getIndexInfosOfType(source)) {
            if (isApplicableIndexType(info.keyType, targetInfo.keyType)) {
              propTypes.push(info.type);
            }
          }
          if (propTypes.length) {
            inferWithPriority(getUnionType(propTypes), targetInfo.type, priority2);
          }
        }
      }
      for (const targetInfo of indexInfos) {
        const sourceInfo = getApplicableIndexInfo(source, targetInfo.keyType);
        if (sourceInfo) {
          inferWithPriority(sourceInfo.type, targetInfo.type, priority2);
        }
      }
    }
  }
  function isTypeOrBaseIdenticalTo(s, t) {
    return t === missingType ? s === t : isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
  }
  function isTypeCloselyMatchedBy(s, t) {
    return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol || s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
  }
  function hasPrimitiveConstraint(type) {
    const constraint = getConstraintOfTypeParameter(type);
    return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 402784252 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
  }
  function isObjectLiteralType(type) {
    return !!(getObjectFlags(type) & 128 /* ObjectLiteral */);
  }
  function isObjectOrArrayLiteralType(type) {
    return !!(getObjectFlags(type) & (128 /* ObjectLiteral */ | 16384 /* ArrayLiteral */));
  }
  function unionObjectAndArrayLiteralCandidates(candidates) {
    if (candidates.length > 1) {
      const objectLiterals = filter(candidates, isObjectOrArrayLiteralType);
      if (objectLiterals.length) {
        const literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
        return concatenate(filter(candidates, (t) => !isObjectOrArrayLiteralType(t)), [literalsType]);
      }
    }
    return candidates;
  }
  function getContravariantInference(inference) {
    return inference.priority & 416 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
  }
  function getCovariantInference(inference, signature) {
    const candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
    const primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter) || isConstTypeVariable(inference.typeParameter);
    const widenLiteralTypes = !primitiveConstraint && inference.topLevel && (inference.isFixed || !isTypeParameterAtTopLevelInReturnType(signature, inference.typeParameter));
    const baseCandidates = primitiveConstraint ? sameMap(candidates, getRegularTypeOfLiteralType) : widenLiteralTypes ? sameMap(candidates, getWidenedLiteralType) : candidates;
    const unwidenedType = inference.priority & 416 /* PriorityImpliesCombination */ ? getUnionType(baseCandidates, 2 /* Subtype */) : getCommonSupertype(baseCandidates);
    return getWidenedType(unwidenedType);
  }
  function getInferredType(context, index) {
    const inference = context.inferences[index];
    if (!inference.inferredType) {
      let inferredType;
      let fallbackType;
      if (context.signature) {
        const inferredCovariantType = inference.candidates ? getCovariantInference(inference, context.signature) : void 0;
        const inferredContravariantType = inference.contraCandidates ? getContravariantInference(inference) : void 0;
        if (inferredCovariantType || inferredContravariantType) {
          const preferCovariantType = inferredCovariantType && (!inferredContravariantType || !(inferredCovariantType.flags & (131072 /* Never */ | 1 /* Any */)) && some(inference.contraCandidates, (t) => isTypeAssignableTo(inferredCovariantType, t)) && every(context.inferences, (other) => other !== inference && getConstraintOfTypeParameter(other.typeParameter) !== inference.typeParameter || every(other.candidates, (t) => isTypeAssignableTo(t, inferredCovariantType))));
          inferredType = preferCovariantType ? inferredCovariantType : inferredContravariantType;
          fallbackType = preferCovariantType ? inferredContravariantType : inferredCovariantType;
        } else if (context.flags & 1 /* NoDefault */) {
          inferredType = silentNeverType;
        } else {
          const defaultType = getDefaultFromTypeParameter(inference.typeParameter);
          if (defaultType) {
            inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
          }
        }
      } else {
        inferredType = getTypeFromInference(inference);
      }
      inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
      const constraint = getConstraintOfTypeParameter(inference.typeParameter);
      if (constraint) {
        const instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
        if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
          inference.inferredType = fallbackType && context.compareTypes(fallbackType, getTypeWithThisArgument(instantiatedConstraint, fallbackType)) ? fallbackType : instantiatedConstraint;
        }
      }
    }
    return inference.inferredType;
  }
  function getDefaultTypeArgumentType(isInJavaScriptFile) {
    return isInJavaScriptFile ? anyType : unknownType;
  }
  function getInferredTypes(context) {
    const result = [];
    for (let i = 0; i < context.inferences.length; i++) {
      result.push(getInferredType(context, i));
    }
    return result;
  }
  function getCannotFindNameDiagnosticForName(node) {
    switch (node.escapedText) {
      case "document":
      case "console":
        return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
      case "$":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery;
      case "describe":
      case "suite":
      case "it":
      case "test":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha;
      case "process":
      case "require":
      case "Buffer":
      case "module":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
      case "Bun":
        return compilerOptions.types ? Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun_and_then_add_bun_to_the_types_field_in_your_tsconfig : Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_Bun_Try_npm_i_save_dev_types_Slashbun;
      case "Map":
      case "Set":
      case "Promise":
      case "Symbol":
      case "WeakMap":
      case "WeakSet":
      case "Iterator":
      case "AsyncIterator":
      case "SharedArrayBuffer":
      case "Atomics":
      case "AsyncIterable":
      case "AsyncIterableIterator":
      case "AsyncGenerator":
      case "AsyncGeneratorFunction":
      case "BigInt":
      case "Reflect":
      case "BigInt64Array":
      case "BigUint64Array":
        return Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later;
      case "await":
        if (isCallExpression(node.parent)) {
          return Diagnostics.Cannot_find_name_0_Did_you_mean_to_write_this_in_an_async_function;
        }
      // falls through
      default:
        if (node.parent.kind === 304 /* ShorthandPropertyAssignment */) {
          return Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
        } else {
          return Diagnostics.Cannot_find_name_0;
        }
    }
  }
  function getResolvedSymbol(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedSymbol) {
      links.resolvedSymbol = !nodeIsMissing(node) && resolveName(
        node,
        node,
        111551 /* Value */ | 1048576 /* ExportValue */,
        getCannotFindNameDiagnosticForName(node),
        !isWriteOnlyAccess(node),
        /*excludeGlobals*/
        false
      ) || unknownSymbol;
    }
    return links.resolvedSymbol;
  }
  function isInAmbientOrTypeNode(node) {
    return !!(node.flags & 33554432 /* Ambient */ || findAncestor(node, (n) => isInterfaceDeclaration(n) || isTypeAliasDeclaration(n) || isTypeLiteralNode(n)));
  }
  function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
    switch (node.kind) {
      case 80 /* Identifier */:
        if (!isThisInTypeQuery(node)) {
          const symbol = getResolvedSymbol(node);
          return symbol !== unknownSymbol ? `${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}|${getSymbolId(symbol)}` : void 0;
        }
      // falls through
      case 110 /* ThisKeyword */:
        return `0|${flowContainer ? getNodeId(flowContainer) : "-1"}|${getTypeId(declaredType)}|${getTypeId(initialType)}`;
      case 235 /* NonNullExpression */:
      case 217 /* ParenthesizedExpression */:
        return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
      case 166 /* QualifiedName */:
        const left = getFlowCacheKey(node.left, declaredType, initialType, flowContainer);
        return left && `${left}.${node.right.escapedText}`;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        const propName = getAccessedPropertyName(node);
        if (propName !== void 0) {
          const key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
          return key && `${key}.${propName}`;
        }
        if (isElementAccessExpression(node) && isIdentifier(node.argumentExpression)) {
          const symbol = getResolvedSymbol(node.argumentExpression);
          if (isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol)) {
            const key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
            return key && `${key}.@${getSymbolId(symbol)}`;
          }
        }
        break;
      case 206 /* ObjectBindingPattern */:
      case 207 /* ArrayBindingPattern */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 174 /* MethodDeclaration */:
        return `${getNodeId(node)}#${getTypeId(declaredType)}`;
    }
    return void 0;
  }
  function isMatchingReference(source, target) {
    switch (target.kind) {
      case 217 /* ParenthesizedExpression */:
      case 235 /* NonNullExpression */:
        return isMatchingReference(source, target.expression);
      case 226 /* BinaryExpression */:
        return isAssignmentExpression(target) && isMatchingReference(source, target.left) || isBinaryExpression(target) && target.operatorToken.kind === 28 /* CommaToken */ && isMatchingReference(source, target.right);
    }
    switch (source.kind) {
      case 236 /* MetaProperty */:
        return target.kind === 236 /* MetaProperty */ && source.keywordToken === target.keywordToken && source.name.escapedText === target.name.escapedText;
      case 80 /* Identifier */:
      case 81 /* PrivateIdentifier */:
        return isThisInTypeQuery(source) ? target.kind === 110 /* ThisKeyword */ : target.kind === 80 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) || (isVariableDeclaration(target) || isBindingElement(target)) && getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfDeclaration(target);
      case 110 /* ThisKeyword */:
        return target.kind === 110 /* ThisKeyword */;
      case 108 /* SuperKeyword */:
        return target.kind === 108 /* SuperKeyword */;
      case 235 /* NonNullExpression */:
      case 217 /* ParenthesizedExpression */:
        return isMatchingReference(source.expression, target);
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        const sourcePropertyName = getAccessedPropertyName(source);
        if (sourcePropertyName !== void 0) {
          const targetPropertyName = isAccessExpression(target) ? getAccessedPropertyName(target) : void 0;
          if (targetPropertyName !== void 0) {
            return targetPropertyName === sourcePropertyName && isMatchingReference(source.expression, target.expression);
          }
        }
        if (isElementAccessExpression(source) && isElementAccessExpression(target) && isIdentifier(source.argumentExpression) && isIdentifier(target.argumentExpression)) {
          const symbol = getResolvedSymbol(source.argumentExpression);
          if (symbol === getResolvedSymbol(target.argumentExpression) && (isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol))) {
            return isMatchingReference(source.expression, target.expression);
          }
        }
        break;
      case 166 /* QualifiedName */:
        return isAccessExpression(target) && source.right.escapedText === getAccessedPropertyName(target) && isMatchingReference(source.left, target.expression);
      case 226 /* BinaryExpression */:
        return isBinaryExpression(source) && source.operatorToken.kind === 28 /* CommaToken */ && isMatchingReference(source.right, target);
    }
    return false;
  }
  function getAccessedPropertyName(access) {
    if (isPropertyAccessExpression(access)) {
      return access.name.escapedText;
    }
    if (isElementAccessExpression(access)) {
      return tryGetElementAccessExpressionName(access);
    }
    if (isBindingElement(access)) {
      const name = getDestructuringPropertyName(access);
      return name ? escapeLeadingUnderscores(name) : void 0;
    }
    if (isParameter(access)) {
      return "" + access.parent.parameters.indexOf(access);
    }
    return void 0;
  }
  function tryGetNameFromType(type) {
    return type.flags & 8192 /* UniqueESSymbol */ ? type.escapedName : type.flags & 384 /* StringOrNumberLiteral */ ? escapeLeadingUnderscores("" + type.value) : void 0;
  }
  function tryGetElementAccessExpressionName(node) {
    return isStringOrNumericLiteralLike(node.argumentExpression) ? escapeLeadingUnderscores(node.argumentExpression.text) : isEntityNameExpression(node.argumentExpression) ? tryGetNameFromEntityNameExpression(node.argumentExpression) : void 0;
  }
  function tryGetNameFromEntityNameExpression(node) {
    const symbol = resolveEntityName(
      node,
      111551 /* Value */,
      /*ignoreErrors*/
      true
    );
    if (!symbol || !(isConstantVariable(symbol) || symbol.flags & 8 /* EnumMember */)) return void 0;
    const declaration = symbol.valueDeclaration;
    if (declaration === void 0) return void 0;
    const type = tryGetTypeFromEffectiveTypeNode(declaration);
    if (type) {
      const name = tryGetNameFromType(type);
      if (name !== void 0) {
        return name;
      }
    }
    if (hasOnlyExpressionInitializer(declaration) && isBlockScopedNameDeclaredBeforeUse(declaration, node)) {
      const initializer = getEffectiveInitializer(declaration);
      if (initializer) {
        const initializerType = isBindingPattern(declaration.parent) ? getTypeForBindingElement(declaration) : getTypeOfExpression(initializer);
        return initializerType && tryGetNameFromType(initializerType);
      }
      if (isEnumMember(declaration)) {
        return getTextOfPropertyName(declaration.name);
      }
    }
    return void 0;
  }
  function containsMatchingReference(source, target) {
    while (isAccessExpression(source)) {
      source = source.expression;
      if (isMatchingReference(source, target)) {
        return true;
      }
    }
    return false;
  }
  function optionalChainContainsReference(source, target) {
    while (isOptionalChain(source)) {
      source = source.expression;
      if (isMatchingReference(source, target)) {
        return true;
      }
    }
    return false;
  }
  function isDiscriminantProperty(type, name) {
    if (type && type.flags & 1048576 /* Union */) {
      const prop = getUnionOrIntersectionProperty(type, name);
      if (prop && getCheckFlags(prop) & 2 /* SyntheticProperty */) {
        if (prop.links.isDiscriminantProperty === void 0) {
          prop.links.isDiscriminantProperty = (prop.links.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ && !isGenericType(getTypeOfSymbol(prop));
        }
        return !!prop.links.isDiscriminantProperty;
      }
    }
    return false;
  }
  function findDiscriminantProperties(sourceProperties, target) {
    let result;
    for (const sourceProperty of sourceProperties) {
      if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
        if (result) {
          result.push(sourceProperty);
          continue;
        }
        result = [sourceProperty];
      }
    }
    return result;
  }
  function mapTypesByKeyProperty(types, name) {
    const map2 = /* @__PURE__ */ new Map();
    let count = 0;
    for (const type of types) {
      if (type.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 58982400 /* InstantiableNonPrimitive */)) {
        const discriminant = getTypeOfPropertyOfType(type, name);
        if (discriminant) {
          if (!isLiteralType(discriminant)) {
            return void 0;
          }
          let duplicate = false;
          forEachType(discriminant, (t) => {
            const id = getTypeId(getRegularTypeOfLiteralType(t));
            const existing = map2.get(id);
            if (!existing) {
              map2.set(id, type);
            } else if (existing !== unknownType) {
              map2.set(id, unknownType);
              duplicate = true;
            }
          });
          if (!duplicate) count++;
        }
      }
    }
    return count >= 10 && count * 2 >= types.length ? map2 : void 0;
  }
  function getKeyPropertyName(unionType) {
    const types = unionType.types;
    if (types.length < 10 || getObjectFlags(unionType) & 32768 /* PrimitiveUnion */ || countWhere(types, (t) => !!(t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */))) < 10) {
      return void 0;
    }
    if (unionType.keyPropertyName === void 0) {
      const keyPropertyName = forEach(types, (t) => t.flags & (524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ? forEach(getPropertiesOfType(t), (p) => isUnitType(getTypeOfSymbol(p)) ? p.escapedName : void 0) : void 0);
      const mapByKeyProperty = keyPropertyName && mapTypesByKeyProperty(types, keyPropertyName);
      unionType.keyPropertyName = mapByKeyProperty ? keyPropertyName : "";
      unionType.constituentMap = mapByKeyProperty;
    }
    return unionType.keyPropertyName.length ? unionType.keyPropertyName : void 0;
  }
  function getConstituentTypeForKeyType(unionType, keyType) {
    var _a;
    const result = (_a = unionType.constituentMap) == null ? void 0 : _a.get(getTypeId(getRegularTypeOfLiteralType(keyType)));
    return result !== unknownType ? result : void 0;
  }
  function getMatchingUnionConstituentForType(unionType, type) {
    const keyPropertyName = getKeyPropertyName(unionType);
    const propType = keyPropertyName && getTypeOfPropertyOfType(type, keyPropertyName);
    return propType && getConstituentTypeForKeyType(unionType, propType);
  }
  function getMatchingUnionConstituentForObjectLiteral(unionType, node) {
    const keyPropertyName = getKeyPropertyName(unionType);
    const propNode = keyPropertyName && find(node.properties, (p) => p.symbol && p.kind === 303 /* PropertyAssignment */ && p.symbol.escapedName === keyPropertyName && isPossiblyDiscriminantValue(p.initializer));
    const propType = propNode && getContextFreeTypeOfExpression(propNode.initializer);
    return propType && getConstituentTypeForKeyType(unionType, propType);
  }
  function isOrContainsMatchingReference(source, target) {
    return isMatchingReference(source, target) || containsMatchingReference(source, target);
  }
  function hasMatchingArgument(expression, reference) {
    if (expression.arguments) {
      for (const argument of expression.arguments) {
        if (isOrContainsMatchingReference(reference, argument) || optionalChainContainsReference(argument, reference)) {
          return true;
        }
      }
    }
    if (expression.expression.kind === 211 /* PropertyAccessExpression */ && isOrContainsMatchingReference(reference, expression.expression.expression)) {
      return true;
    }
    return false;
  }
  function getFlowNodeId(flow) {
    if (flow.id <= 0) {
      flow.id = nextFlowId;
      nextFlowId++;
    }
    return flow.id;
  }
  function typeMaybeAssignableTo(source, target) {
    if (!(source.flags & 1048576 /* Union */)) {
      return isTypeAssignableTo(source, target);
    }
    for (const t of source.types) {
      if (isTypeAssignableTo(t, target)) {
        return true;
      }
    }
    return false;
  }
  function getAssignmentReducedType(declaredType, assignedType) {
    if (declaredType === assignedType) {
      return declaredType;
    }
    if (assignedType.flags & 131072 /* Never */) {
      return assignedType;
    }
    const key = `A${getTypeId(declaredType)},${getTypeId(assignedType)}`;
    return getCachedType(key) ?? setCachedType(key, getAssignmentReducedTypeWorker(declaredType, assignedType));
  }
  function getAssignmentReducedTypeWorker(declaredType, assignedType) {
    const filteredType = filterType(declaredType, (t) => typeMaybeAssignableTo(assignedType, t));
    const reducedType = assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType) ? mapType(filteredType, getFreshTypeOfLiteralType) : filteredType;
    return isTypeAssignableTo(assignedType, reducedType) ? reducedType : declaredType;
  }
  function isFunctionObjectType(type) {
    if (getObjectFlags(type) & 256 /* EvolvingArray */) {
      return false;
    }
    const resolved = resolveStructuredTypeMembers(type);
    return !!(resolved.callSignatures.length || resolved.constructSignatures.length || resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
  }
  function getTypeFacts(type, mask) {
    return getTypeFactsWorker(type, mask) & mask;
  }
  function hasTypeFacts(type, mask) {
    return getTypeFacts(type, mask) !== 0;
  }
  function getTypeFactsWorker(type, callerOnlyNeeds) {
    if (type.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */)) {
      type = getBaseConstraintOfType(type) || unknownType;
    }
    const flags = type.flags;
    if (flags & (4 /* String */ | 268435456 /* StringMapping */)) {
      return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
    }
    if (flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */)) {
      const isEmpty = flags & 128 /* StringLiteral */ && type.value === "";
      return strictNullChecks ? isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ : isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
    }
    if (flags & (8 /* Number */ | 32 /* Enum */)) {
      return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
    }
    if (flags & 256 /* NumberLiteral */) {
      const isZero = type.value === 0;
      return strictNullChecks ? isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ : isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
    }
    if (flags & 64 /* BigInt */) {
      return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
    }
    if (flags & 2048 /* BigIntLiteral */) {
      const isZero = isZeroBigInt(type);
      return strictNullChecks ? isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ : isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
    }
    if (flags & 16 /* Boolean */) {
      return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
    }
    if (flags & 528 /* BooleanLike */) {
      return strictNullChecks ? type === falseType || type === regularFalseType ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ : type === falseType || type === regularFalseType ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
    }
    if (flags & 524288 /* Object */) {
      const possibleFacts = strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ | 7880640 /* FunctionStrictFacts */ | 7888800 /* ObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ | 16728e3 /* FunctionFacts */ | 16736160 /* ObjectFacts */;
      if ((callerOnlyNeeds & possibleFacts) === 0) {
        return 0;
      }
      return getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ? strictNullChecks ? 83427327 /* EmptyObjectStrictFacts */ : 83886079 /* EmptyObjectFacts */ : isFunctionObjectType(type) ? strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728e3 /* FunctionFacts */ : strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
    }
    if (flags & 16384 /* Void */) {
      return 9830144 /* VoidFacts */;
    }
    if (flags & 32768 /* Undefined */) {
      return 26607360 /* UndefinedFacts */;
    }
    if (flags & 65536 /* Null */) {
      return 42917664 /* NullFacts */;
    }
    if (flags & 12288 /* ESSymbolLike */) {
      return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
    }
    if (flags & 67108864 /* NonPrimitive */) {
      return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
    }
    if (flags & 131072 /* Never */) {
      return 0 /* None */;
    }
    if (flags & 1048576 /* Union */) {
      return reduceLeft(type.types, (facts, t) => facts | getTypeFactsWorker(t, callerOnlyNeeds), 0 /* None */);
    }
    if (flags & 2097152 /* Intersection */) {
      return getIntersectionTypeFacts(type, callerOnlyNeeds);
    }
    return 83886079 /* UnknownFacts */;
  }
  function getIntersectionTypeFacts(type, callerOnlyNeeds) {
    const ignoreObjects = maybeTypeOfKind(type, 402784252 /* Primitive */);
    let oredFacts = 0 /* None */;
    let andedFacts = 134217727 /* All */;
    for (const t of type.types) {
      if (!(ignoreObjects && t.flags & 524288 /* Object */)) {
        const f = getTypeFactsWorker(t, callerOnlyNeeds);
        oredFacts |= f;
        andedFacts &= f;
      }
    }
    return oredFacts & 8256 /* OrFactsMask */ | andedFacts & 134209471 /* AndFactsMask */;
  }
  function getTypeWithFacts(type, include) {
    return filterType(type, (t) => hasTypeFacts(t, include));
  }
  function getAdjustedTypeWithFacts(type, facts) {
    const reduced = recombineUnknownType(getTypeWithFacts(strictNullChecks && type.flags & 2 /* Unknown */ ? unknownUnionType : type, facts));
    if (strictNullChecks) {
      switch (facts) {
        case 524288 /* NEUndefined */:
          return removeNullableByIntersection(reduced, 65536 /* EQUndefined */, 131072 /* EQNull */, 33554432 /* IsNull */, nullType);
        case 1048576 /* NENull */:
          return removeNullableByIntersection(reduced, 131072 /* EQNull */, 65536 /* EQUndefined */, 16777216 /* IsUndefined */, undefinedType);
        case 2097152 /* NEUndefinedOrNull */:
        case 4194304 /* Truthy */:
          return mapType(reduced, (t) => hasTypeFacts(t, 262144 /* EQUndefinedOrNull */) ? getGlobalNonNullableTypeInstantiation(t) : t);
      }
    }
    return reduced;
  }
  function removeNullableByIntersection(type, targetFacts, otherFacts, otherIncludesFacts, otherType) {
    const facts = getTypeFacts(type, 65536 /* EQUndefined */ | 131072 /* EQNull */ | 16777216 /* IsUndefined */ | 33554432 /* IsNull */);
    if (!(facts & targetFacts)) {
      return type;
    }
    const emptyAndOtherUnion = getUnionType([emptyObjectType, otherType]);
    return mapType(type, (t) => hasTypeFacts(t, targetFacts) ? getIntersectionType([t, !(facts & otherIncludesFacts) && hasTypeFacts(t, otherFacts) ? emptyAndOtherUnion : emptyObjectType]) : t);
  }
  function recombineUnknownType(type) {
    return type === unknownUnionType ? unknownType : type;
  }
  function getTypeWithDefault(type, defaultExpression) {
    return defaultExpression ? getUnionType([getNonUndefinedType(type), getTypeOfExpression(defaultExpression)]) : type;
  }
  function getTypeOfDestructuredProperty(type, name) {
    var _a;
    const nameType = getLiteralTypeFromPropertyName(name);
    if (!isTypeUsableAsPropertyName(nameType)) return errorType;
    const text = getPropertyNameFromType(nameType);
    return getTypeOfPropertyOfType(type, text) || includeUndefinedInIndexSignature((_a = getApplicableIndexInfoForName(type, text)) == null ? void 0 : _a.type) || errorType;
  }
  function getTypeOfDestructuredArrayElement(type, index) {
    return everyType(type, isTupleLikeType) && getTupleElementType(type, index) || includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(
      65 /* Destructuring */,
      type,
      undefinedType,
      /*errorNode*/
      void 0
    )) || errorType;
  }
  function includeUndefinedInIndexSignature(type) {
    if (!type) return type;
    return compilerOptions.noUncheckedIndexedAccess ? getUnionType([type, missingType]) : type;
  }
  function getTypeOfDestructuredSpreadExpression(type) {
    return createArrayType(checkIteratedTypeOrElementType(
      65 /* Destructuring */,
      type,
      undefinedType,
      /*errorNode*/
      void 0
    ) || errorType);
  }
  function getAssignedTypeOfBinaryExpression(node) {
    const isDestructuringDefaultAssignment = node.parent.kind === 209 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) || node.parent.kind === 303 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
    return isDestructuringDefaultAssignment ? getTypeWithDefault(getAssignedType(node), node.right) : getTypeOfExpression(node.right);
  }
  function isDestructuringAssignmentTarget(parent) {
    return parent.parent.kind === 226 /* BinaryExpression */ && parent.parent.left === parent || parent.parent.kind === 250 /* ForOfStatement */ && parent.parent.initializer === parent;
  }
  function getAssignedTypeOfArrayLiteralElement(node, element) {
    return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
  }
  function getAssignedTypeOfSpreadExpression(node) {
    return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
  }
  function getAssignedTypeOfPropertyAssignment(node) {
    return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
  }
  function getAssignedTypeOfShorthandPropertyAssignment(node) {
    return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
  }
  function getAssignedType(node) {
    const { parent } = node;
    switch (parent.kind) {
      case 249 /* ForInStatement */:
        return stringType;
      case 250 /* ForOfStatement */:
        return checkRightHandSideOfForOf(parent) || errorType;
      case 226 /* BinaryExpression */:
        return getAssignedTypeOfBinaryExpression(parent);
      case 220 /* DeleteExpression */:
        return undefinedType;
      case 209 /* ArrayLiteralExpression */:
        return getAssignedTypeOfArrayLiteralElement(parent, node);
      case 230 /* SpreadElement */:
        return getAssignedTypeOfSpreadExpression(parent);
      case 303 /* PropertyAssignment */:
        return getAssignedTypeOfPropertyAssignment(parent);
      case 304 /* ShorthandPropertyAssignment */:
        return getAssignedTypeOfShorthandPropertyAssignment(parent);
    }
    return errorType;
  }
  function getInitialTypeOfBindingElement(node) {
    const pattern = node.parent;
    const parentType = getInitialType(pattern.parent);
    const type = pattern.kind === 206 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType);
    return getTypeWithDefault(type, node.initializer);
  }
  function getTypeOfInitializer(node) {
    const links = getNodeLinks(node);
    return links.resolvedType || getTypeOfExpression(node);
  }
  function getInitialTypeOfVariableDeclaration(node) {
    if (node.initializer) {
      return getTypeOfInitializer(node.initializer);
    }
    if (node.parent.parent.kind === 249 /* ForInStatement */) {
      return stringType;
    }
    if (node.parent.parent.kind === 250 /* ForOfStatement */) {
      return checkRightHandSideOfForOf(node.parent.parent) || errorType;
    }
    return errorType;
  }
  function getInitialType(node) {
    return node.kind === 260 /* VariableDeclaration */ ? getInitialTypeOfVariableDeclaration(node) : getInitialTypeOfBindingElement(node);
  }
  function isEmptyArrayAssignment(node) {
    return node.kind === 260 /* VariableDeclaration */ && node.initializer && isEmptyArrayLiteral2(node.initializer) || node.kind !== 208 /* BindingElement */ && node.parent.kind === 226 /* BinaryExpression */ && isEmptyArrayLiteral2(node.parent.right);
  }
  function getReferenceCandidate(node) {
    switch (node.kind) {
      case 217 /* ParenthesizedExpression */:
        return getReferenceCandidate(node.expression);
      case 226 /* BinaryExpression */:
        switch (node.operatorToken.kind) {
          case 64 /* EqualsToken */:
          case 76 /* BarBarEqualsToken */:
          case 77 /* AmpersandAmpersandEqualsToken */:
          case 78 /* QuestionQuestionEqualsToken */:
            return getReferenceCandidate(node.left);
          case 28 /* CommaToken */:
            return getReferenceCandidate(node.right);
        }
    }
    return node;
  }
  function getReferenceRoot(node) {
    const { parent } = node;
    return parent.kind === 217 /* ParenthesizedExpression */ || parent.kind === 226 /* BinaryExpression */ && parent.operatorToken.kind === 64 /* EqualsToken */ && parent.left === node || parent.kind === 226 /* BinaryExpression */ && parent.operatorToken.kind === 28 /* CommaToken */ && parent.right === node ? getReferenceRoot(parent) : node;
  }
  function getTypeOfSwitchClause(clause) {
    if (clause.kind === 296 /* CaseClause */) {
      return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
    }
    return neverType;
  }
  function getSwitchClauseTypes(switchStatement) {
    const links = getNodeLinks(switchStatement);
    if (!links.switchTypes) {
      links.switchTypes = [];
      for (const clause of switchStatement.caseBlock.clauses) {
        links.switchTypes.push(getTypeOfSwitchClause(clause));
      }
    }
    return links.switchTypes;
  }
  function getSwitchClauseTypeOfWitnesses(switchStatement) {
    if (some(switchStatement.caseBlock.clauses, (clause) => clause.kind === 296 /* CaseClause */ && !isStringLiteralLike(clause.expression))) {
      return void 0;
    }
    const witnesses = [];
    for (const clause of switchStatement.caseBlock.clauses) {
      const text = clause.kind === 296 /* CaseClause */ ? clause.expression.text : void 0;
      witnesses.push(text && !contains(witnesses, text) ? text : void 0);
    }
    return witnesses;
  }
  function eachTypeContainedIn(source, types) {
    return source.flags & 1048576 /* Union */ ? !forEach(source.types, (t) => !contains(types, t)) : contains(types, source);
  }
  function isTypeSubsetOf(source, target) {
    return !!(source === target || source.flags & 131072 /* Never */ || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target));
  }
  function isTypeSubsetOfUnion(source, target) {
    if (source.flags & 1048576 /* Union */) {
      for (const t of source.types) {
        if (!containsType(target.types, t)) {
          return false;
        }
      }
      return true;
    }
    if (source.flags & 1056 /* EnumLike */ && getBaseTypeOfEnumLikeType(source) === target) {
      return true;
    }
    return containsType(target.types, source);
  }
  function forEachType(type, f) {
    return type.flags & 1048576 /* Union */ ? forEach(type.types, f) : f(type);
  }
  function someType(type, f) {
    return type.flags & 1048576 /* Union */ ? some(type.types, f) : f(type);
  }
  function everyType(type, f) {
    return type.flags & 1048576 /* Union */ ? every(type.types, f) : f(type);
  }
  function everyContainedType(type, f) {
    return type.flags & 3145728 /* UnionOrIntersection */ ? every(type.types, f) : f(type);
  }
  function filterType(type, f) {
    if (type.flags & 1048576 /* Union */) {
      const types = type.types;
      const filtered = filter(types, f);
      if (filtered === types) {
        return type;
      }
      const origin = type.origin;
      let newOrigin;
      if (origin && origin.flags & 1048576 /* Union */) {
        const originTypes = origin.types;
        const originFiltered = filter(originTypes, (t) => !!(t.flags & 1048576 /* Union */) || f(t));
        if (originTypes.length - originFiltered.length === types.length - filtered.length) {
          if (originFiltered.length === 1) {
            return originFiltered[0];
          }
          newOrigin = createOriginUnionOrIntersectionType(1048576 /* Union */, originFiltered);
        }
      }
      return getUnionTypeFromSortedList(
        filtered,
        type.objectFlags & (32768 /* PrimitiveUnion */ | 16777216 /* ContainsIntersections */),
        /*aliasSymbol*/
        void 0,
        /*aliasTypeArguments*/
        void 0,
        newOrigin
      );
    }
    return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
  }
  function removeType(type, targetType) {
    return filterType(type, (t) => t !== targetType);
  }
  function countTypes(type) {
    return type.flags & 1048576 /* Union */ ? type.types.length : 1;
  }
  function mapType(type, mapper, noReductions) {
    if (type.flags & 131072 /* Never */) {
      return type;
    }
    if (!(type.flags & 1048576 /* Union */)) {
      return mapper(type);
    }
    const origin = type.origin;
    const types = origin && origin.flags & 1048576 /* Union */ ? origin.types : type.types;
    let mappedTypes;
    let changed = false;
    for (const t of types) {
      const mapped = t.flags & 1048576 /* Union */ ? mapType(t, mapper, noReductions) : mapper(t);
      changed || (changed = t !== mapped);
      if (mapped) {
        if (!mappedTypes) {
          mappedTypes = [mapped];
        } else {
          mappedTypes.push(mapped);
        }
      }
    }
    return changed ? mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */) : type;
  }
  function mapTypeWithAlias(type, mapper, aliasSymbol, aliasTypeArguments) {
    return type.flags & 1048576 /* Union */ && aliasSymbol ? getUnionType(map(type.types, mapper), 1 /* Literal */, aliasSymbol, aliasTypeArguments) : mapType(type, mapper);
  }
  function extractTypesOfKind(type, kind) {
    return filterType(type, (t) => (t.flags & kind) !== 0);
  }
  function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
    if (maybeTypeOfKind(typeWithPrimitives, 4 /* String */ | 134217728 /* TemplateLiteral */ | 8 /* Number */ | 64 /* BigInt */) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 256 /* NumberLiteral */ | 2048 /* BigIntLiteral */)) {
      return mapType(typeWithPrimitives, (t) => t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) : isPatternLiteralType(t) && !maybeTypeOfKind(typeWithLiterals, 4 /* String */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) ? extractTypesOfKind(typeWithLiterals, 128 /* StringLiteral */) : t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) : t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t);
    }
    return typeWithPrimitives;
  }
  function isIncomplete(flowType) {
    return flowType.flags === 0;
  }
  function getTypeFromFlowType(flowType) {
    return flowType.flags === 0 ? flowType.type : flowType;
  }
  function createFlowType(type, incomplete) {
    return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type;
  }
  function createEvolvingArrayType(elementType) {
    const result = createObjectType(256 /* EvolvingArray */);
    result.elementType = elementType;
    return result;
  }
  function getEvolvingArrayType(elementType) {
    return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
  }
  function addEvolvingArrayElementType(evolvingArrayType, node) {
    const elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)));
    return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
  }
  function createFinalArrayType(elementType) {
    return elementType.flags & 131072 /* Never */ ? autoArrayType : createArrayType(
      elementType.flags & 1048576 /* Union */ ? getUnionType(elementType.types, 2 /* Subtype */) : elementType
    );
  }
  function getFinalArrayType(evolvingArrayType) {
    return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
  }
  function finalizeEvolvingArrayType(type) {
    return getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
  }
  function getElementTypeOfEvolvingArrayType(type) {
    return getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
  }
  function isEvolvingArrayTypeList(types) {
    let hasEvolvingArrayType = false;
    for (const t of types) {
      if (!(t.flags & 131072 /* Never */)) {
        if (!(getObjectFlags(t) & 256 /* EvolvingArray */)) {
          return false;
        }
        hasEvolvingArrayType = true;
      }
    }
    return hasEvolvingArrayType;
  }
  function isEvolvingArrayOperationTarget(node) {
    const root = getReferenceRoot(node);
    const parent = root.parent;
    const isLengthPushOrUnshift = isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" || parent.parent.kind === 213 /* CallExpression */ && isIdentifier(parent.name) && isPushOrUnshiftIdentifier(parent.name));
    const isElementAssignment = parent.kind === 212 /* ElementAccessExpression */ && parent.expression === root && parent.parent.kind === 226 /* BinaryExpression */ && parent.parent.operatorToken.kind === 64 /* EqualsToken */ && parent.parent.left === parent && !isAssignmentTarget(parent.parent) && isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
    return isLengthPushOrUnshift || isElementAssignment;
  }
  function isDeclarationWithExplicitTypeAnnotation(node) {
    return (isVariableDeclaration(node) || isPropertyDeclaration(node) || isPropertySignature(node) || isParameter(node)) && !!(getEffectiveTypeAnnotationNode(node) || isInJSFile(node) && hasInitializer(node) && node.initializer && isFunctionExpressionOrArrowFunction(node.initializer) && getEffectiveReturnTypeNode(node.initializer));
  }
  function getExplicitTypeOfSymbol(symbol, diagnostic) {
    symbol = resolveSymbol(symbol);
    if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
      return getTypeOfSymbol(symbol);
    }
    if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
      if (getCheckFlags(symbol) & 262144 /* Mapped */) {
        const origin = symbol.links.syntheticOrigin;
        if (origin && getExplicitTypeOfSymbol(origin)) {
          return getTypeOfSymbol(symbol);
        }
      }
      const declaration = symbol.valueDeclaration;
      if (declaration) {
        if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
          return getTypeOfSymbol(symbol);
        }
        if (isVariableDeclaration(declaration) && declaration.parent.parent.kind === 250 /* ForOfStatement */) {
          const statement = declaration.parent.parent;
          const expressionType = getTypeOfDottedName(
            statement.expression,
            /*diagnostic*/
            void 0
          );
          if (expressionType) {
            const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
            return checkIteratedTypeOrElementType(
              use,
              expressionType,
              undefinedType,
              /*errorNode*/
              void 0
            );
          }
        }
        if (diagnostic) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(declaration, Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
        }
      }
    }
  }
  function getTypeOfDottedName(node, diagnostic) {
    if (!(node.flags & 67108864 /* InWithStatement */)) {
      switch (node.kind) {
        case 80 /* Identifier */:
          const symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
          return getExplicitTypeOfSymbol(symbol, diagnostic);
        case 110 /* ThisKeyword */:
          return getExplicitThisType(node);
        case 108 /* SuperKeyword */:
          return checkSuperExpression(node);
        case 211 /* PropertyAccessExpression */: {
          const type = getTypeOfDottedName(node.expression, diagnostic);
          if (type) {
            const name = node.name;
            let prop;
            if (isPrivateIdentifier(name)) {
              if (!type.symbol) {
                return void 0;
              }
              prop = getPropertyOfType(type, getSymbolNameForPrivateIdentifier(type.symbol, name.escapedText));
            } else {
              prop = getPropertyOfType(type, name.escapedText);
            }
            return prop && getExplicitTypeOfSymbol(prop, diagnostic);
          }
          return void 0;
        }
        case 217 /* ParenthesizedExpression */:
          return getTypeOfDottedName(node.expression, diagnostic);
      }
    }
  }
  function getEffectsSignature(node) {
    const links = getNodeLinks(node);
    let signature = links.effectsSignature;
    if (signature === void 0) {
      let funcType;
      if (isBinaryExpression(node)) {
        const rightType = checkNonNullExpression(node.right);
        funcType = getSymbolHasInstanceMethodOfObjectType(rightType);
      } else if (node.parent.kind === 244 /* ExpressionStatement */) {
        funcType = getTypeOfDottedName(
          node.expression,
          /*diagnostic*/
          void 0
        );
      } else if (node.expression.kind !== 108 /* SuperKeyword */) {
        if (isOptionalChain(node)) {
          funcType = checkNonNullType(
            getOptionalExpressionType(checkExpression(node.expression), node.expression),
            node.expression
          );
        } else {
          funcType = checkNonNullExpression(node.expression);
        }
      }
      const signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
      const candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : void 0;
      signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
    }
    return signature === unknownSignature ? void 0 : signature;
  }
  function hasTypePredicateOrNeverReturnType(signature) {
    return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
  }
  function getTypePredicateArgument(predicate, callExpression) {
    if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
      return callExpression.arguments[predicate.parameterIndex];
    }
    const invokedExpression = skipParentheses(callExpression.expression);
    return isAccessExpression(invokedExpression) ? skipParentheses(invokedExpression.expression) : void 0;
  }
  function reportFlowControlError(node) {
    const block = findAncestor(node, isFunctionOrModuleBlock);
    const sourceFile = getSourceFileOfNode(node);
    const span = getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
    diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
  }
  function isReachableFlowNode(flow) {
    const result = isReachableFlowNodeWorker(
      flow,
      /*noCacheCheck*/
      false
    );
    lastFlowNode = flow;
    lastFlowNodeReachable = result;
    return result;
  }
  function isFalseExpression(expr) {
    const node = skipParentheses(
      expr,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return node.kind === 97 /* FalseKeyword */ || node.kind === 226 /* BinaryExpression */ && (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || node.operatorToken.kind === 57 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
  }
  function isReachableFlowNodeWorker(flow, noCacheCheck) {
    while (true) {
      if (flow === lastFlowNode) {
        return lastFlowNodeReachable;
      }
      const flags = flow.flags;
      if (flags & 4096 /* Shared */) {
        if (!noCacheCheck) {
          const id = getFlowNodeId(flow);
          const reachable = flowNodeReachable[id];
          return reachable !== void 0 ? reachable : flowNodeReachable[id] = isReachableFlowNodeWorker(
            flow,
            /*noCacheCheck*/
            true
          );
        }
        noCacheCheck = false;
      }
      if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
        flow = flow.antecedent;
      } else if (flags & 512 /* Call */) {
        const signature = getEffectsSignature(flow.node);
        if (signature) {
          const predicate = getTypePredicateOfSignature(signature);
          if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) {
            const predicateArgument = flow.node.arguments[predicate.parameterIndex];
            if (predicateArgument && isFalseExpression(predicateArgument)) {
              return false;
            }
          }
          if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
            return false;
          }
        }
        flow = flow.antecedent;
      } else if (flags & 4 /* BranchLabel */) {
        return some(flow.antecedent, (f) => isReachableFlowNodeWorker(
          f,
          /*noCacheCheck*/
          false
        ));
      } else if (flags & 8 /* LoopLabel */) {
        const antecedents = flow.antecedent;
        if (antecedents === void 0 || antecedents.length === 0) {
          return false;
        }
        flow = antecedents[0];
      } else if (flags & 128 /* SwitchClause */) {
        const data = flow.node;
        if (data.clauseStart === data.clauseEnd && isExhaustiveSwitchStatement(data.switchStatement)) {
          return false;
        }
        flow = flow.antecedent;
      } else if (flags & 1024 /* ReduceLabel */) {
        lastFlowNode = void 0;
        const target = flow.node.target;
        const saveAntecedents = target.antecedent;
        target.antecedent = flow.node.antecedents;
        const result = isReachableFlowNodeWorker(
          flow.antecedent,
          /*noCacheCheck*/
          false
        );
        target.antecedent = saveAntecedents;
        return result;
      } else {
        return !(flags & 1 /* Unreachable */);
      }
    }
  }
  function isPostSuperFlowNode(flow, noCacheCheck) {
    while (true) {
      const flags = flow.flags;
      if (flags & 4096 /* Shared */) {
        if (!noCacheCheck) {
          const id = getFlowNodeId(flow);
          const postSuper = flowNodePostSuper[id];
          return postSuper !== void 0 ? postSuper : flowNodePostSuper[id] = isPostSuperFlowNode(
            flow,
            /*noCacheCheck*/
            true
          );
        }
        noCacheCheck = false;
      }
      if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) {
        flow = flow.antecedent;
      } else if (flags & 512 /* Call */) {
        if (flow.node.expression.kind === 108 /* SuperKeyword */) {
          return true;
        }
        flow = flow.antecedent;
      } else if (flags & 4 /* BranchLabel */) {
        return every(flow.antecedent, (f) => isPostSuperFlowNode(
          f,
          /*noCacheCheck*/
          false
        ));
      } else if (flags & 8 /* LoopLabel */) {
        flow = flow.antecedent[0];
      } else if (flags & 1024 /* ReduceLabel */) {
        const target = flow.node.target;
        const saveAntecedents = target.antecedent;
        target.antecedent = flow.node.antecedents;
        const result = isPostSuperFlowNode(
          flow.antecedent,
          /*noCacheCheck*/
          false
        );
        target.antecedent = saveAntecedents;
        return result;
      } else {
        return !!(flags & 1 /* Unreachable */);
      }
    }
  }
  function isConstantReference(node) {
    switch (node.kind) {
      case 110 /* ThisKeyword */:
        return true;
      case 80 /* Identifier */:
        if (!isThisInTypeQuery(node)) {
          const symbol = getResolvedSymbol(node);
          return isConstantVariable(symbol) || isParameterOrMutableLocalVariable(symbol) && !isSymbolAssigned(symbol) || !!symbol.valueDeclaration && isFunctionExpression(symbol.valueDeclaration);
        }
        break;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return isConstantReference(node.expression) && isReadonlySymbol(getNodeLinks(node).resolvedSymbol || unknownSymbol);
      case 206 /* ObjectBindingPattern */:
      case 207 /* ArrayBindingPattern */:
        const rootDeclaration = getRootDeclaration(node.parent);
        return isParameter(rootDeclaration) || isCatchClauseVariableDeclaration(rootDeclaration) ? !isSomeSymbolAssigned(rootDeclaration) : isVariableDeclaration(rootDeclaration) && isVarConstLike2(rootDeclaration);
    }
    return false;
  }
  function getFlowTypeOfReference(reference, declaredType, initialType = declaredType, flowContainer, flowNode = ((_a) => (_a = tryCast(reference, canHaveFlowNode)) == null ? void 0 : _a.flowNode)()) {
    let key;
    let isKeySet = false;
    let flowDepth = 0;
    if (flowAnalysisDisabled) {
      return errorType;
    }
    if (!flowNode) {
      return declaredType;
    }
    flowInvocationCount++;
    const sharedFlowStart = sharedFlowCount;
    const evolvedType = getTypeFromFlowType(getTypeAtFlowNode(flowNode));
    sharedFlowCount = sharedFlowStart;
    const resultType = getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
    if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 235 /* NonNullExpression */ && !(resultType.flags & 131072 /* Never */) && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
      return declaredType;
    }
    return resultType;
    function getOrSetCacheKey() {
      if (isKeySet) {
        return key;
      }
      isKeySet = true;
      return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
    }
    function getTypeAtFlowNode(flow) {
      var _a2;
      if (flowDepth === 2e3) {
        (_a2 = tracing) == null ? void 0 : _a2.instant(tracing.Phase.CheckTypes, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
        flowAnalysisDisabled = true;
        reportFlowControlError(reference);
        return errorType;
      }
      flowDepth++;
      let sharedFlow;
      while (true) {
        const flags = flow.flags;
        if (flags & 4096 /* Shared */) {
          for (let i = sharedFlowStart; i < sharedFlowCount; i++) {
            if (sharedFlowNodes[i] === flow) {
              flowDepth--;
              return sharedFlowTypes[i];
            }
          }
          sharedFlow = flow;
        }
        let type;
        if (flags & 16 /* Assignment */) {
          type = getTypeAtFlowAssignment(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & 512 /* Call */) {
          type = getTypeAtFlowCall(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & 96 /* Condition */) {
          type = getTypeAtFlowCondition(flow);
        } else if (flags & 128 /* SwitchClause */) {
          type = getTypeAtSwitchClause(flow);
        } else if (flags & 12 /* Label */) {
          if (flow.antecedent.length === 1) {
            flow = flow.antecedent[0];
            continue;
          }
          type = flags & 4 /* BranchLabel */ ? getTypeAtFlowBranchLabel(flow) : getTypeAtFlowLoopLabel(flow);
        } else if (flags & 256 /* ArrayMutation */) {
          type = getTypeAtFlowArrayMutation(flow);
          if (!type) {
            flow = flow.antecedent;
            continue;
          }
        } else if (flags & 1024 /* ReduceLabel */) {
          const target = flow.node.target;
          const saveAntecedents = target.antecedent;
          target.antecedent = flow.node.antecedents;
          type = getTypeAtFlowNode(flow.antecedent);
          target.antecedent = saveAntecedents;
        } else if (flags & 2 /* Start */) {
          const container = flow.node;
          if (container && container !== flowContainer && reference.kind !== 211 /* PropertyAccessExpression */ && reference.kind !== 212 /* ElementAccessExpression */ && !(reference.kind === 110 /* ThisKeyword */ && container.kind !== 219 /* ArrowFunction */)) {
            flow = container.flowNode;
            continue;
          }
          type = initialType;
        } else {
          type = convertAutoToAny(declaredType);
        }
        if (sharedFlow) {
          sharedFlowNodes[sharedFlowCount] = sharedFlow;
          sharedFlowTypes[sharedFlowCount] = type;
          sharedFlowCount++;
        }
        flowDepth--;
        return type;
      }
    }
    function getInitialOrAssignedType(flow) {
      const node = flow.node;
      return getNarrowableTypeForReference(
        node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */ ? getInitialType(node) : getAssignedType(node),
        reference
      );
    }
    function getTypeAtFlowAssignment(flow) {
      const node = flow.node;
      if (isMatchingReference(reference, node)) {
        if (!isReachableFlowNode(flow)) {
          return unreachableNeverType;
        }
        if (getAssignmentTargetKind(node) === 2 /* Compound */) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
        }
        if (declaredType === autoType || declaredType === autoArrayType) {
          if (isEmptyArrayAssignment(node)) {
            return getEvolvingArrayType(neverType);
          }
          const assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow));
          return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
        }
        const t = isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(declaredType) : declaredType;
        if (t.flags & 1048576 /* Union */) {
          return getAssignmentReducedType(t, getInitialOrAssignedType(flow));
        }
        return t;
      }
      if (containsMatchingReference(reference, node)) {
        if (!isReachableFlowNode(flow)) {
          return unreachableNeverType;
        }
        if (isVariableDeclaration(node) && (isInJSFile(node) || isVarConstLike2(node))) {
          const init = getDeclaredExpandoInitializer(node);
          if (init && (init.kind === 218 /* FunctionExpression */ || init.kind === 219 /* ArrowFunction */)) {
            return getTypeAtFlowNode(flow.antecedent);
          }
        }
        return declaredType;
      }
      if (isVariableDeclaration(node) && node.parent.parent.kind === 249 /* ForInStatement */ && (isMatchingReference(reference, node.parent.parent.expression) || optionalChainContainsReference(node.parent.parent.expression, reference))) {
        return getNonNullableTypeIfNeeded(finalizeEvolvingArrayType(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent))));
      }
      return void 0;
    }
    function narrowTypeByAssertion(type, expr) {
      const node = skipParentheses(
        expr,
        /*excludeJSDocTypeAssertions*/
        true
      );
      if (node.kind === 97 /* FalseKeyword */) {
        return unreachableNeverType;
      }
      if (node.kind === 226 /* BinaryExpression */) {
        if (node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) {
          return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
        }
        if (node.operatorToken.kind === 57 /* BarBarToken */) {
          return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
        }
      }
      return narrowType(
        type,
        node,
        /*assumeTrue*/
        true
      );
    }
    function getTypeAtFlowCall(flow) {
      const signature = getEffectsSignature(flow.node);
      if (signature) {
        const predicate = getTypePredicateOfSignature(signature);
        if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          const type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
          const narrowedType = predicate.type ? narrowTypeByTypePredicate(
            type,
            predicate,
            flow.node,
            /*assumeTrue*/
            true
          ) : predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type;
          return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
        }
        if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
          return unreachableNeverType;
        }
      }
      return void 0;
    }
    function getTypeAtFlowArrayMutation(flow) {
      if (declaredType === autoType || declaredType === autoArrayType) {
        const node = flow.node;
        const expr = node.kind === 213 /* CallExpression */ ? node.expression.expression : node.left.expression;
        if (isMatchingReference(reference, getReferenceCandidate(expr))) {
          const flowType = getTypeAtFlowNode(flow.antecedent);
          const type = getTypeFromFlowType(flowType);
          if (getObjectFlags(type) & 256 /* EvolvingArray */) {
            let evolvedType2 = type;
            if (node.kind === 213 /* CallExpression */) {
              for (const arg of node.arguments) {
                evolvedType2 = addEvolvingArrayElementType(evolvedType2, arg);
              }
            } else {
              const indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
              if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
                evolvedType2 = addEvolvingArrayElementType(evolvedType2, node.right);
              }
            }
            return evolvedType2 === type ? flowType : createFlowType(evolvedType2, isIncomplete(flowType));
          }
          return flowType;
        }
      }
      return void 0;
    }
    function getTypeAtFlowCondition(flow) {
      const flowType = getTypeAtFlowNode(flow.antecedent);
      const type = getTypeFromFlowType(flowType);
      if (type.flags & 131072 /* Never */) {
        return flowType;
      }
      const assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
      const nonEvolvingType = finalizeEvolvingArrayType(type);
      const narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
      if (narrowedType === nonEvolvingType) {
        return flowType;
      }
      return createFlowType(narrowedType, isIncomplete(flowType));
    }
    function getTypeAtSwitchClause(flow) {
      const expr = skipParentheses(flow.node.switchStatement.expression);
      const flowType = getTypeAtFlowNode(flow.antecedent);
      let type = getTypeFromFlowType(flowType);
      if (isMatchingReference(reference, expr)) {
        type = narrowTypeBySwitchOnDiscriminant(type, flow.node);
      } else if (expr.kind === 221 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
        type = narrowTypeBySwitchOnTypeOf(type, flow.node);
      } else if (expr.kind === 112 /* TrueKeyword */) {
        type = narrowTypeBySwitchOnTrue(type, flow.node);
      } else {
        if (strictNullChecks) {
          if (optionalChainContainsReference(expr, reference)) {
            type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)));
          } else if (expr.kind === 221 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
            type = narrowTypeBySwitchOptionalChainContainment(type, flow.node, (t) => !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"));
          }
        }
        const access = getDiscriminantPropertyAccess(expr, type);
        if (access) {
          type = narrowTypeBySwitchOnDiscriminantProperty(type, access, flow.node);
        }
      }
      return createFlowType(type, isIncomplete(flowType));
    }
    function getTypeAtFlowBranchLabel(flow) {
      const antecedentTypes = [];
      let subtypeReduction = false;
      let seenIncomplete = false;
      let bypassFlow;
      for (const antecedent of flow.antecedent) {
        if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.node.clauseStart === antecedent.node.clauseEnd) {
          bypassFlow = antecedent;
          continue;
        }
        const flowType = getTypeAtFlowNode(antecedent);
        const type = getTypeFromFlowType(flowType);
        if (type === declaredType && declaredType === initialType) {
          return type;
        }
        pushIfUnique(antecedentTypes, type);
        if (!isTypeSubsetOf(type, initialType)) {
          subtypeReduction = true;
        }
        if (isIncomplete(flowType)) {
          seenIncomplete = true;
        }
      }
      if (bypassFlow) {
        const flowType = getTypeAtFlowNode(bypassFlow);
        const type = getTypeFromFlowType(flowType);
        if (!(type.flags & 131072 /* Never */) && !contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.node.switchStatement)) {
          if (type === declaredType && declaredType === initialType) {
            return type;
          }
          antecedentTypes.push(type);
          if (!isTypeSubsetOf(type, initialType)) {
            subtypeReduction = true;
          }
          if (isIncomplete(flowType)) {
            seenIncomplete = true;
          }
        }
      }
      return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
    }
    function getTypeAtFlowLoopLabel(flow) {
      const id = getFlowNodeId(flow);
      const cache = flowLoopCaches[id] || (flowLoopCaches[id] = /* @__PURE__ */ new Map());
      const key2 = getOrSetCacheKey();
      if (!key2) {
        return declaredType;
      }
      const cached = cache.get(key2);
      if (cached) {
        return cached;
      }
      for (let i = flowLoopStart; i < flowLoopCount; i++) {
        if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key2 && flowLoopTypes[i].length) {
          return createFlowType(
            getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */),
            /*incomplete*/
            true
          );
        }
      }
      const antecedentTypes = [];
      let subtypeReduction = false;
      let firstAntecedentType;
      for (const antecedent of flow.antecedent) {
        let flowType;
        if (!firstAntecedentType) {
          flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
        } else {
          flowLoopNodes[flowLoopCount] = flow;
          flowLoopKeys[flowLoopCount] = key2;
          flowLoopTypes[flowLoopCount] = antecedentTypes;
          flowLoopCount++;
          const saveFlowTypeCache = flowTypeCache;
          flowTypeCache = void 0;
          flowType = getTypeAtFlowNode(antecedent);
          flowTypeCache = saveFlowTypeCache;
          flowLoopCount--;
          const cached2 = cache.get(key2);
          if (cached2) {
            return cached2;
          }
        }
        const type = getTypeFromFlowType(flowType);
        pushIfUnique(antecedentTypes, type);
        if (!isTypeSubsetOf(type, initialType)) {
          subtypeReduction = true;
        }
        if (type === declaredType) {
          break;
        }
      }
      const result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
      if (isIncomplete(firstAntecedentType)) {
        return createFlowType(
          result,
          /*incomplete*/
          true
        );
      }
      cache.set(key2, result);
      return result;
    }
    function getUnionOrEvolvingArrayType(types, subtypeReduction) {
      if (isEvolvingArrayTypeList(types)) {
        return getEvolvingArrayType(getUnionType(map(types, getElementTypeOfEvolvingArrayType)));
      }
      const result = recombineUnknownType(getUnionType(sameMap(types, finalizeEvolvingArrayType), subtypeReduction));
      if (result !== declaredType && result.flags & declaredType.flags & 1048576 /* Union */ && arrayIsEqualTo(result.types, declaredType.types)) {
        return declaredType;
      }
      return result;
    }
    function getCandidateDiscriminantPropertyAccess(expr) {
      if (isBindingPattern(reference) || isFunctionExpressionOrArrowFunction(reference) || isObjectLiteralMethod(reference)) {
        if (isIdentifier(expr)) {
          const symbol = getResolvedSymbol(expr);
          const declaration = symbol.valueDeclaration;
          if (declaration && (isBindingElement(declaration) || isParameter(declaration)) && reference === declaration.parent && !declaration.initializer && !declaration.dotDotDotToken) {
            return declaration;
          }
        }
      } else if (isAccessExpression(expr)) {
        if (isMatchingReference(reference, expr.expression)) {
          return expr;
        }
      } else if (isIdentifier(expr)) {
        const symbol = getResolvedSymbol(expr);
        if (isConstantVariable(symbol)) {
          const declaration = symbol.valueDeclaration;
          if (isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isAccessExpression(declaration.initializer) && isMatchingReference(reference, declaration.initializer.expression)) {
            return declaration.initializer;
          }
          if (isBindingElement(declaration) && !declaration.initializer) {
            const parent = declaration.parent.parent;
            if (isVariableDeclaration(parent) && !parent.type && parent.initializer && (isIdentifier(parent.initializer) || isAccessExpression(parent.initializer)) && isMatchingReference(reference, parent.initializer)) {
              return declaration;
            }
          }
        }
      }
      return void 0;
    }
    function getDiscriminantPropertyAccess(expr, computedType) {
      if (declaredType.flags & 1048576 /* Union */ || computedType.flags & 1048576 /* Union */) {
        const access = getCandidateDiscriminantPropertyAccess(expr);
        if (access) {
          const name = getAccessedPropertyName(access);
          if (name) {
            const type = declaredType.flags & 1048576 /* Union */ && isTypeSubsetOf(computedType, declaredType) ? declaredType : computedType;
            if (isDiscriminantProperty(type, name)) {
              return access;
            }
          }
        }
      }
      return void 0;
    }
    function narrowTypeByDiscriminant(type, access, narrowType2) {
      const propName = getAccessedPropertyName(access);
      if (propName === void 0) {
        return type;
      }
      const optionalChain = isOptionalChain(access);
      const removeNullable = strictNullChecks && (optionalChain || isNonNullAccess(access)) && maybeTypeOfKind(type, 98304 /* Nullable */);
      let propType = getTypeOfPropertyOfType(removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type, propName);
      if (!propType) {
        return type;
      }
      propType = removeNullable && optionalChain ? getOptionalType(propType) : propType;
      const narrowedPropType = narrowType2(propType);
      return filterType(type, (t) => {
        const discriminantType = getTypeOfPropertyOrIndexSignatureOfType(t, propName) || unknownType;
        return !(discriminantType.flags & 131072 /* Never */) && !(narrowedPropType.flags & 131072 /* Never */) && areTypesComparable(narrowedPropType, discriminantType);
      });
    }
    function narrowTypeByDiscriminantProperty(type, access, operator, value, assumeTrue) {
      if ((operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) && type.flags & 1048576 /* Union */) {
        const keyPropertyName = getKeyPropertyName(type);
        if (keyPropertyName && keyPropertyName === getAccessedPropertyName(access)) {
          const candidate = getConstituentTypeForKeyType(type, getTypeOfExpression(value));
          if (candidate) {
            return operator === (assumeTrue ? 37 /* EqualsEqualsEqualsToken */ : 38 /* ExclamationEqualsEqualsToken */) ? candidate : isUnitType(getTypeOfPropertyOfType(candidate, keyPropertyName) || unknownType) ? removeType(type, candidate) : type;
          }
        }
      }
      return narrowTypeByDiscriminant(type, access, (t) => narrowTypeByEquality(t, operator, value, assumeTrue));
    }
    function narrowTypeBySwitchOnDiscriminantProperty(type, access, data) {
      if (data.clauseStart < data.clauseEnd && type.flags & 1048576 /* Union */ && getKeyPropertyName(type) === getAccessedPropertyName(access)) {
        const clauseTypes = getSwitchClauseTypes(data.switchStatement).slice(data.clauseStart, data.clauseEnd);
        const candidate = getUnionType(map(clauseTypes, (t) => getConstituentTypeForKeyType(type, t) || unknownType));
        if (candidate !== unknownType) {
          return candidate;
        }
      }
      return narrowTypeByDiscriminant(type, access, (t) => narrowTypeBySwitchOnDiscriminant(t, data));
    }
    function narrowTypeByTruthiness(type, expr, assumeTrue) {
      if (isMatchingReference(reference, expr)) {
        return getAdjustedTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
      }
      if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
        type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
      }
      const access = getDiscriminantPropertyAccess(expr, type);
      if (access) {
        return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */));
      }
      return type;
    }
    function isTypePresencePossible(type, propName, assumeTrue) {
      const prop = getPropertyOfType(type, propName);
      return prop ? !!(prop.flags & 16777216 /* Optional */ || getCheckFlags(prop) & 48 /* Partial */) || assumeTrue : !!getApplicableIndexInfoForName(type, propName) || !assumeTrue;
    }
    function narrowTypeByInKeyword(type, nameType, assumeTrue) {
      const name = getPropertyNameFromType(nameType);
      const isKnownProperty2 = someType(type, (t) => isTypePresencePossible(
        t,
        name,
        /*assumeTrue*/
        true
      ));
      if (isKnownProperty2) {
        return filterType(type, (t) => isTypePresencePossible(t, name, assumeTrue));
      }
      if (assumeTrue) {
        const recordSymbol = getGlobalRecordSymbol();
        if (recordSymbol) {
          return getIntersectionType([type, getTypeAliasInstantiation(recordSymbol, [nameType, unknownType])]);
        }
      }
      return type;
    }
    function narrowTypeByBooleanComparison(type, expr, bool, operator, assumeTrue) {
      assumeTrue = assumeTrue !== (bool.kind === 112 /* TrueKeyword */) !== (operator !== 38 /* ExclamationEqualsEqualsToken */ && operator !== 36 /* ExclamationEqualsToken */);
      return narrowType(type, expr, assumeTrue);
    }
    function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
      switch (expr.operatorToken.kind) {
        case 64 /* EqualsToken */:
        case 76 /* BarBarEqualsToken */:
        case 77 /* AmpersandAmpersandEqualsToken */:
        case 78 /* QuestionQuestionEqualsToken */:
          return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
        case 35 /* EqualsEqualsToken */:
        case 36 /* ExclamationEqualsToken */:
        case 37 /* EqualsEqualsEqualsToken */:
        case 38 /* ExclamationEqualsEqualsToken */:
          const operator = expr.operatorToken.kind;
          const left = getReferenceCandidate(expr.left);
          const right = getReferenceCandidate(expr.right);
          if (left.kind === 221 /* TypeOfExpression */ && isStringLiteralLike(right)) {
            return narrowTypeByTypeof(type, left, operator, right, assumeTrue);
          }
          if (right.kind === 221 /* TypeOfExpression */ && isStringLiteralLike(left)) {
            return narrowTypeByTypeof(type, right, operator, left, assumeTrue);
          }
          if (isMatchingReference(reference, left)) {
            return narrowTypeByEquality(type, operator, right, assumeTrue);
          }
          if (isMatchingReference(reference, right)) {
            return narrowTypeByEquality(type, operator, left, assumeTrue);
          }
          if (strictNullChecks) {
            if (optionalChainContainsReference(left, reference)) {
              type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue);
            } else if (optionalChainContainsReference(right, reference)) {
              type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue);
            }
          }
          const leftAccess = getDiscriminantPropertyAccess(left, type);
          if (leftAccess) {
            return narrowTypeByDiscriminantProperty(type, leftAccess, operator, right, assumeTrue);
          }
          const rightAccess = getDiscriminantPropertyAccess(right, type);
          if (rightAccess) {
            return narrowTypeByDiscriminantProperty(type, rightAccess, operator, left, assumeTrue);
          }
          if (isMatchingConstructorReference(left)) {
            return narrowTypeByConstructor(type, operator, right, assumeTrue);
          }
          if (isMatchingConstructorReference(right)) {
            return narrowTypeByConstructor(type, operator, left, assumeTrue);
          }
          if (isBooleanLiteral(right) && !isAccessExpression(left)) {
            return narrowTypeByBooleanComparison(type, left, right, operator, assumeTrue);
          }
          if (isBooleanLiteral(left) && !isAccessExpression(right)) {
            return narrowTypeByBooleanComparison(type, right, left, operator, assumeTrue);
          }
          break;
        case 104 /* InstanceOfKeyword */:
          return narrowTypeByInstanceof(type, expr, assumeTrue);
        case 103 /* InKeyword */:
          if (isPrivateIdentifier(expr.left)) {
            return narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue);
          }
          const target = getReferenceCandidate(expr.right);
          if (containsMissingType(type) && isAccessExpression(reference) && isMatchingReference(reference.expression, target)) {
            const leftType = getTypeOfExpression(expr.left);
            if (isTypeUsableAsPropertyName(leftType) && getAccessedPropertyName(reference) === getPropertyNameFromType(leftType)) {
              return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */);
            }
          }
          if (isMatchingReference(reference, target)) {
            const leftType = getTypeOfExpression(expr.left);
            if (isTypeUsableAsPropertyName(leftType)) {
              return narrowTypeByInKeyword(type, leftType, assumeTrue);
            }
          }
          break;
        case 28 /* CommaToken */:
          return narrowType(type, expr.right, assumeTrue);
        // Ordinarily we won't see && and || expressions in control flow analysis because the Binder breaks those
        // expressions down to individual conditional control flows. However, we may encounter them when analyzing
        // aliased conditional expressions.
        case 56 /* AmpersandAmpersandToken */:
          return assumeTrue ? narrowType(
            narrowType(
              type,
              expr.left,
              /*assumeTrue*/
              true
            ),
            expr.right,
            /*assumeTrue*/
            true
          ) : getUnionType([narrowType(
            type,
            expr.left,
            /*assumeTrue*/
            false
          ), narrowType(
            type,
            expr.right,
            /*assumeTrue*/
            false
          )]);
        case 57 /* BarBarToken */:
          return assumeTrue ? getUnionType([narrowType(
            type,
            expr.left,
            /*assumeTrue*/
            true
          ), narrowType(
            type,
            expr.right,
            /*assumeTrue*/
            true
          )]) : narrowType(
            narrowType(
              type,
              expr.left,
              /*assumeTrue*/
              false
            ),
            expr.right,
            /*assumeTrue*/
            false
          );
      }
      return type;
    }
    function narrowTypeByPrivateIdentifierInInExpression(type, expr, assumeTrue) {
      const target = getReferenceCandidate(expr.right);
      if (!isMatchingReference(reference, target)) {
        return type;
      }
      Debug.assertNode(expr.left, isPrivateIdentifier);
      const symbol = getSymbolForPrivateIdentifierExpression(expr.left);
      if (symbol === void 0) {
        return type;
      }
      const classSymbol = symbol.parent;
      const targetType = hasStaticModifier(Debug.checkDefined(symbol.valueDeclaration, "should always have a declaration")) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol);
      return getNarrowedType(
        type,
        targetType,
        assumeTrue,
        /*checkDerived*/
        true
      );
    }
    function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
      const equalsOperator = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */;
      const nullableFlags = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
      const valueType = getTypeOfExpression(value);
      const removeNullable = equalsOperator !== assumeTrue && everyType(valueType, (t) => !!(t.flags & nullableFlags)) || equalsOperator === assumeTrue && everyType(valueType, (t) => !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)));
      return removeNullable ? getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
    }
    function narrowTypeByEquality(type, operator, value, assumeTrue) {
      if (type.flags & 1 /* Any */) {
        return type;
      }
      if (operator === 36 /* ExclamationEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) {
        assumeTrue = !assumeTrue;
      }
      const valueType = getTypeOfExpression(value);
      const doubleEquals = operator === 35 /* EqualsEqualsToken */ || operator === 36 /* ExclamationEqualsToken */;
      if (valueType.flags & 98304 /* Nullable */) {
        if (!strictNullChecks) {
          return type;
        }
        const facts = doubleEquals ? assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ : valueType.flags & 65536 /* Null */ ? assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ : assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
        return getAdjustedTypeWithFacts(type, facts);
      }
      if (assumeTrue) {
        if (!doubleEquals && (type.flags & 2 /* Unknown */ || someType(type, isEmptyAnonymousObjectType))) {
          if (valueType.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */) || isEmptyAnonymousObjectType(valueType)) {
            return valueType;
          }
          if (valueType.flags & 524288 /* Object */) {
            return nonPrimitiveType;
          }
        }
        const filteredType = filterType(type, (t) => areTypesComparable(t, valueType) || doubleEquals && isCoercibleUnderDoubleEquals(t, valueType));
        return replacePrimitivesWithLiterals(filteredType, valueType);
      }
      if (isUnitType(valueType)) {
        return filterType(type, (t) => !(isUnitLikeType(t) && areTypesComparable(t, valueType)));
      }
      return type;
    }
    function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
      if (operator === 36 /* ExclamationEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */) {
        assumeTrue = !assumeTrue;
      }
      const target = getReferenceCandidate(typeOfExpr.expression);
      if (!isMatchingReference(reference, target)) {
        if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
          type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
        }
        const propertyAccess = getDiscriminantPropertyAccess(target, type);
        if (propertyAccess) {
          return narrowTypeByDiscriminant(type, propertyAccess, (t) => narrowTypeByLiteralExpression(t, literal, assumeTrue));
        }
        return type;
      }
      return narrowTypeByLiteralExpression(type, literal, assumeTrue);
    }
    function narrowTypeByLiteralExpression(type, literal, assumeTrue) {
      return assumeTrue ? narrowTypeByTypeName(type, literal.text) : getAdjustedTypeWithFacts(type, typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */);
    }
    function narrowTypeBySwitchOptionalChainContainment(type, { switchStatement, clauseStart, clauseEnd }, clauseCheck) {
      const everyClauseChecks = clauseStart !== clauseEnd && every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
      return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
    }
    function narrowTypeBySwitchOnDiscriminant(type, { switchStatement, clauseStart, clauseEnd }) {
      const switchTypes = getSwitchClauseTypes(switchStatement);
      if (!switchTypes.length) {
        return type;
      }
      const clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
      const hasDefaultClause = clauseStart === clauseEnd || contains(clauseTypes, neverType);
      if (type.flags & 2 /* Unknown */ && !hasDefaultClause) {
        let groundClauseTypes;
        for (let i = 0; i < clauseTypes.length; i += 1) {
          const t = clauseTypes[i];
          if (t.flags & (402784252 /* Primitive */ | 67108864 /* NonPrimitive */)) {
            if (groundClauseTypes !== void 0) {
              groundClauseTypes.push(t);
            }
          } else if (t.flags & 524288 /* Object */) {
            if (groundClauseTypes === void 0) {
              groundClauseTypes = clauseTypes.slice(0, i);
            }
            groundClauseTypes.push(nonPrimitiveType);
          } else {
            return type;
          }
        }
        return getUnionType(groundClauseTypes === void 0 ? clauseTypes : groundClauseTypes);
      }
      const discriminantType = getUnionType(clauseTypes);
      const caseType = discriminantType.flags & 131072 /* Never */ ? neverType : replacePrimitivesWithLiterals(filterType(type, (t) => areTypesComparable(discriminantType, t)), discriminantType);
      if (!hasDefaultClause) {
        return caseType;
      }
      const defaultType = filterType(type, (t) => !(isUnitLikeType(t) && contains(switchTypes, t.flags & 32768 /* Undefined */ ? undefinedType : getRegularTypeOfLiteralType(extractUnitType(t)))));
      return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
    }
    function narrowTypeByTypeName(type, typeName) {
      switch (typeName) {
        case "string":
          return narrowTypeByTypeFacts(type, stringType, 1 /* TypeofEQString */);
        case "number":
          return narrowTypeByTypeFacts(type, numberType, 2 /* TypeofEQNumber */);
        case "bigint":
          return narrowTypeByTypeFacts(type, bigintType, 4 /* TypeofEQBigInt */);
        case "boolean":
          return narrowTypeByTypeFacts(type, booleanType, 8 /* TypeofEQBoolean */);
        case "symbol":
          return narrowTypeByTypeFacts(type, esSymbolType, 16 /* TypeofEQSymbol */);
        case "object":
          return type.flags & 1 /* Any */ ? type : getUnionType([narrowTypeByTypeFacts(type, nonPrimitiveType, 32 /* TypeofEQObject */), narrowTypeByTypeFacts(type, nullType, 131072 /* EQNull */)]);
        case "function":
          return type.flags & 1 /* Any */ ? type : narrowTypeByTypeFacts(type, globalFunctionType, 64 /* TypeofEQFunction */);
        case "undefined":
          return narrowTypeByTypeFacts(type, undefinedType, 65536 /* EQUndefined */);
      }
      return narrowTypeByTypeFacts(type, nonPrimitiveType, 128 /* TypeofEQHostObject */);
    }
    function narrowTypeByTypeFacts(type, impliedType, facts) {
      return mapType(type, (t) => (
        // We first check if a constituent is a subtype of the implied type. If so, we either keep or eliminate
        // the constituent based on its type facts. We use the strict subtype relation because it treats `object`
        // as a subtype of `{}`, and we need the type facts check because function types are subtypes of `object`,
        // but are classified as "function" according to `typeof`.
        isTypeRelatedTo(t, impliedType, strictSubtypeRelation) ? hasTypeFacts(t, facts) ? t : neverType : (
          // We next check if the consituent is a supertype of the implied type. If so, we substitute the implied
          // type. This handles top types like `unknown` and `{}`, and supertypes like `{ toString(): string }`.
          isTypeSubtypeOf(impliedType, t) ? impliedType : (
            // Neither the constituent nor the implied type is a subtype of the other, however their domains may still
            // overlap. For example, an unconstrained type parameter and type `string`. If the type facts indicate
            // possible overlap, we form an intersection. Otherwise, we eliminate the constituent.
            hasTypeFacts(t, facts) ? getIntersectionType([t, impliedType]) : neverType
          )
        )
      ));
    }
    function narrowTypeBySwitchOnTypeOf(type, { switchStatement, clauseStart, clauseEnd }) {
      const witnesses = getSwitchClauseTypeOfWitnesses(switchStatement);
      if (!witnesses) {
        return type;
      }
      const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === 297 /* DefaultClause */);
      const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd;
      if (hasDefaultClause) {
        const notEqualFacts = getNotEqualFactsFromTypeofSwitch(clauseStart, clauseEnd, witnesses);
        return filterType(type, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts);
      }
      const clauseWitnesses = witnesses.slice(clauseStart, clauseEnd);
      return getUnionType(map(clauseWitnesses, (text) => text ? narrowTypeByTypeName(type, text) : neverType));
    }
    function narrowTypeBySwitchOnTrue(type, { switchStatement, clauseStart, clauseEnd }) {
      const defaultIndex = findIndex(switchStatement.caseBlock.clauses, (clause) => clause.kind === 297 /* DefaultClause */);
      const hasDefaultClause = clauseStart === clauseEnd || defaultIndex >= clauseStart && defaultIndex < clauseEnd;
      for (let i = 0; i < clauseStart; i++) {
        const clause = switchStatement.caseBlock.clauses[i];
        if (clause.kind === 296 /* CaseClause */) {
          type = narrowType(
            type,
            clause.expression,
            /*assumeTrue*/
            false
          );
        }
      }
      if (hasDefaultClause) {
        for (let i = clauseEnd; i < switchStatement.caseBlock.clauses.length; i++) {
          const clause = switchStatement.caseBlock.clauses[i];
          if (clause.kind === 296 /* CaseClause */) {
            type = narrowType(
              type,
              clause.expression,
              /*assumeTrue*/
              false
            );
          }
        }
        return type;
      }
      const clauses = switchStatement.caseBlock.clauses.slice(clauseStart, clauseEnd);
      return getUnionType(map(clauses, (clause) => clause.kind === 296 /* CaseClause */ ? narrowType(
        type,
        clause.expression,
        /*assumeTrue*/
        true
      ) : neverType));
    }
    function isMatchingConstructorReference(expr) {
      return (isPropertyAccessExpression(expr) && idText(expr.name) === "constructor" || isElementAccessExpression(expr) && isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") && isMatchingReference(reference, expr.expression);
    }
    function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
      if (assumeTrue ? operator !== 35 /* EqualsEqualsToken */ && operator !== 37 /* EqualsEqualsEqualsToken */ : operator !== 36 /* ExclamationEqualsToken */ && operator !== 38 /* ExclamationEqualsEqualsToken */) {
        return type;
      }
      const identifierType = getTypeOfExpression(identifier);
      if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
        return type;
      }
      const prototypeProperty = getPropertyOfType(identifierType, "prototype");
      if (!prototypeProperty) {
        return type;
      }
      const prototypeType = getTypeOfSymbol(prototypeProperty);
      const candidate = !isTypeAny(prototypeType) ? prototypeType : void 0;
      if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
        return type;
      }
      if (isTypeAny(type)) {
        return candidate;
      }
      return filterType(type, (t) => isConstructedBy(t, candidate));
      function isConstructedBy(source, target) {
        if (source.flags & 524288 /* Object */ && getObjectFlags(source) & 1 /* Class */ || target.flags & 524288 /* Object */ && getObjectFlags(target) & 1 /* Class */) {
          return source.symbol === target.symbol;
        }
        return isTypeSubtypeOf(source, target);
      }
    }
    function narrowTypeByInstanceof(type, expr, assumeTrue) {
      const left = getReferenceCandidate(expr.left);
      if (!isMatchingReference(reference, left)) {
        if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
          return getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
        }
        return type;
      }
      const right = expr.right;
      const rightType = getTypeOfExpression(right);
      if (!isTypeDerivedFrom(rightType, globalObjectType)) {
        return type;
      }
      const signature = getEffectsSignature(expr);
      const predicate = signature && getTypePredicateOfSignature(signature);
      if (predicate && predicate.kind === 1 /* Identifier */ && predicate.parameterIndex === 0) {
        return getNarrowedType(
          type,
          predicate.type,
          assumeTrue,
          /*checkDerived*/
          true
        );
      }
      if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
        return type;
      }
      const instanceType = mapType(rightType, getInstanceType);
      if (isTypeAny(type) && (instanceType === globalObjectType || instanceType === globalFunctionType) || !assumeTrue && !(instanceType.flags & 524288 /* Object */ && !isEmptyAnonymousObjectType(instanceType))) {
        return type;
      }
      return getNarrowedType(
        type,
        instanceType,
        assumeTrue,
        /*checkDerived*/
        true
      );
    }
    function getInstanceType(constructorType) {
      const prototypePropertyType = getTypeOfPropertyOfType(constructorType, "prototype");
      if (prototypePropertyType && !isTypeAny(prototypePropertyType)) {
        return prototypePropertyType;
      }
      const constructSignatures = getSignaturesOfType(constructorType, 1 /* Construct */);
      if (constructSignatures.length) {
        return getUnionType(map(constructSignatures, (signature) => getReturnTypeOfSignature(getErasedSignature(signature))));
      }
      return emptyObjectType;
    }
    function getNarrowedType(type, candidate, assumeTrue, checkDerived) {
      const key2 = type.flags & 1048576 /* Union */ ? `N${getTypeId(type)},${getTypeId(candidate)},${(assumeTrue ? 1 : 0) | (checkDerived ? 2 : 0)}` : void 0;
      return getCachedType(key2) ?? setCachedType(key2, getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived));
    }
    function getNarrowedTypeWorker(type, candidate, assumeTrue, checkDerived) {
      if (!assumeTrue) {
        if (type === candidate) {
          return neverType;
        }
        if (checkDerived) {
          return filterType(type, (t) => !isTypeDerivedFrom(t, candidate));
        }
        const trueType2 = getNarrowedType(
          type,
          candidate,
          /*assumeTrue*/
          true,
          /*checkDerived*/
          false
        );
        return filterType(type, (t) => !isTypeSubsetOf(t, trueType2));
      }
      if (type.flags & 3 /* AnyOrUnknown */) {
        return candidate;
      }
      if (type === candidate) {
        return candidate;
      }
      const isRelated = checkDerived ? isTypeDerivedFrom : isTypeSubtypeOf;
      const keyPropertyName = type.flags & 1048576 /* Union */ ? getKeyPropertyName(type) : void 0;
      const narrowedType = mapType(candidate, (c) => {
        const discriminant = keyPropertyName && getTypeOfPropertyOfType(c, keyPropertyName);
        const matching = discriminant && getConstituentTypeForKeyType(type, discriminant);
        const directlyRelated = mapType(
          matching || type,
          checkDerived ? (t) => isTypeDerivedFrom(t, c) ? t : isTypeDerivedFrom(c, t) ? c : neverType : (t) => isTypeStrictSubtypeOf(t, c) ? t : isTypeStrictSubtypeOf(c, t) ? c : isTypeSubtypeOf(t, c) ? t : isTypeSubtypeOf(c, t) ? c : neverType
        );
        return directlyRelated.flags & 131072 /* Never */ ? mapType(type, (t) => maybeTypeOfKind(t, 465829888 /* Instantiable */) && isRelated(c, getBaseConstraintOfType(t) || unknownType) ? getIntersectionType([t, c]) : neverType) : directlyRelated;
      });
      return !(narrowedType.flags & 131072 /* Never */) ? narrowedType : isTypeSubtypeOf(candidate, type) ? candidate : isTypeAssignableTo(type, candidate) ? type : isTypeAssignableTo(candidate, type) ? candidate : getIntersectionType([type, candidate]);
    }
    function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
      if (hasMatchingArgument(callExpression, reference)) {
        const signature = assumeTrue || !isCallChain(callExpression) ? getEffectsSignature(callExpression) : void 0;
        const predicate = signature && getTypePredicateOfSignature(signature);
        if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
          return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
        }
      }
      if (containsMissingType(type) && isAccessExpression(reference) && isPropertyAccessExpression(callExpression.expression)) {
        const callAccess = callExpression.expression;
        if (isMatchingReference(reference.expression, getReferenceCandidate(callAccess.expression)) && isIdentifier(callAccess.name) && callAccess.name.escapedText === "hasOwnProperty" && callExpression.arguments.length === 1) {
          const argument = callExpression.arguments[0];
          if (isStringLiteralLike(argument) && getAccessedPropertyName(reference) === escapeLeadingUnderscores(argument.text)) {
            return getTypeWithFacts(type, assumeTrue ? 524288 /* NEUndefined */ : 65536 /* EQUndefined */);
          }
        }
      }
      return type;
    }
    function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
      if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
        const predicateArgument = getTypePredicateArgument(predicate, callExpression);
        if (predicateArgument) {
          if (isMatchingReference(reference, predicateArgument)) {
            return getNarrowedType(
              type,
              predicate.type,
              assumeTrue,
              /*checkDerived*/
              false
            );
          }
          if (strictNullChecks && optionalChainContainsReference(predicateArgument, reference) && (assumeTrue && !hasTypeFacts(predicate.type, 65536 /* EQUndefined */) || !assumeTrue && everyType(predicate.type, isNullableType))) {
            type = getAdjustedTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
          }
          const access = getDiscriminantPropertyAccess(predicateArgument, type);
          if (access) {
            return narrowTypeByDiscriminant(type, access, (t) => getNarrowedType(
              t,
              predicate.type,
              assumeTrue,
              /*checkDerived*/
              false
            ));
          }
        }
      }
      return type;
    }
    function narrowType(type, expr, assumeTrue) {
      if (isExpressionOfOptionalChainRoot(expr) || isBinaryExpression(expr.parent) && (expr.parent.operatorToken.kind === 61 /* QuestionQuestionToken */ || expr.parent.operatorToken.kind === 78 /* QuestionQuestionEqualsToken */) && expr.parent.left === expr) {
        return narrowTypeByOptionality(type, expr, assumeTrue);
      }
      switch (expr.kind) {
        case 80 /* Identifier */:
          if (!isMatchingReference(reference, expr) && inlineLevel < 5) {
            const symbol = getResolvedSymbol(expr);
            if (isConstantVariable(symbol)) {
              const declaration = symbol.valueDeclaration;
              if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && isConstantReference(reference)) {
                inlineLevel++;
                const result = narrowType(type, declaration.initializer, assumeTrue);
                inlineLevel--;
                return result;
              }
            }
          }
        // falls through
        case 110 /* ThisKeyword */:
        case 108 /* SuperKeyword */:
        case 211 /* PropertyAccessExpression */:
        case 212 /* ElementAccessExpression */:
          return narrowTypeByTruthiness(type, expr, assumeTrue);
        case 213 /* CallExpression */:
          return narrowTypeByCallExpression(type, expr, assumeTrue);
        case 217 /* ParenthesizedExpression */:
        case 235 /* NonNullExpression */:
          return narrowType(type, expr.expression, assumeTrue);
        case 226 /* BinaryExpression */:
          return narrowTypeByBinaryExpression(type, expr, assumeTrue);
        case 224 /* PrefixUnaryExpression */:
          if (expr.operator === 54 /* ExclamationToken */) {
            return narrowType(type, expr.operand, !assumeTrue);
          }
          break;
      }
      return type;
    }
    function narrowTypeByOptionality(type, expr, assumePresent) {
      if (isMatchingReference(reference, expr)) {
        return getAdjustedTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
      }
      const access = getDiscriminantPropertyAccess(expr, type);
      if (access) {
        return narrowTypeByDiscriminant(type, access, (t) => getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */));
      }
      return type;
    }
  }
  function getTypeOfSymbolAtLocation(symbol, location) {
    symbol = getExportSymbolOfValueSymbolIfExported(symbol);
    if (location.kind === 80 /* Identifier */ || location.kind === 81 /* PrivateIdentifier */) {
      if (isRightSideOfQualifiedNameOrPropertyAccess(location)) {
        location = location.parent;
      }
      if (isExpressionNode(location) && (!isAssignmentTarget(location) || isWriteAccess(location))) {
        const type = removeOptionalTypeMarker(
          isWriteAccess(location) && location.kind === 211 /* PropertyAccessExpression */ ? checkPropertyAccessExpression(
            location,
            /*checkMode*/
            void 0,
            /*writeOnly*/
            true
          ) : getTypeOfExpression(location)
        );
        if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
          return type;
        }
      }
    }
    if (isDeclarationName(location) && isSetAccessor(location.parent) && getAnnotatedAccessorTypeNode(location.parent)) {
      return getWriteTypeOfAccessors(location.parent.symbol);
    }
    return isRightSideOfAccessExpression(location) && isWriteAccess(location.parent) ? getWriteTypeOfSymbol(symbol) : getNonMissingTypeOfSymbol(symbol);
  }
  function getControlFlowContainer(node) {
    return findAncestor(node.parent, (node2) => isFunctionLike(node2) && !getImmediatelyInvokedFunctionExpression(node2) || node2.kind === 268 /* ModuleBlock */ || node2.kind === 307 /* SourceFile */ || node2.kind === 172 /* PropertyDeclaration */);
  }
  function isSymbolAssignedDefinitely(symbol) {
    if (symbol.lastAssignmentPos !== void 0) {
      return symbol.lastAssignmentPos < 0;
    }
    return isSymbolAssigned(symbol) && symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0;
  }
  function isSymbolAssigned(symbol) {
    return !isPastLastAssignment(
      symbol,
      /*location*/
      void 0
    );
  }
  function isPastLastAssignment(symbol, location) {
    const parent = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile);
    if (!parent) {
      return false;
    }
    const links = getNodeLinks(parent);
    if (!(links.flags & 131072 /* AssignmentsMarked */)) {
      links.flags |= 131072 /* AssignmentsMarked */;
      if (!hasParentWithAssignmentsMarked(parent)) {
        markNodeAssignments(parent);
      }
    }
    return !symbol.lastAssignmentPos || location && Math.abs(symbol.lastAssignmentPos) < location.pos;
  }
  function isSomeSymbolAssigned(rootDeclaration) {
    Debug.assert(isVariableDeclaration(rootDeclaration) || isParameter(rootDeclaration));
    return isSomeSymbolAssignedWorker(rootDeclaration.name);
  }
  function isSomeSymbolAssignedWorker(node) {
    if (node.kind === 80 /* Identifier */) {
      return isSymbolAssigned(getSymbolOfDeclaration(node.parent));
    }
    return some(node.elements, (e) => e.kind !== 232 /* OmittedExpression */ && isSomeSymbolAssignedWorker(e.name));
  }
  function hasParentWithAssignmentsMarked(node) {
    return !!findAncestor(node.parent, (node2) => isFunctionOrSourceFile(node2) && !!(getNodeLinks(node2).flags & 131072 /* AssignmentsMarked */));
  }
  function isFunctionOrSourceFile(node) {
    return isFunctionLikeDeclaration(node) || isSourceFile(node);
  }
  function markNodeAssignments(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        const assigmentTarget = getAssignmentTargetKind(node);
        if (assigmentTarget !== 0 /* None */) {
          const symbol = getResolvedSymbol(node);
          const hasDefiniteAssignment = assigmentTarget === 1 /* Definite */ || symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0;
          if (isParameterOrMutableLocalVariable(symbol)) {
            if (symbol.lastAssignmentPos === void 0 || Math.abs(symbol.lastAssignmentPos) !== Number.MAX_VALUE) {
              const referencingFunction = findAncestor(node, isFunctionOrSourceFile);
              const declaringFunction = findAncestor(symbol.valueDeclaration, isFunctionOrSourceFile);
              symbol.lastAssignmentPos = referencingFunction === declaringFunction ? extendAssignmentPosition(node, symbol.valueDeclaration) : Number.MAX_VALUE;
            }
            if (hasDefiniteAssignment && symbol.lastAssignmentPos > 0) {
              symbol.lastAssignmentPos *= -1;
            }
          }
        }
        return;
      case 281 /* ExportSpecifier */:
        const exportDeclaration = node.parent.parent;
        const name = node.propertyName || node.name;
        if (!node.isTypeOnly && !exportDeclaration.isTypeOnly && !exportDeclaration.moduleSpecifier && name.kind !== 11 /* StringLiteral */) {
          const symbol = resolveEntityName(
            name,
            111551 /* Value */,
            /*ignoreErrors*/
            true,
            /*dontResolveAlias*/
            true
          );
          if (symbol && isParameterOrMutableLocalVariable(symbol)) {
            const sign = symbol.lastAssignmentPos !== void 0 && symbol.lastAssignmentPos < 0 ? -1 : 1;
            symbol.lastAssignmentPos = sign * Number.MAX_VALUE;
          }
        }
        return;
      case 264 /* InterfaceDeclaration */:
      case 265 /* TypeAliasDeclaration */:
      case 266 /* EnumDeclaration */:
        return;
    }
    if (isTypeNode(node)) {
      return;
    }
    forEachChild(node, markNodeAssignments);
  }
  function extendAssignmentPosition(node, declaration) {
    let pos = node.pos;
    while (node && node.pos > declaration.pos) {
      switch (node.kind) {
        case 243 /* VariableStatement */:
        case 244 /* ExpressionStatement */:
        case 245 /* IfStatement */:
        case 246 /* DoStatement */:
        case 247 /* WhileStatement */:
        case 248 /* ForStatement */:
        case 249 /* ForInStatement */:
        case 250 /* ForOfStatement */:
        case 254 /* WithStatement */:
        case 255 /* SwitchStatement */:
        case 258 /* TryStatement */:
        case 263 /* ClassDeclaration */:
          pos = node.end;
      }
      node = node.parent;
    }
    return pos;
  }
  function isConstantVariable(symbol) {
    return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */) !== 0;
  }
  function isParameterOrMutableLocalVariable(symbol) {
    const declaration = symbol.valueDeclaration && getRootDeclaration(symbol.valueDeclaration);
    return !!declaration && (isParameter(declaration) || isVariableDeclaration(declaration) && (isCatchClause(declaration.parent) || isMutableLocalVariableDeclaration(declaration)));
  }
  function isMutableLocalVariableDeclaration(declaration) {
    return !!(declaration.parent.flags & 1 /* Let */) && !(getCombinedModifierFlags(declaration) & 32 /* Export */ || declaration.parent.parent.kind === 243 /* VariableStatement */ && isGlobalSourceFile(declaration.parent.parent.parent));
  }
  function parameterInitializerContainsUndefined(declaration) {
    const links = getNodeLinks(declaration);
    if (links.parameterInitializerContainsUndefined === void 0) {
      if (!pushTypeResolution(declaration, 8 /* ParameterInitializerContainsUndefined */)) {
        reportCircularityError(declaration.symbol);
        return true;
      }
      const containsUndefined = !!hasTypeFacts(checkDeclarationInitializer(declaration, 0 /* Normal */), 16777216 /* IsUndefined */);
      if (!popTypeResolution()) {
        reportCircularityError(declaration.symbol);
        return true;
      }
      links.parameterInitializerContainsUndefined ?? (links.parameterInitializerContainsUndefined = containsUndefined);
    }
    return links.parameterInitializerContainsUndefined;
  }
  function removeOptionalityFromDeclaredType(declaredType, declaration) {
    const removeUndefined = strictNullChecks && declaration.kind === 169 /* Parameter */ && declaration.initializer && hasTypeFacts(declaredType, 16777216 /* IsUndefined */) && !parameterInitializerContainsUndefined(declaration);
    return removeUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
  }
  function isConstraintPosition(type, node) {
    const parent = node.parent;
    return parent.kind === 211 /* PropertyAccessExpression */ || parent.kind === 166 /* QualifiedName */ || parent.kind === 213 /* CallExpression */ && parent.expression === node || parent.kind === 214 /* NewExpression */ && parent.expression === node || parent.kind === 212 /* ElementAccessExpression */ && parent.expression === node && !(someType(type, isGenericTypeWithoutNullableConstraint) && isGenericIndexType(getTypeOfExpression(parent.argumentExpression)));
  }
  function isGenericTypeWithUnionConstraint(type) {
    return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithUnionConstraint) : !!(type.flags & 465829888 /* Instantiable */ && getBaseConstraintOrType(type).flags & (98304 /* Nullable */ | 1048576 /* Union */));
  }
  function isGenericTypeWithoutNullableConstraint(type) {
    return type.flags & 2097152 /* Intersection */ ? some(type.types, isGenericTypeWithoutNullableConstraint) : !!(type.flags & 465829888 /* Instantiable */ && !maybeTypeOfKind(getBaseConstraintOrType(type), 98304 /* Nullable */));
  }
  function hasContextualTypeWithNoGenericTypes(node, checkMode) {
    const contextualType = (isIdentifier(node) || isPropertyAccessExpression(node) || isElementAccessExpression(node)) && !((isJsxOpeningElement(node.parent) || isJsxSelfClosingElement(node.parent)) && node.parent.tagName === node) && (checkMode && checkMode & 32 /* RestBindingElement */ ? getContextualType(node, 8 /* SkipBindingPatterns */) : getContextualType(
      node,
      /*contextFlags*/
      void 0
    ));
    return contextualType && !isGenericType(contextualType);
  }
  function getNarrowableTypeForReference(type, reference, checkMode) {
    if (isNoInferType(type)) {
      type = type.baseType;
    }
    const substituteConstraints = !(checkMode && checkMode & 2 /* Inferential */) && someType(type, isGenericTypeWithUnionConstraint) && (isConstraintPosition(type, reference) || hasContextualTypeWithNoGenericTypes(reference, checkMode));
    return substituteConstraints ? mapType(type, getBaseConstraintOrType) : type;
  }
  function isExportOrExportExpression(location) {
    return !!findAncestor(location, (n) => {
      const parent = n.parent;
      if (parent === void 0) {
        return "quit";
      }
      if (isExportAssignment(parent)) {
        return parent.expression === n && isEntityNameExpression(n);
      }
      if (isExportSpecifier(parent)) {
        return parent.name === n || parent.propertyName === n;
      }
      return false;
    });
  }
  function markLinkedReferences(location, hint, propSymbol, parentType) {
    if (!canCollectSymbolAliasAccessabilityData) {
      return;
    }
    if (location.flags & 33554432 /* Ambient */ && !isPropertySignature(location) && !isPropertyDeclaration(location)) {
      return;
    }
    switch (hint) {
      case 1 /* Identifier */:
        return markIdentifierAliasReferenced(location);
      case 2 /* Property */:
        return markPropertyAliasReferenced(location, propSymbol, parentType);
      case 3 /* ExportAssignment */:
        return markExportAssignmentAliasReferenced(location);
      case 4 /* Jsx */:
        return markJsxAliasReferenced(location);
      case 5 /* AsyncFunction */:
        return markAsyncFunctionAliasReferenced(location);
      case 6 /* ExportImportEquals */:
        return markImportEqualsAliasReferenced(location);
      case 7 /* ExportSpecifier */:
        return markExportSpecifierAliasReferenced(location);
      case 8 /* Decorator */:
        return markDecoratorAliasReferenced(location);
      case 0 /* Unspecified */: {
        if (isIdentifier(location) && (isExpressionNode(location) || isShorthandPropertyAssignment(location.parent) || isImportEqualsDeclaration(location.parent) && location.parent.moduleReference === location) && shouldMarkIdentifierAliasReferenced(location)) {
          if (isPropertyAccessOrQualifiedName(location.parent)) {
            const left = isPropertyAccessExpression(location.parent) ? location.parent.expression : location.parent.left;
            if (left !== location) return;
          }
          markIdentifierAliasReferenced(location);
          return;
        }
        if (isPropertyAccessOrQualifiedName(location)) {
          let topProp = location;
          while (isPropertyAccessOrQualifiedName(topProp)) {
            if (isPartOfTypeNode(topProp)) return;
            topProp = topProp.parent;
          }
          return markPropertyAliasReferenced(location);
        }
        if (isExportAssignment(location)) {
          return markExportAssignmentAliasReferenced(location);
        }
        if (isJsxOpeningLikeElement(location) || isJsxOpeningFragment(location)) {
          return markJsxAliasReferenced(location);
        }
        if (isImportEqualsDeclaration(location)) {
          if (isInternalModuleImportEqualsDeclaration(location) || checkExternalImportOrExportDeclaration(location)) {
            return markImportEqualsAliasReferenced(location);
          }
          return;
        }
        if (isExportSpecifier(location)) {
          return markExportSpecifierAliasReferenced(location);
        }
        if (isFunctionLikeDeclaration(location) || isMethodSignature(location)) {
          markAsyncFunctionAliasReferenced(location);
        }
        if (!compilerOptions.emitDecoratorMetadata) {
          return;
        }
        if (!canHaveDecorators(location) || !hasDecorators(location) || !location.modifiers || !nodeCanBeDecorated(legacyDecorators, location, location.parent, location.parent.parent)) {
          return;
        }
        return markDecoratorAliasReferenced(location);
      }
      default:
        Debug.assertNever(hint, `Unhandled reference hint: ${hint}`);
    }
  }
  function markIdentifierAliasReferenced(location) {
    const symbol = getResolvedSymbol(location);
    if (symbol && symbol !== argumentsSymbol && symbol !== unknownSymbol && !isThisInTypeQuery(location)) {
      markAliasReferenced(symbol, location);
    }
  }
  function markPropertyAliasReferenced(location, propSymbol, parentType) {
    const left = isPropertyAccessExpression(location) ? location.expression : location.left;
    if (isThisIdentifier(left) || !isIdentifier(left)) {
      return;
    }
    const parentSymbol = getResolvedSymbol(left);
    if (!parentSymbol || parentSymbol === unknownSymbol) {
      return;
    }
    if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location)) {
      markAliasReferenced(parentSymbol, location);
      return;
    }
    const leftType = parentType || checkExpressionCached(left);
    if (isTypeAny(leftType) || leftType === silentNeverType) {
      markAliasReferenced(parentSymbol, location);
      return;
    }
    let prop = propSymbol;
    if (!prop && !parentType) {
      const right = isPropertyAccessExpression(location) ? location.name : location.right;
      const lexicallyScopedSymbol = isPrivateIdentifier(right) && lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
      const assignmentKind = getAssignmentTargetKind(location);
      const apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(location) ? getWidenedType(leftType) : leftType);
      prop = isPrivateIdentifier(right) ? lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(apparentType, lexicallyScopedSymbol) || void 0 : getPropertyOfType(apparentType, right.escapedText);
    }
    if (!(prop && (isConstEnumOrConstEnumOnlyModule(prop) || prop.flags & 8 /* EnumMember */ && location.parent.kind === 306 /* EnumMember */))) {
      markAliasReferenced(parentSymbol, location);
    }
    return;
  }
  function markExportAssignmentAliasReferenced(location) {
    if (isIdentifier(location.expression)) {
      const id = location.expression;
      const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(
        id,
        -1 /* All */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        location
      ));
      if (sym) {
        markAliasReferenced(sym, id);
      }
    }
  }
  function markJsxAliasReferenced(node) {
    if (!getJsxNamespaceContainerForImplicitImport(node)) {
      const jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? Diagnostics.This_JSX_tag_requires_0_to_be_in_scope_but_it_could_not_be_found : void 0;
      const jsxFactoryNamespace = getJsxNamespace(node);
      const jsxFactoryLocation = isJsxOpeningLikeElement(node) ? node.tagName : node;
      const shouldFactoryRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */;
      let jsxFactorySym;
      if (!(isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
        jsxFactorySym = resolveName(
          jsxFactoryLocation,
          jsxFactoryNamespace,
          shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */,
          jsxFactoryRefErr,
          /*isUse*/
          true
        );
      }
      if (jsxFactorySym) {
        jsxFactorySym.isReferenced = -1 /* All */;
        if (canCollectSymbolAliasAccessabilityData && jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
          markAliasSymbolAsReferenced(jsxFactorySym);
        }
      }
      if (isJsxOpeningFragment(node)) {
        const file = getSourceFileOfNode(node);
        const localJsxNamespace = getLocalJsxNamespace(file);
        if (localJsxNamespace) {
          resolveName(
            jsxFactoryLocation,
            localJsxNamespace,
            shouldFactoryRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */,
            jsxFactoryRefErr,
            /*isUse*/
            true
          );
        }
      }
    }
    return;
  }
  function markAsyncFunctionAliasReferenced(location) {
    if (languageVersion < 2 /* ES2015 */) {
      if (getFunctionFlags(location) & 2 /* Async */) {
        const returnTypeNode = getEffectiveReturnTypeNode(location);
        markTypeNodeAsReferenced(returnTypeNode);
      }
    }
  }
  function markImportEqualsAliasReferenced(location) {
    if (hasSyntacticModifier(location, 32 /* Export */)) {
      markExportAsReferenced(location);
    }
  }
  function markExportSpecifierAliasReferenced(location) {
    if (!location.parent.parent.moduleSpecifier && !location.isTypeOnly && !location.parent.parent.isTypeOnly) {
      const exportedName = location.propertyName || location.name;
      if (exportedName.kind === 11 /* StringLiteral */) {
        return;
      }
      const symbol = resolveName(
        exportedName,
        exportedName.escapedText,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
      } else {
        const target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
        if (!target || getSymbolFlags(target) & 111551 /* Value */) {
          markExportAsReferenced(location);
          markIdentifierAliasReferenced(exportedName);
        }
      }
      return;
    }
  }
  function markDecoratorAliasReferenced(node) {
    if (compilerOptions.emitDecoratorMetadata) {
      const firstDecorator = find(node.modifiers, isDecorator);
      if (!firstDecorator) {
        return;
      }
      checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
      switch (node.kind) {
        case 263 /* ClassDeclaration */:
          const constructor = getFirstConstructorWithBody(node);
          if (constructor) {
            for (const parameter of constructor.parameters) {
              markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
            }
          }
          break;
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          const otherKind = node.kind === 177 /* GetAccessor */ ? 178 /* SetAccessor */ : 177 /* GetAccessor */;
          const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(node), otherKind);
          markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
          break;
        case 174 /* MethodDeclaration */:
          for (const parameter of node.parameters) {
            markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
          }
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(node));
          break;
        case 172 /* PropertyDeclaration */:
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveTypeAnnotationNode(node));
          break;
        case 169 /* Parameter */:
          markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
          const containingSignature = node.parent;
          for (const parameter of containingSignature.parameters) {
            markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
          }
          markDecoratorMedataDataTypeNodeAsReferenced(getEffectiveReturnTypeNode(containingSignature));
          break;
      }
    }
  }
  function markAliasReferenced(symbol, location) {
    if (!canCollectSymbolAliasAccessabilityData) {
      return;
    }
    if (isNonLocalAlias(
      symbol,
      /*excludes*/
      111551 /* Value */
    ) && !isInTypeQuery(location)) {
      const target = resolveAlias(symbol);
      if (getSymbolFlags(
        symbol,
        /*excludeTypeOnlyMeanings*/
        true
      ) & (111551 /* Value */ | 1048576 /* ExportValue */)) {
        if (getIsolatedModules(compilerOptions) || shouldPreserveConstEnums(compilerOptions) && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(getExportSymbolOfValueSymbolIfExported(target))) {
          markAliasSymbolAsReferenced(symbol);
        }
      }
    }
  }
  function markAliasSymbolAsReferenced(symbol) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    const links = getSymbolLinks(symbol);
    if (!links.referenced) {
      links.referenced = true;
      const node = getDeclarationOfAliasSymbol(symbol);
      if (!node) return Debug.fail();
      if (isInternalModuleImportEqualsDeclaration(node)) {
        if (getSymbolFlags(resolveSymbol(symbol)) & 111551 /* Value */) {
          const left = getFirstIdentifier(node.moduleReference);
          markIdentifierAliasReferenced(left);
        }
      }
    }
  }
  function markExportAsReferenced(node) {
    const symbol = getSymbolOfDeclaration(node);
    const target = resolveAlias(symbol);
    if (target) {
      const markAlias = target === unknownSymbol || getSymbolFlags(
        symbol,
        /*excludeTypeOnlyMeanings*/
        true
      ) & 111551 /* Value */ && !isConstEnumOrConstEnumOnlyModule(target);
      if (markAlias) {
        markAliasSymbolAsReferenced(symbol);
      }
    }
  }
  function markEntityNameOrEntityExpressionAsReference(typeName, forDecoratorMetadata) {
    if (!typeName) return;
    const rootName = getFirstIdentifier(typeName);
    const meaning = (typeName.kind === 80 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
    const rootSymbol = resolveName(
      rootName,
      rootName.escapedText,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (rootSymbol && rootSymbol.flags & 2097152 /* Alias */) {
      if (canCollectSymbolAliasAccessabilityData && symbolIsValue(rootSymbol) && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol)) && !getTypeOnlyAliasDeclaration(rootSymbol)) {
        markAliasSymbolAsReferenced(rootSymbol);
      } else if (forDecoratorMetadata && getIsolatedModules(compilerOptions) && getEmitModuleKind(compilerOptions) >= 5 /* ES2015 */ && !symbolIsValue(rootSymbol) && !some(rootSymbol.declarations, isTypeOnlyImportOrExportDeclaration)) {
        const diag2 = error(typeName, Diagnostics.A_type_referenced_in_a_decorated_signature_must_be_imported_with_import_type_or_a_namespace_import_when_isolatedModules_and_emitDecoratorMetadata_are_enabled);
        const aliasDeclaration = find(rootSymbol.declarations || emptyArray, isAliasSymbolDeclaration);
        if (aliasDeclaration) {
          addRelatedInfo(diag2, createDiagnosticForNode(aliasDeclaration, Diagnostics._0_was_imported_here, idText(rootName)));
        }
      }
    }
  }
  function markTypeNodeAsReferenced(node) {
    markEntityNameOrEntityExpressionAsReference(
      node && getEntityNameFromTypeNode(node),
      /*forDecoratorMetadata*/
      false
    );
  }
  function markDecoratorMedataDataTypeNodeAsReferenced(node) {
    const entityName = getEntityNameForDecoratorMetadata(node);
    if (entityName && isEntityName(entityName)) {
      markEntityNameOrEntityExpressionAsReference(
        entityName,
        /*forDecoratorMetadata*/
        true
      );
    }
  }
  function getNarrowedTypeOfSymbol(symbol, location) {
    var _a;
    const type = getTypeOfSymbol(symbol);
    const declaration = symbol.valueDeclaration;
    if (declaration) {
      if (isBindingElement(declaration) && !declaration.initializer && !declaration.dotDotDotToken && declaration.parent.elements.length >= 2) {
        const parent = declaration.parent.parent;
        const rootDeclaration = getRootDeclaration(parent);
        if (rootDeclaration.kind === 260 /* VariableDeclaration */ && getCombinedNodeFlagsCached(rootDeclaration) & 6 /* Constant */ || rootDeclaration.kind === 169 /* Parameter */) {
          const links = getNodeLinks(parent);
          if (!(links.flags & 4194304 /* InCheckIdentifier */)) {
            links.flags |= 4194304 /* InCheckIdentifier */;
            const parentType = getTypeForBindingElementParent(parent, 0 /* Normal */);
            const parentTypeConstraint = parentType && mapType(parentType, getBaseConstraintOrType);
            links.flags &= ~4194304 /* InCheckIdentifier */;
            if (parentTypeConstraint && parentTypeConstraint.flags & 1048576 /* Union */ && !(rootDeclaration.kind === 169 /* Parameter */ && isSomeSymbolAssigned(rootDeclaration))) {
              const pattern = declaration.parent;
              const narrowedType = getFlowTypeOfReference(
                pattern,
                parentTypeConstraint,
                parentTypeConstraint,
                /*flowContainer*/
                void 0,
                location.flowNode
              );
              if (narrowedType.flags & 131072 /* Never */) {
                return neverType;
              }
              return getBindingElementTypeFromParentType(
                declaration,
                narrowedType,
                /*noTupleBoundsCheck*/
                true
              );
            }
          }
        }
      }
      if (isParameter(declaration) && !declaration.type && !declaration.initializer && !declaration.dotDotDotToken) {
        const func = declaration.parent;
        if (func.parameters.length >= 2 && isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
          const contextualSignature = getContextualSignature(func);
          if (contextualSignature && contextualSignature.parameters.length === 1 && signatureHasRestParameter(contextualSignature)) {
            const restType = getReducedApparentType(instantiateType(getTypeOfSymbol(contextualSignature.parameters[0]), (_a = getInferenceContext(func)) == null ? void 0 : _a.nonFixingMapper));
            if (restType.flags & 1048576 /* Union */ && everyType(restType, isTupleType) && !some(func.parameters, isSomeSymbolAssigned)) {
              const narrowedType = getFlowTypeOfReference(
                func,
                restType,
                restType,
                /*flowContainer*/
                void 0,
                location.flowNode
              );
              const index = func.parameters.indexOf(declaration) - (getThisParameter(func) ? 1 : 0);
              return getIndexedAccessType(narrowedType, getNumberLiteralType(index));
            }
          }
        }
      }
    }
    return type;
  }
  function checkIdentifierCalculateNodeCheckFlags(node, symbol) {
    if (isThisInTypeQuery(node)) return;
    if (symbol === argumentsSymbol) {
      if (isInPropertyInitializerOrClassStaticBlock(node)) {
        error(node, Diagnostics.arguments_cannot_be_referenced_in_property_initializers);
        return;
      }
      let container = getContainingFunction(node);
      if (container) {
        if (languageVersion < 2 /* ES2015 */) {
          if (container.kind === 219 /* ArrowFunction */) {
            error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES5_Consider_using_a_standard_function_expression);
          } else if (hasSyntacticModifier(container, 1024 /* Async */)) {
            error(node, Diagnostics.The_arguments_object_cannot_be_referenced_in_an_async_function_or_method_in_ES5_Consider_using_a_standard_function_or_method);
          }
        }
        getNodeLinks(container).flags |= 512 /* CaptureArguments */;
        while (container && isArrowFunction(container)) {
          container = getContainingFunction(container);
          if (container) {
            getNodeLinks(container).flags |= 512 /* CaptureArguments */;
          }
        }
      }
      return;
    }
    const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
    const targetSymbol = resolveAliasWithDeprecationCheck(localOrExportSymbol, node);
    if (isDeprecatedSymbol(targetSymbol) && isUncalledFunctionReference(node, targetSymbol) && targetSymbol.declarations) {
      addDeprecatedSuggestion(node, targetSymbol.declarations, node.escapedText);
    }
    const declaration = localOrExportSymbol.valueDeclaration;
    if (declaration && localOrExportSymbol.flags & 32 /* Class */) {
      if (isClassLike(declaration) && declaration.name !== node) {
        let container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        while (container.kind !== 307 /* SourceFile */ && container.parent !== declaration) {
          container = getThisContainer(
            container,
            /*includeArrowFunctions*/
            false,
            /*includeClassComputedPropertyName*/
            false
          );
        }
        if (container.kind !== 307 /* SourceFile */) {
          getNodeLinks(declaration).flags |= 262144 /* ContainsConstructorReference */;
          getNodeLinks(container).flags |= 262144 /* ContainsConstructorReference */;
          getNodeLinks(node).flags |= 536870912 /* ConstructorReference */;
        }
      }
    }
    checkNestedBlockScopedBinding(node, symbol);
  }
  function checkIdentifier(node, checkMode) {
    if (isThisInTypeQuery(node)) {
      return checkThisExpression(node);
    }
    const symbol = getResolvedSymbol(node);
    if (symbol === unknownSymbol) {
      return errorType;
    }
    checkIdentifierCalculateNodeCheckFlags(node, symbol);
    if (symbol === argumentsSymbol) {
      if (isInPropertyInitializerOrClassStaticBlock(node)) {
        return errorType;
      }
      return getTypeOfSymbol(symbol);
    }
    if (shouldMarkIdentifierAliasReferenced(node)) {
      markLinkedReferences(node, 1 /* Identifier */);
    }
    const localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
    let declaration = localOrExportSymbol.valueDeclaration;
    const immediateDeclaration = declaration;
    if (declaration && declaration.kind === 208 /* BindingElement */ && contains(contextualBindingPatterns, declaration.parent) && findAncestor(node, (parent) => parent === declaration.parent)) {
      return nonInferrableAnyType;
    }
    let type = getNarrowedTypeOfSymbol(localOrExportSymbol, node);
    const assignmentKind = getAssignmentTargetKind(node);
    if (assignmentKind) {
      if (!(localOrExportSymbol.flags & 3 /* Variable */) && !(isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
        const assignmentError = localOrExportSymbol.flags & 384 /* Enum */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_enum : localOrExportSymbol.flags & 32 /* Class */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_class : localOrExportSymbol.flags & 1536 /* Module */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_namespace : localOrExportSymbol.flags & 16 /* Function */ ? Diagnostics.Cannot_assign_to_0_because_it_is_a_function : localOrExportSymbol.flags & 2097152 /* Alias */ ? Diagnostics.Cannot_assign_to_0_because_it_is_an_import : Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable;
        error(node, assignmentError, symbolToString(symbol));
        return errorType;
      }
      if (isReadonlySymbol(localOrExportSymbol)) {
        if (localOrExportSymbol.flags & 3 /* Variable */) {
          error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
        } else {
          error(node, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
        }
        return errorType;
      }
    }
    const isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
    if (localOrExportSymbol.flags & 3 /* Variable */) {
      if (assignmentKind === 1 /* Definite */) {
        return isInCompoundLikeAssignment(node) ? getBaseTypeOfLiteralType(type) : type;
      }
    } else if (isAlias) {
      declaration = getDeclarationOfAliasSymbol(symbol);
    } else {
      return type;
    }
    if (!declaration) {
      return type;
    }
    type = getNarrowableTypeForReference(type, node, checkMode);
    const isParameter2 = getRootDeclaration(declaration).kind === 169 /* Parameter */;
    const declarationContainer = getControlFlowContainer(declaration);
    let flowContainer = getControlFlowContainer(node);
    const isOuterVariable = flowContainer !== declarationContainer;
    const isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
    const isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
    const typeIsAutomatic = type === autoType || type === autoArrayType;
    const isAutomaticTypeInNonNull = typeIsAutomatic && node.parent.kind === 235 /* NonNullExpression */;
    while (flowContainer !== declarationContainer && (flowContainer.kind === 218 /* FunctionExpression */ || flowContainer.kind === 219 /* ArrowFunction */ || isObjectLiteralOrClassExpressionMethodOrAccessor(flowContainer)) && (isConstantVariable(localOrExportSymbol) && type !== autoArrayType || isParameterOrMutableLocalVariable(localOrExportSymbol) && isPastLastAssignment(localOrExportSymbol, node))) {
      flowContainer = getControlFlowContainer(flowContainer);
    }
    const isNeverInitialized = immediateDeclaration && isVariableDeclaration(immediateDeclaration) && !immediateDeclaration.initializer && !immediateDeclaration.exclamationToken && isMutableLocalVariableDeclaration(immediateDeclaration) && !isSymbolAssignedDefinitely(symbol);
    const assumeInitialized = isParameter2 || isAlias || isOuterVariable && !isNeverInitialized || isSpreadDestructuringAssignmentTarget || isModuleExports || isSameScopedBindingElement(node, declaration) || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 || isInTypeQuery(node) || isInAmbientOrTypeNode(node) || node.parent.kind === 281 /* ExportSpecifier */) || node.parent.kind === 235 /* NonNullExpression */ || declaration.kind === 260 /* VariableDeclaration */ && declaration.exclamationToken || declaration.flags & 33554432 /* Ambient */;
    const initialType = isAutomaticTypeInNonNull ? undefinedType : assumeInitialized ? isParameter2 ? removeOptionalityFromDeclaredType(type, declaration) : type : typeIsAutomatic ? undefinedType : getOptionalType(type);
    const flowType = isAutomaticTypeInNonNull ? getNonNullableType(getFlowTypeOfReference(node, type, initialType, flowContainer)) : getFlowTypeOfReference(node, type, initialType, flowContainer);
    if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
      if (flowType === autoType || flowType === autoArrayType) {
        if (noImplicitAny) {
          error(getNameOfDeclaration(declaration), Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol), typeToString(flowType));
          error(node, Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
        }
        return convertAutoToAny(flowType);
      }
    } else if (!assumeInitialized && !containsUndefinedType(type) && containsUndefinedType(flowType)) {
      error(node, Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
      return type;
    }
    return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
  }
  function isSameScopedBindingElement(node, declaration) {
    if (isBindingElement(declaration)) {
      const bindingElement = findAncestor(node, isBindingElement);
      return bindingElement && getRootDeclaration(bindingElement) === getRootDeclaration(declaration);
    }
  }
  function shouldMarkIdentifierAliasReferenced(node) {
    var _a;
    const parent = node.parent;
    if (parent) {
      if (isPropertyAccessExpression(parent) && parent.expression === node) {
        return false;
      }
      if (isExportSpecifier(parent) && parent.isTypeOnly) {
        return false;
      }
      const greatGrandparent = (_a = parent.parent) == null ? void 0 : _a.parent;
      if (greatGrandparent && isExportDeclaration(greatGrandparent) && greatGrandparent.isTypeOnly) {
        return false;
      }
    }
    return true;
  }
  function isInsideFunctionOrInstancePropertyInitializer(node, threshold) {
    return !!findAncestor(node, (n) => n === threshold ? "quit" : isFunctionLike(n) || n.parent && isPropertyDeclaration(n.parent) && !hasStaticModifier(n.parent) && n.parent.initializer === n);
  }
  function getPartOfForStatementContainingNode(node, container) {
    return findAncestor(node, (n) => n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement);
  }
  function getEnclosingIterationStatement(node) {
    return findAncestor(node, (n) => !n || nodeStartsNewLexicalEnvironment(n) ? "quit" : isIterationStatement(
      n,
      /*lookInLabeledStatements*/
      false
    ));
  }
  function checkNestedBlockScopedBinding(node, symbol) {
    if (languageVersion >= 2 /* ES2015 */ || (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 || !symbol.valueDeclaration || isSourceFile(symbol.valueDeclaration) || symbol.valueDeclaration.parent.kind === 299 /* CatchClause */) {
      return;
    }
    const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration);
    const isCaptured = isInsideFunctionOrInstancePropertyInitializer(node, container);
    const enclosingIterationStatement = getEnclosingIterationStatement(container);
    if (enclosingIterationStatement) {
      if (isCaptured) {
        let capturesBlockScopeBindingInLoopBody = true;
        if (isForStatement(container)) {
          const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */);
          if (varDeclList && varDeclList.parent === container) {
            const part = getPartOfForStatementContainingNode(node.parent, container);
            if (part) {
              const links = getNodeLinks(part);
              links.flags |= 8192 /* ContainsCapturedBlockScopeBinding */;
              const capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
              pushIfUnique(capturedBindings, symbol);
              if (part === container.initializer) {
                capturesBlockScopeBindingInLoopBody = false;
              }
            }
          }
        }
        if (capturesBlockScopeBindingInLoopBody) {
          getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */;
        }
      }
      if (isForStatement(container)) {
        const varDeclList = getAncestor(symbol.valueDeclaration, 261 /* VariableDeclarationList */);
        if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
          getNodeLinks(symbol.valueDeclaration).flags |= 65536 /* NeedsLoopOutParameter */;
        }
      }
      getNodeLinks(symbol.valueDeclaration).flags |= 32768 /* BlockScopedBindingInLoop */;
    }
    if (isCaptured) {
      getNodeLinks(symbol.valueDeclaration).flags |= 16384 /* CapturedBlockScopedBinding */;
    }
  }
  function isBindingCapturedByNode(node, decl) {
    const links = getNodeLinks(node);
    return !!links && contains(links.capturedBlockScopeBindings, getSymbolOfDeclaration(decl));
  }
  function isAssignedInBodyOfForStatement(node, container) {
    let current = node;
    while (current.parent.kind === 217 /* ParenthesizedExpression */) {
      current = current.parent;
    }
    let isAssigned = false;
    if (isAssignmentTarget(current)) {
      isAssigned = true;
    } else if (current.parent.kind === 224 /* PrefixUnaryExpression */ || current.parent.kind === 225 /* PostfixUnaryExpression */) {
      const expr = current.parent;
      isAssigned = expr.operator === 46 /* PlusPlusToken */ || expr.operator === 47 /* MinusMinusToken */;
    }
    if (!isAssigned) {
      return false;
    }
    return !!findAncestor(current, (n) => n === container ? "quit" : n === container.statement);
  }
  function captureLexicalThis(node, container) {
    getNodeLinks(node).flags |= 2 /* LexicalThis */;
    if (container.kind === 172 /* PropertyDeclaration */ || container.kind === 176 /* Constructor */) {
      const classNode = container.parent;
      getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
    } else {
      getNodeLinks(container).flags |= 4 /* CaptureThis */;
    }
  }
  function findFirstSuperCall(node) {
    return isSuperCall(node) ? node : isFunctionLike(node) ? void 0 : forEachChild(node, findFirstSuperCall);
  }
  function classDeclarationExtendsNull(classDecl) {
    const classSymbol = getSymbolOfDeclaration(classDecl);
    const classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
    const baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
    return baseConstructorType === nullWideningType;
  }
  function checkThisBeforeSuper(node, container, diagnosticMessage) {
    const containingClassDecl = container.parent;
    const baseTypeNode = getClassExtendsHeritageElement(containingClassDecl);
    if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
      if (canHaveFlowNode(node) && node.flowNode && !isPostSuperFlowNode(
        node.flowNode,
        /*noCacheCheck*/
        false
      )) {
        error(node, diagnosticMessage);
      }
    }
  }
  function checkThisInStaticClassFieldInitializerInDecoratedClass(thisExpression, container) {
    if (isPropertyDeclaration(container) && hasStaticModifier(container) && legacyDecorators && container.initializer && textRangeContainsPositionInclusive(container.initializer, thisExpression.pos) && hasDecorators(container.parent)) {
      error(thisExpression, Diagnostics.Cannot_use_this_in_a_static_property_initializer_of_a_decorated_class);
    }
  }
  function checkThisExpression(node) {
    const isNodeInTypeQuery = isInTypeQuery(node);
    let container = getThisContainer(
      node,
      /*includeArrowFunctions*/
      true,
      /*includeClassComputedPropertyName*/
      true
    );
    let capturedByArrowFunction = false;
    let thisInComputedPropertyName = false;
    if (container.kind === 176 /* Constructor */) {
      checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
    }
    while (true) {
      if (container.kind === 219 /* ArrowFunction */) {
        container = getThisContainer(
          container,
          /*includeArrowFunctions*/
          false,
          !thisInComputedPropertyName
        );
        capturedByArrowFunction = true;
      }
      if (container.kind === 167 /* ComputedPropertyName */) {
        container = getThisContainer(
          container,
          !capturedByArrowFunction,
          /*includeClassComputedPropertyName*/
          false
        );
        thisInComputedPropertyName = true;
        continue;
      }
      break;
    }
    checkThisInStaticClassFieldInitializerInDecoratedClass(node, container);
    if (thisInComputedPropertyName) {
      error(node, Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
    } else {
      switch (container.kind) {
        case 267 /* ModuleDeclaration */:
          error(node, Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
          break;
        case 266 /* EnumDeclaration */:
          error(node, Diagnostics.this_cannot_be_referenced_in_current_location);
          break;
      }
    }
    if (!isNodeInTypeQuery && capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
      captureLexicalThis(node, container);
    }
    const type = tryGetThisTypeAt(
      node,
      /*includeGlobalThis*/
      true,
      container
    );
    if (noImplicitThis) {
      const globalThisType2 = getTypeOfSymbol(globalThisSymbol);
      if (type === globalThisType2 && capturedByArrowFunction) {
        error(node, Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
      } else if (!type) {
        const diag2 = error(node, Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
        if (!isSourceFile(container)) {
          const outsideThis = tryGetThisTypeAt(container);
          if (outsideThis && outsideThis !== globalThisType2) {
            addRelatedInfo(diag2, createDiagnosticForNode(container, Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
          }
        }
      }
    }
    return type || anyType;
  }
  function tryGetThisTypeAt(node, includeGlobalThis = true, container = getThisContainer(
    node,
    /*includeArrowFunctions*/
    false,
    /*includeClassComputedPropertyName*/
    false
  )) {
    const isInJS = isInJSFile(node);
    if (isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || getThisParameter(container))) {
      let thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container);
      if (!thisType) {
        const className = getClassNameFromPrototypeMethod(container);
        if (isInJS && className) {
          const classSymbol = checkExpression(className).symbol;
          if (classSymbol && classSymbol.members && classSymbol.flags & 16 /* Function */) {
            thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
          }
        } else if (isJSConstructor(container)) {
          thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
        }
        thisType || (thisType = getContextualThisParameterType(container));
      }
      if (thisType) {
        return getFlowTypeOfReference(node, thisType);
      }
    }
    if (isClassLike(container.parent)) {
      const symbol = getSymbolOfDeclaration(container.parent);
      const type = isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
      return getFlowTypeOfReference(node, type);
    }
    if (isSourceFile(container)) {
      if (container.commonJsModuleIndicator) {
        const fileSymbol = getSymbolOfDeclaration(container);
        return fileSymbol && getTypeOfSymbol(fileSymbol);
      } else if (container.externalModuleIndicator) {
        return undefinedType;
      } else if (includeGlobalThis) {
        return getTypeOfSymbol(globalThisSymbol);
      }
    }
  }
  function getExplicitThisType(node) {
    const container = getThisContainer(
      node,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    if (isFunctionLike(container)) {
      const signature = getSignatureFromDeclaration(container);
      if (signature.thisParameter) {
        return getExplicitTypeOfSymbol(signature.thisParameter);
      }
    }
    if (isClassLike(container.parent)) {
      const symbol = getSymbolOfDeclaration(container.parent);
      return isStatic(container) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
    }
  }
  function getClassNameFromPrototypeMethod(container) {
    if (container.kind === 218 /* FunctionExpression */ && isBinaryExpression(container.parent) && getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
      return container.parent.left.expression.expression;
    } else if (container.kind === 174 /* MethodDeclaration */ && container.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent) && getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
      return container.parent.parent.left.expression;
    } else if (container.kind === 218 /* FunctionExpression */ && container.parent.kind === 303 /* PropertyAssignment */ && container.parent.parent.kind === 210 /* ObjectLiteralExpression */ && isBinaryExpression(container.parent.parent.parent) && getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
      return container.parent.parent.parent.left.expression;
    } else if (container.kind === 218 /* FunctionExpression */ && isPropertyAssignment(container.parent) && isIdentifier(container.parent.name) && (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") && isObjectLiteralExpression(container.parent.parent) && isCallExpression(container.parent.parent.parent) && container.parent.parent.parent.arguments[2] === container.parent.parent && getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
      return container.parent.parent.parent.arguments[0].expression;
    } else if (isMethodDeclaration(container) && isIdentifier(container.name) && (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") && isObjectLiteralExpression(container.parent) && isCallExpression(container.parent.parent) && container.parent.parent.arguments[2] === container.parent && getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
      return container.parent.parent.arguments[0].expression;
    }
  }
  function getTypeForThisExpressionFromJSDoc(node) {
    const thisTag = getJSDocThisTag(node);
    if (thisTag && thisTag.typeExpression) {
      return getTypeFromTypeNode(thisTag.typeExpression);
    }
    const signature = getSignatureOfTypeTag(node);
    if (signature) {
      return getThisTypeOfSignature(signature);
    }
  }
  function isInConstructorArgumentInitializer(node, constructorDecl) {
    return !!findAncestor(node, (n) => isFunctionLikeDeclaration(n) ? "quit" : n.kind === 169 /* Parameter */ && n.parent === constructorDecl);
  }
  function checkSuperExpression(node) {
    const isCallExpression2 = node.parent.kind === 213 /* CallExpression */ && node.parent.expression === node;
    const immediateContainer = getSuperContainer(
      node,
      /*stopOnFunctions*/
      true
    );
    let container = immediateContainer;
    let needToCaptureLexicalThis = false;
    let inAsyncFunction = false;
    if (!isCallExpression2) {
      while (container && container.kind === 219 /* ArrowFunction */) {
        if (hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true;
        container = getSuperContainer(
          container,
          /*stopOnFunctions*/
          true
        );
        needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
      }
      if (container && hasSyntacticModifier(container, 1024 /* Async */)) inAsyncFunction = true;
    }
    let nodeCheckFlag = 0;
    if (!container || !isLegalUsageOfSuperExpression(container)) {
      const current = findAncestor(node, (n) => n === container ? "quit" : n.kind === 167 /* ComputedPropertyName */);
      if (current && current.kind === 167 /* ComputedPropertyName */) {
        error(node, Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
      } else if (isCallExpression2) {
        error(node, Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
      } else if (!container || !container.parent || !(isClassLike(container.parent) || container.parent.kind === 210 /* ObjectLiteralExpression */)) {
        error(node, Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
      } else {
        error(node, Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
      }
      return errorType;
    }
    if (!isCallExpression2 && immediateContainer.kind === 176 /* Constructor */) {
      checkThisBeforeSuper(node, container, Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
    }
    if (isStatic(container) || isCallExpression2) {
      nodeCheckFlag = 32 /* SuperStatic */;
      if (!isCallExpression2 && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && (isPropertyDeclaration(container) || isClassStaticBlockDeclaration(container))) {
        forEachEnclosingBlockScopeContainer(node.parent, (current) => {
          if (!isSourceFile(current) || isExternalOrCommonJsModule(current)) {
            getNodeLinks(current).flags |= 2097152 /* ContainsSuperPropertyInStaticInitializer */;
          }
        });
      }
    } else {
      nodeCheckFlag = 16 /* SuperInstance */;
    }
    getNodeLinks(node).flags |= nodeCheckFlag;
    if (container.kind === 174 /* MethodDeclaration */ && inAsyncFunction) {
      if (isSuperProperty(node.parent) && isAssignmentTarget(node.parent)) {
        getNodeLinks(container).flags |= 256 /* MethodWithSuperPropertyAssignmentInAsync */;
      } else {
        getNodeLinks(container).flags |= 128 /* MethodWithSuperPropertyAccessInAsync */;
      }
    }
    if (needToCaptureLexicalThis) {
      captureLexicalThis(node.parent, container);
    }
    if (container.parent.kind === 210 /* ObjectLiteralExpression */) {
      if (languageVersion < 2 /* ES2015 */) {
        error(node, Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
        return errorType;
      } else {
        return anyType;
      }
    }
    const classLikeDeclaration = container.parent;
    if (!getClassExtendsHeritageElement(classLikeDeclaration)) {
      error(node, Diagnostics.super_can_only_be_referenced_in_a_derived_class);
      return errorType;
    }
    if (classDeclarationExtendsNull(classLikeDeclaration)) {
      return isCallExpression2 ? errorType : nullWideningType;
    }
    const classType = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(classLikeDeclaration));
    const baseClassType = classType && getBaseTypes(classType)[0];
    if (!baseClassType) {
      return errorType;
    }
    if (container.kind === 176 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
      error(node, Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
      return errorType;
    }
    return nodeCheckFlag === 32 /* SuperStatic */ ? getBaseConstructorTypeOfClass(classType) : getTypeWithThisArgument(baseClassType, classType.thisType);
    function isLegalUsageOfSuperExpression(container2) {
      if (isCallExpression2) {
        return container2.kind === 176 /* Constructor */;
      } else {
        if (isClassLike(container2.parent) || container2.parent.kind === 210 /* ObjectLiteralExpression */) {
          if (isStatic(container2)) {
            return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 175 /* ClassStaticBlockDeclaration */;
          } else {
            return container2.kind === 174 /* MethodDeclaration */ || container2.kind === 173 /* MethodSignature */ || container2.kind === 177 /* GetAccessor */ || container2.kind === 178 /* SetAccessor */ || container2.kind === 172 /* PropertyDeclaration */ || container2.kind === 171 /* PropertySignature */ || container2.kind === 176 /* Constructor */;
          }
        }
      }
      return false;
    }
  }
  function getContainingObjectLiteral(func) {
    return (func.kind === 174 /* MethodDeclaration */ || func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */) && func.parent.kind === 210 /* ObjectLiteralExpression */ ? func.parent : func.kind === 218 /* FunctionExpression */ && func.parent.kind === 303 /* PropertyAssignment */ ? func.parent.parent : void 0;
  }
  function getThisTypeArgument(type) {
    return getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : void 0;
  }
  function getThisTypeFromContextualType(type) {
    return mapType(type, (t) => {
      return t.flags & 2097152 /* Intersection */ ? forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
    });
  }
  function getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType) {
    let literal = containingLiteral;
    let type = contextualType;
    while (type) {
      const thisType = getThisTypeFromContextualType(type);
      if (thisType) {
        return thisType;
      }
      if (literal.parent.kind !== 303 /* PropertyAssignment */) {
        break;
      }
      literal = literal.parent.parent;
      type = getApparentTypeOfContextualType(
        literal,
        /*contextFlags*/
        void 0
      );
    }
  }
  function getContextualThisParameterType(func) {
    if (func.kind === 219 /* ArrowFunction */) {
      return void 0;
    }
    if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
      const contextualSignature = getContextualSignature(func);
      if (contextualSignature) {
        const thisParameter = contextualSignature.thisParameter;
        if (thisParameter) {
          return getTypeOfSymbol(thisParameter);
        }
      }
    }
    const inJs = isInJSFile(func);
    if (noImplicitThis || inJs) {
      const containingLiteral = getContainingObjectLiteral(func);
      if (containingLiteral) {
        const contextualType = getApparentTypeOfContextualType(
          containingLiteral,
          /*contextFlags*/
          void 0
        );
        const thisType = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType);
        if (thisType) {
          return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
        }
        return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
      }
      const parent = walkUpParenthesizedExpressions(func.parent);
      if (isAssignmentExpression(parent)) {
        const target = parent.left;
        if (isAccessExpression(target)) {
          const { expression } = target;
          if (inJs && isIdentifier(expression)) {
            const sourceFile = getSourceFileOfNode(parent);
            if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
              return void 0;
            }
          }
          return getWidenedType(checkExpressionCached(expression));
        }
      }
    }
    return void 0;
  }
  function getContextuallyTypedParameterType(parameter) {
    const func = parameter.parent;
    if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
      return void 0;
    }
    const iife = getImmediatelyInvokedFunctionExpression(func);
    if (iife && iife.arguments) {
      const args = getEffectiveCallArguments(iife);
      const indexOfParameter = func.parameters.indexOf(parameter);
      if (parameter.dotDotDotToken) {
        return getSpreadArgumentType(
          args,
          indexOfParameter,
          args.length,
          anyType,
          /*context*/
          void 0,
          0 /* Normal */
        );
      }
      const links = getNodeLinks(iife);
      const cached = links.resolvedSignature;
      links.resolvedSignature = anySignature;
      const type = indexOfParameter < args.length ? getWidenedLiteralType(checkExpression(args[indexOfParameter])) : parameter.initializer ? void 0 : undefinedWideningType;
      links.resolvedSignature = cached;
      return type;
    }
    const contextualSignature = getContextualSignature(func);
    if (contextualSignature) {
      const index = func.parameters.indexOf(parameter) - (getThisParameter(func) ? 1 : 0);
      return parameter.dotDotDotToken && lastOrUndefined(func.parameters) === parameter ? getRestTypeAtPosition(contextualSignature, index) : tryGetTypeAtPosition(contextualSignature, index);
    }
  }
  function getContextualTypeForVariableLikeDeclaration(declaration, contextFlags) {
    const typeNode = getEffectiveTypeAnnotationNode(declaration) || (isInJSFile(declaration) ? tryGetJSDocSatisfiesTypeNode(declaration) : void 0);
    if (typeNode) {
      return getTypeFromTypeNode(typeNode);
    }
    switch (declaration.kind) {
      case 169 /* Parameter */:
        return getContextuallyTypedParameterType(declaration);
      case 208 /* BindingElement */:
        return getContextualTypeForBindingElement(declaration, contextFlags);
      case 172 /* PropertyDeclaration */:
        if (isStatic(declaration)) {
          return getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags);
        }
    }
  }
  function getContextualTypeForBindingElement(declaration, contextFlags) {
    const parent = declaration.parent.parent;
    const name = declaration.propertyName || declaration.name;
    const parentType = getContextualTypeForVariableLikeDeclaration(parent, contextFlags) || parent.kind !== 208 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent, declaration.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */);
    if (!parentType || isBindingPattern(name) || isComputedNonLiteralName(name)) return void 0;
    if (parent.name.kind === 207 /* ArrayBindingPattern */) {
      const index = indexOfNode(declaration.parent.elements, declaration);
      if (index < 0) return void 0;
      return getContextualTypeForElementExpression(parentType, index);
    }
    const nameType = getLiteralTypeFromPropertyName(name);
    if (isTypeUsableAsPropertyName(nameType)) {
      const text = getPropertyNameFromType(nameType);
      return getTypeOfPropertyOfType(parentType, text);
    }
  }
  function getContextualTypeForStaticPropertyDeclaration(declaration, contextFlags) {
    const parentType = isExpression(declaration.parent) && getContextualType(declaration.parent, contextFlags);
    if (!parentType) return void 0;
    return getTypeOfPropertyOfContextualType(parentType, getSymbolOfDeclaration(declaration).escapedName);
  }
  function getContextualTypeForInitializerExpression(node, contextFlags) {
    const declaration = node.parent;
    if (hasInitializer(declaration) && node === declaration.initializer) {
      const result = getContextualTypeForVariableLikeDeclaration(declaration, contextFlags);
      if (result) {
        return result;
      }
      if (!(contextFlags & 8 /* SkipBindingPatterns */) && isBindingPattern(declaration.name) && declaration.name.elements.length > 0) {
        return getTypeFromBindingPattern(
          declaration.name,
          /*includePatternInType*/
          true,
          /*reportErrors*/
          false
        );
      }
    }
    return void 0;
  }
  function getContextualTypeForReturnExpression(node, contextFlags) {
    const func = getContainingFunction(node);
    if (func) {
      let contextualReturnType = getContextualReturnType(func, contextFlags);
      if (contextualReturnType) {
        const functionFlags = getFunctionFlags(func);
        if (functionFlags & 1 /* Generator */) {
          const isAsyncGenerator = (functionFlags & 2 /* Async */) !== 0;
          if (contextualReturnType.flags & 1048576 /* Union */) {
            contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator));
          }
          const iterationReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
          if (!iterationReturnType) {
            return void 0;
          }
          contextualReturnType = iterationReturnType;
        }
        if (functionFlags & 2 /* Async */) {
          const contextualAwaitedType = mapType(contextualReturnType, getAwaitedTypeNoAlias);
          return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
        }
        return contextualReturnType;
      }
    }
    return void 0;
  }
  function getContextualTypeForAwaitOperand(node, contextFlags) {
    const contextualType = getContextualType(node, contextFlags);
    if (contextualType) {
      const contextualAwaitedType = getAwaitedTypeNoAlias(contextualType);
      return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
    }
    return void 0;
  }
  function getContextualTypeForYieldOperand(node, contextFlags) {
    const func = getContainingFunction(node);
    if (func) {
      const functionFlags = getFunctionFlags(func);
      let contextualReturnType = getContextualReturnType(func, contextFlags);
      if (contextualReturnType) {
        const isAsyncGenerator = (functionFlags & 2 /* Async */) !== 0;
        if (!node.asteriskToken && contextualReturnType.flags & 1048576 /* Union */) {
          contextualReturnType = filterType(contextualReturnType, (type) => !!getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, type, isAsyncGenerator));
        }
        if (node.asteriskToken) {
          const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(contextualReturnType, isAsyncGenerator);
          const yieldType = (iterationTypes == null ? void 0 : iterationTypes.yieldType) ?? silentNeverType;
          const returnType = getContextualType(node, contextFlags) ?? silentNeverType;
          const nextType = (iterationTypes == null ? void 0 : iterationTypes.nextType) ?? unknownType;
          const generatorType = createGeneratorType(
            yieldType,
            returnType,
            nextType,
            /*isAsyncGenerator*/
            false
          );
          if (isAsyncGenerator) {
            const asyncGeneratorType = createGeneratorType(
              yieldType,
              returnType,
              nextType,
              /*isAsyncGenerator*/
              true
            );
            return getUnionType([generatorType, asyncGeneratorType]);
          }
          return generatorType;
        }
        return getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, isAsyncGenerator);
      }
    }
    return void 0;
  }
  function isInParameterInitializerBeforeContainingFunction(node) {
    let inBindingInitializer = false;
    while (node.parent && !isFunctionLike(node.parent)) {
      if (isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
        return true;
      }
      if (isBindingElement(node.parent) && node.parent.initializer === node) {
        inBindingInitializer = true;
      }
      node = node.parent;
    }
    return false;
  }
  function getContextualIterationType(kind, functionDecl) {
    const isAsync = !!(getFunctionFlags(functionDecl) & 2 /* Async */);
    const contextualReturnType = getContextualReturnType(
      functionDecl,
      /*contextFlags*/
      void 0
    );
    if (contextualReturnType) {
      return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync) || void 0;
    }
    return void 0;
  }
  function getContextualReturnType(functionDecl, contextFlags) {
    const returnType = getReturnTypeFromAnnotation(functionDecl);
    if (returnType) {
      return returnType;
    }
    const signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
    if (signature && !isResolvingReturnTypeOfSignature(signature)) {
      const returnType2 = getReturnTypeOfSignature(signature);
      const functionFlags = getFunctionFlags(functionDecl);
      if (functionFlags & 1 /* Generator */) {
        return filterType(returnType2, (t) => {
          return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || checkGeneratorInstantiationAssignabilityToReturnType(
            t,
            functionFlags,
            /*errorNode*/
            void 0
          );
        });
      }
      if (functionFlags & 2 /* Async */) {
        return filterType(returnType2, (t) => {
          return !!(t.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 58982400 /* InstantiableNonPrimitive */)) || !!getAwaitedTypeOfPromise(t);
        });
      }
      return returnType2;
    }
    const iife = getImmediatelyInvokedFunctionExpression(functionDecl);
    if (iife) {
      return getContextualType(iife, contextFlags);
    }
    return void 0;
  }
  function getContextualTypeForArgument(callTarget, arg) {
    const args = getEffectiveCallArguments(callTarget);
    const argIndex = args.indexOf(arg);
    return argIndex === -1 ? void 0 : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
  }
  function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
    if (isImportCall(callTarget)) {
      return argIndex === 0 ? stringType : argIndex === 1 ? getGlobalImportCallOptionsType(
        /*reportErrors*/
        false
      ) : anyType;
    }
    const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
    if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
      return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
    }
    const restIndex = signature.parameters.length - 1;
    return signatureHasRestParameter(signature) && argIndex >= restIndex ? getIndexedAccessType(getTypeOfSymbol(signature.parameters[restIndex]), getNumberLiteralType(argIndex - restIndex), 256 /* Contextual */) : getTypeAtPosition(signature, argIndex);
  }
  function getContextualTypeForDecorator(decorator) {
    const signature = getDecoratorCallSignature(decorator);
    return signature ? getOrCreateTypeFromSignature(signature) : void 0;
  }
  function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
    if (template.parent.kind === 215 /* TaggedTemplateExpression */) {
      return getContextualTypeForArgument(template.parent, substitutionExpression);
    }
    return void 0;
  }
  function getContextualTypeForBinaryOperand(node, contextFlags) {
    const binaryExpression = node.parent;
    const { left, operatorToken, right } = binaryExpression;
    switch (operatorToken.kind) {
      case 64 /* EqualsToken */:
      case 77 /* AmpersandAmpersandEqualsToken */:
      case 76 /* BarBarEqualsToken */:
      case 78 /* QuestionQuestionEqualsToken */:
        return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : void 0;
      case 57 /* BarBarToken */:
      case 61 /* QuestionQuestionToken */:
        const type = getContextualType(binaryExpression, contextFlags);
        return node === right && (type && type.pattern || !type && !isDefaultedExpandoInitializer(binaryExpression)) ? getTypeOfExpression(left) : type;
      case 56 /* AmpersandAmpersandToken */:
      case 28 /* CommaToken */:
        return node === right ? getContextualType(binaryExpression, contextFlags) : void 0;
      default:
        return void 0;
    }
  }
  function getSymbolForExpression(e) {
    if (canHaveSymbol(e) && e.symbol) {
      return e.symbol;
    }
    if (isIdentifier(e)) {
      return getResolvedSymbol(e);
    }
    if (isPropertyAccessExpression(e)) {
      const lhsType = getTypeOfExpression(e.expression);
      return isPrivateIdentifier(e.name) ? tryGetPrivateIdentifierPropertyOfType(lhsType, e.name) : getPropertyOfType(lhsType, e.name.escapedText);
    }
    if (isElementAccessExpression(e)) {
      const propType = checkExpressionCached(e.argumentExpression);
      if (!isTypeUsableAsPropertyName(propType)) {
        return void 0;
      }
      const lhsType = getTypeOfExpression(e.expression);
      return getPropertyOfType(lhsType, getPropertyNameFromType(propType));
    }
    return void 0;
    function tryGetPrivateIdentifierPropertyOfType(type, id) {
      const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(id.escapedText, id);
      return lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(type, lexicallyScopedSymbol);
    }
  }
  function getContextualTypeForAssignmentDeclaration(binaryExpression) {
    var _a, _b;
    const kind = getAssignmentDeclarationKind(binaryExpression);
    switch (kind) {
      case 0 /* None */:
      case 4 /* ThisProperty */:
        const lhsSymbol = getSymbolForExpression(binaryExpression.left);
        const decl = lhsSymbol && lhsSymbol.valueDeclaration;
        if (decl && (isPropertyDeclaration(decl) || isPropertySignature(decl))) {
          const overallAnnotation = getEffectiveTypeAnnotationNode(decl);
          return overallAnnotation && instantiateType(getTypeFromTypeNode(overallAnnotation), getSymbolLinks(lhsSymbol).mapper) || (isPropertyDeclaration(decl) ? decl.initializer && getTypeOfExpression(binaryExpression.left) : void 0);
        }
        if (kind === 0 /* None */) {
          return getTypeOfExpression(binaryExpression.left);
        }
        return getContextualTypeForThisPropertyAssignment(binaryExpression);
      case 5 /* Property */:
        if (isPossiblyAliasedThisProperty(binaryExpression, kind)) {
          return getContextualTypeForThisPropertyAssignment(binaryExpression);
        } else if (!canHaveSymbol(binaryExpression.left) || !binaryExpression.left.symbol) {
          return getTypeOfExpression(binaryExpression.left);
        } else {
          const decl2 = binaryExpression.left.symbol.valueDeclaration;
          if (!decl2) {
            return void 0;
          }
          const lhs = cast(binaryExpression.left, isAccessExpression);
          const overallAnnotation = getEffectiveTypeAnnotationNode(decl2);
          if (overallAnnotation) {
            return getTypeFromTypeNode(overallAnnotation);
          } else if (isIdentifier(lhs.expression)) {
            const id = lhs.expression;
            const parentSymbol = resolveName(
              id,
              id.escapedText,
              111551 /* Value */,
              /*nameNotFoundMessage*/
              void 0,
              /*isUse*/
              true
            );
            if (parentSymbol) {
              const annotated2 = parentSymbol.valueDeclaration && getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
              if (annotated2) {
                const nameStr = getElementOrPropertyAccessName(lhs);
                if (nameStr !== void 0) {
                  return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated2), nameStr);
                }
              }
              return void 0;
            }
          }
          return isInJSFile(decl2) || decl2 === binaryExpression.left ? void 0 : getTypeOfExpression(binaryExpression.left);
        }
      case 1 /* ExportsProperty */:
      case 6 /* Prototype */:
      case 3 /* PrototypeProperty */:
      case 2 /* ModuleExports */:
        let valueDeclaration;
        if (kind !== 2 /* ModuleExports */) {
          valueDeclaration = canHaveSymbol(binaryExpression.left) ? (_a = binaryExpression.left.symbol) == null ? void 0 : _a.valueDeclaration : void 0;
        }
        valueDeclaration || (valueDeclaration = (_b = binaryExpression.symbol) == null ? void 0 : _b.valueDeclaration);
        const annotated = valueDeclaration && getEffectiveTypeAnnotationNode(valueDeclaration);
        return annotated ? getTypeFromTypeNode(annotated) : void 0;
      case 7 /* ObjectDefinePropertyValue */:
      case 8 /* ObjectDefinePropertyExports */:
      case 9 /* ObjectDefinePrototypeProperty */:
        return Debug.fail("Does not apply");
      default:
        return Debug.assertNever(kind);
    }
  }
  function isPossiblyAliasedThisProperty(declaration, kind = getAssignmentDeclarationKind(declaration)) {
    if (kind === 4 /* ThisProperty */) {
      return true;
    }
    if (!isInJSFile(declaration) || kind !== 5 /* Property */ || !isIdentifier(declaration.left.expression)) {
      return false;
    }
    const name = declaration.left.expression.escapedText;
    const symbol = resolveName(
      declaration.left,
      name,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true,
      /*excludeGlobals*/
      true
    );
    return isThisInitializedDeclaration(symbol == null ? void 0 : symbol.valueDeclaration);
  }
  function getContextualTypeForThisPropertyAssignment(binaryExpression) {
    if (!binaryExpression.symbol) return getTypeOfExpression(binaryExpression.left);
    if (binaryExpression.symbol.valueDeclaration) {
      const annotated = getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
      if (annotated) {
        const type = getTypeFromTypeNode(annotated);
        if (type) {
          return type;
        }
      }
    }
    const thisAccess = cast(binaryExpression.left, isAccessExpression);
    if (!isObjectLiteralMethod(getThisContainer(
      thisAccess.expression,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    ))) {
      return void 0;
    }
    const thisType = checkThisExpression(thisAccess.expression);
    const nameStr = getElementOrPropertyAccessName(thisAccess);
    return nameStr !== void 0 && getTypeOfPropertyOfContextualType(thisType, nameStr) || void 0;
  }
  function isCircularMappedProperty(symbol) {
    return !!(getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.links.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
  }
  function isExcludedMappedPropertyName(constraint, propertyNameType) {
    if (constraint.flags & 16777216 /* Conditional */) {
      const type = constraint;
      return !!(getReducedType(getTrueTypeFromConditionalType(type)).flags & 131072 /* Never */) && getActualTypeVariable(getFalseTypeFromConditionalType(type)) === getActualTypeVariable(type.checkType) && isTypeAssignableTo(propertyNameType, type.extendsType);
    }
    if (constraint.flags & 2097152 /* Intersection */) {
      return some(constraint.types, (t) => isExcludedMappedPropertyName(t, propertyNameType));
    }
    return false;
  }
  function getTypeOfPropertyOfContextualType(type, name, nameType) {
    return mapType(
      type,
      (t) => {
        if (t.flags & 2097152 /* Intersection */) {
          let types;
          let indexInfoCandidates;
          let ignoreIndexInfos = false;
          for (const constituentType of t.types) {
            if (!(constituentType.flags & 524288 /* Object */)) {
              continue;
            }
            if (isGenericMappedType(constituentType) && getMappedTypeNameTypeKind(constituentType) !== 2 /* Remapping */) {
              const substitutedType = getIndexedMappedTypeSubstitutedTypeOfContextualType(constituentType, name, nameType);
              types = appendContextualPropertyTypeConstituent(types, substitutedType);
              continue;
            }
            const propertyType = getTypeOfConcretePropertyOfContextualType(constituentType, name);
            if (!propertyType) {
              if (!ignoreIndexInfos) {
                indexInfoCandidates = append(indexInfoCandidates, constituentType);
              }
              continue;
            }
            ignoreIndexInfos = true;
            indexInfoCandidates = void 0;
            types = appendContextualPropertyTypeConstituent(types, propertyType);
          }
          if (indexInfoCandidates) {
            for (const candidate of indexInfoCandidates) {
              const indexInfoType = getTypeFromIndexInfosOfContextualType(candidate, name, nameType);
              types = appendContextualPropertyTypeConstituent(types, indexInfoType);
            }
          }
          if (!types) {
            return;
          }
          if (types.length === 1) {
            return types[0];
          }
          return getIntersectionType(types);
        }
        if (!(t.flags & 524288 /* Object */)) {
          return;
        }
        return isGenericMappedType(t) && getMappedTypeNameTypeKind(t) !== 2 /* Remapping */ ? getIndexedMappedTypeSubstitutedTypeOfContextualType(t, name, nameType) : getTypeOfConcretePropertyOfContextualType(t, name) ?? getTypeFromIndexInfosOfContextualType(t, name, nameType);
      },
      /*noReductions*/
      true
    );
  }
  function appendContextualPropertyTypeConstituent(types, type) {
    return type ? append(types, type.flags & 1 /* Any */ ? unknownType : type) : types;
  }
  function getIndexedMappedTypeSubstitutedTypeOfContextualType(type, name, nameType) {
    const propertyNameType = nameType || getStringLiteralType(unescapeLeadingUnderscores(name));
    const constraint = getConstraintTypeFromMappedType(type);
    if (type.nameType && isExcludedMappedPropertyName(type.nameType, propertyNameType) || isExcludedMappedPropertyName(constraint, propertyNameType)) {
      return;
    }
    const constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
    if (!isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
      return;
    }
    return substituteIndexedMappedType(type, propertyNameType);
  }
  function getTypeOfConcretePropertyOfContextualType(type, name) {
    const prop = getPropertyOfType(type, name);
    if (!prop || isCircularMappedProperty(prop)) {
      return;
    }
    return removeMissingType(getTypeOfSymbol(prop), !!(prop.flags & 16777216 /* Optional */));
  }
  function getTypeFromIndexInfosOfContextualType(type, name, nameType) {
    var _a;
    if (isTupleType(type) && isNumericLiteralName(name) && +name >= 0) {
      const restType = getElementTypeOfSliceOfTupleType(
        type,
        type.target.fixedLength,
        /*endSkipCount*/
        0,
        /*writing*/
        false,
        /*noReductions*/
        true
      );
      if (restType) {
        return restType;
      }
    }
    return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(type), nameType || getStringLiteralType(unescapeLeadingUnderscores(name)))) == null ? void 0 : _a.type;
  }
  function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
    Debug.assert(isObjectLiteralMethod(node));
    if (node.flags & 67108864 /* InWithStatement */) {
      return void 0;
    }
    return getContextualTypeForObjectLiteralElement(node, contextFlags);
  }
  function getContextualTypeForObjectLiteralElement(element, contextFlags) {
    const objectLiteral = element.parent;
    const propertyAssignmentType = isPropertyAssignment(element) && getContextualTypeForVariableLikeDeclaration(element, contextFlags);
    if (propertyAssignmentType) {
      return propertyAssignmentType;
    }
    const type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
    if (type) {
      if (hasBindableName(element)) {
        const symbol = getSymbolOfDeclaration(element);
        return getTypeOfPropertyOfContextualType(type, symbol.escapedName, getSymbolLinks(symbol).nameType);
      }
      if (hasDynamicName(element)) {
        const name = getNameOfDeclaration(element);
        if (name && isComputedPropertyName(name)) {
          const exprType = checkExpression(name.expression);
          const propType = isTypeUsableAsPropertyName(exprType) && getTypeOfPropertyOfContextualType(type, getPropertyNameFromType(exprType));
          if (propType) {
            return propType;
          }
        }
      }
      if (element.name) {
        const nameType = getLiteralTypeFromPropertyName(element.name);
        return mapType(
          type,
          (t) => {
            var _a;
            return (_a = findApplicableIndexInfo(getIndexInfosOfStructuredType(t), nameType)) == null ? void 0 : _a.type;
          },
          /*noReductions*/
          true
        );
      }
    }
    return void 0;
  }
  function getSpreadIndices(elements) {
    let first2, last2;
    for (let i = 0; i < elements.length; i++) {
      if (isSpreadElement(elements[i])) {
        first2 ?? (first2 = i);
        last2 = i;
      }
    }
    return { first: first2, last: last2 };
  }
  function getContextualTypeForElementExpression(type, index, length2, firstSpreadIndex, lastSpreadIndex) {
    return type && mapType(
      type,
      (t) => {
        if (isTupleType(t)) {
          if ((firstSpreadIndex === void 0 || index < firstSpreadIndex) && index < t.target.fixedLength) {
            return removeMissingType(getTypeArguments(t)[index], !!(t.target.elementFlags[index] && 2 /* Optional */));
          }
          const offset = length2 !== void 0 && (lastSpreadIndex === void 0 || index > lastSpreadIndex) ? length2 - index : 0;
          const fixedEndLength = offset > 0 && t.target.combinedFlags & 12 /* Variable */ ? getEndElementCount(t.target, 3 /* Fixed */) : 0;
          if (offset > 0 && offset <= fixedEndLength) {
            return getTypeArguments(t)[getTypeReferenceArity(t) - offset];
          }
          return getElementTypeOfSliceOfTupleType(
            t,
            firstSpreadIndex === void 0 ? t.target.fixedLength : Math.min(t.target.fixedLength, firstSpreadIndex),
            length2 === void 0 || lastSpreadIndex === void 0 ? fixedEndLength : Math.min(fixedEndLength, length2 - lastSpreadIndex),
            /*writing*/
            false,
            /*noReductions*/
            true
          );
        }
        return (!firstSpreadIndex || index < firstSpreadIndex) && getTypeOfPropertyOfContextualType(t, "" + index) || getIteratedTypeOrElementType(
          1 /* Element */,
          t,
          undefinedType,
          /*errorNode*/
          void 0,
          /*checkAssignability*/
          false
        );
      },
      /*noReductions*/
      true
    );
  }
  function getContextualTypeForConditionalOperand(node, contextFlags) {
    const conditional = node.parent;
    return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : void 0;
  }
  function getContextualTypeForChildJsxExpression(node, child, contextFlags) {
    const attributesType = getApparentTypeOfContextualType(node.openingElement.attributes, contextFlags);
    const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
    if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
      return void 0;
    }
    const realChildren = getSemanticJsxChildren(node.children);
    const childIndex = realChildren.indexOf(child);
    const childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
    return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(
      childFieldType,
      (t) => {
        if (isArrayLikeType(t)) {
          return getIndexedAccessType(t, getNumberLiteralType(childIndex));
        } else {
          return t;
        }
      },
      /*noReductions*/
      true
    ));
  }
  function getContextualTypeForJsxExpression(node, contextFlags) {
    const exprParent = node.parent;
    return isJsxAttributeLike(exprParent) ? getContextualType(node, contextFlags) : isJsxElement(exprParent) ? getContextualTypeForChildJsxExpression(exprParent, node, contextFlags) : void 0;
  }
  function getContextualTypeForJsxAttribute(attribute, contextFlags) {
    if (isJsxAttribute(attribute)) {
      const attributesType = getApparentTypeOfContextualType(attribute.parent, contextFlags);
      if (!attributesType || isTypeAny(attributesType)) {
        return void 0;
      }
      return getTypeOfPropertyOfContextualType(attributesType, getEscapedTextOfJsxAttributeName(attribute.name));
    } else {
      return getContextualType(attribute.parent, contextFlags);
    }
  }
  function isPossiblyDiscriminantValue(node) {
    switch (node.kind) {
      case 11 /* StringLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 228 /* TemplateExpression */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 106 /* NullKeyword */:
      case 80 /* Identifier */:
      case 157 /* UndefinedKeyword */:
        return true;
      case 211 /* PropertyAccessExpression */:
      case 217 /* ParenthesizedExpression */:
        return isPossiblyDiscriminantValue(node.expression);
      case 294 /* JsxExpression */:
        return !node.expression || isPossiblyDiscriminantValue(node.expression);
    }
    return false;
  }
  function discriminateContextualTypeByObjectMembers(node, contextualType) {
    const key = `D${getNodeId(node)},${getTypeId(contextualType)}`;
    return getCachedType(key) ?? setCachedType(
      key,
      getMatchingUnionConstituentForObjectLiteral(contextualType, node) ?? discriminateTypeByDiscriminableItems(
        contextualType,
        concatenate(
          map(
            filter(node.properties, (p) => {
              if (!p.symbol) {
                return false;
              }
              if (p.kind === 303 /* PropertyAssignment */) {
                return isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName);
              }
              if (p.kind === 304 /* ShorthandPropertyAssignment */) {
                return isDiscriminantProperty(contextualType, p.symbol.escapedName);
              }
              return false;
            }),
            (prop) => [() => getContextFreeTypeOfExpression(prop.kind === 303 /* PropertyAssignment */ ? prop.initializer : prop.name), prop.symbol.escapedName]
          ),
          map(
            filter(getPropertiesOfType(contextualType), (s) => {
              var _a;
              return !!(s.flags & 16777216 /* Optional */) && !!((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members) && !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName);
            }),
            (s) => [() => undefinedType, s.escapedName]
          )
        ),
        isTypeAssignableTo
      )
    );
  }
  function discriminateContextualTypeByJSXAttributes(node, contextualType) {
    const key = `D${getNodeId(node)},${getTypeId(contextualType)}`;
    const cached = getCachedType(key);
    if (cached) return cached;
    const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
    return setCachedType(
      key,
      discriminateTypeByDiscriminableItems(
        contextualType,
        concatenate(
          map(
            filter(node.properties, (p) => !!p.symbol && p.kind === 291 /* JsxAttribute */ && isDiscriminantProperty(contextualType, p.symbol.escapedName) && (!p.initializer || isPossiblyDiscriminantValue(p.initializer))),
            (prop) => [!prop.initializer ? () => trueType : () => getContextFreeTypeOfExpression(prop.initializer), prop.symbol.escapedName]
          ),
          map(
            filter(getPropertiesOfType(contextualType), (s) => {
              var _a;
              if (!(s.flags & 16777216 /* Optional */) || !((_a = node == null ? void 0 : node.symbol) == null ? void 0 : _a.members)) {
                return false;
              }
              const element = node.parent.parent;
              if (s.escapedName === jsxChildrenPropertyName && isJsxElement(element) && getSemanticJsxChildren(element.children).length) {
                return false;
              }
              return !node.symbol.members.has(s.escapedName) && isDiscriminantProperty(contextualType, s.escapedName);
            }),
            (s) => [() => undefinedType, s.escapedName]
          )
        ),
        isTypeAssignableTo
      )
    );
  }
  function getApparentTypeOfContextualType(node, contextFlags) {
    const contextualType = isObjectLiteralMethod(node) ? getContextualTypeForObjectLiteralMethod(node, contextFlags) : getContextualType(node, contextFlags);
    const instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
    if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
      const apparentType = mapType(
        instantiatedType,
        // When obtaining apparent type of *contextual* type we don't want to get apparent type of mapped types.
        // That would evaluate mapped types with array or tuple type constraints too eagerly
        // and thus it would prevent `getTypeOfPropertyOfContextualType` from obtaining per-position contextual type for elements of array literal expressions.
        // Apparent type of other mapped types is already the mapped type itself so we can just avoid calling `getApparentType` here for all mapped types.
        (t) => getObjectFlags(t) & 32 /* Mapped */ ? t : getApparentType(t),
        /*noReductions*/
        true
      );
      return apparentType.flags & 1048576 /* Union */ && isObjectLiteralExpression(node) ? discriminateContextualTypeByObjectMembers(node, apparentType) : apparentType.flags & 1048576 /* Union */ && isJsxAttributes(node) ? discriminateContextualTypeByJSXAttributes(node, apparentType) : apparentType;
    }
  }
  function instantiateContextualType(contextualType, node, contextFlags) {
    if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* Instantiable */)) {
      const inferenceContext = getInferenceContext(node);
      if (inferenceContext && contextFlags & 1 /* Signature */ && some(inferenceContext.inferences, hasInferenceCandidatesOrDefault)) {
        return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
      }
      if (inferenceContext == null ? void 0 : inferenceContext.returnMapper) {
        const type = instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
        return type.flags & 1048576 /* Union */ && containsType(type.types, regularFalseType) && containsType(type.types, regularTrueType) ? filterType(type, (t) => t !== regularFalseType && t !== regularTrueType) : type;
      }
    }
    return contextualType;
  }
  function instantiateInstantiableTypes(type, mapper) {
    if (type.flags & 465829888 /* Instantiable */) {
      return instantiateType(type, mapper);
    }
    if (type.flags & 1048576 /* Union */) {
      return getUnionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)), 0 /* None */);
    }
    if (type.flags & 2097152 /* Intersection */) {
      return getIntersectionType(map(type.types, (t) => instantiateInstantiableTypes(t, mapper)));
    }
    return type;
  }
  function getContextualType(node, contextFlags) {
    var _a;
    if (node.flags & 67108864 /* InWithStatement */) {
      return void 0;
    }
    const index = findContextualNode(
      node,
      /*includeCaches*/
      !contextFlags
    );
    if (index >= 0) {
      return contextualTypes[index];
    }
    const { parent } = node;
    switch (parent.kind) {
      case 260 /* VariableDeclaration */:
      case 169 /* Parameter */:
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
      case 208 /* BindingElement */:
        return getContextualTypeForInitializerExpression(node, contextFlags);
      case 219 /* ArrowFunction */:
      case 253 /* ReturnStatement */:
        return getContextualTypeForReturnExpression(node, contextFlags);
      case 229 /* YieldExpression */:
        return getContextualTypeForYieldOperand(parent, contextFlags);
      case 223 /* AwaitExpression */:
        return getContextualTypeForAwaitOperand(parent, contextFlags);
      case 213 /* CallExpression */:
      case 214 /* NewExpression */:
        return getContextualTypeForArgument(parent, node);
      case 170 /* Decorator */:
        return getContextualTypeForDecorator(parent);
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
        return isConstTypeReference(parent.type) ? getContextualType(parent, contextFlags) : getTypeFromTypeNode(parent.type);
      case 226 /* BinaryExpression */:
        return getContextualTypeForBinaryOperand(node, contextFlags);
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
        return getContextualTypeForObjectLiteralElement(parent, contextFlags);
      case 305 /* SpreadAssignment */:
        return getContextualType(parent.parent, contextFlags);
      case 209 /* ArrayLiteralExpression */: {
        const arrayLiteral = parent;
        const type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
        const elementIndex = indexOfNode(arrayLiteral.elements, node);
        const spreadIndices = (_a = getNodeLinks(arrayLiteral)).spreadIndices ?? (_a.spreadIndices = getSpreadIndices(arrayLiteral.elements));
        return getContextualTypeForElementExpression(type, elementIndex, arrayLiteral.elements.length, spreadIndices.first, spreadIndices.last);
      }
      case 227 /* ConditionalExpression */:
        return getContextualTypeForConditionalOperand(node, contextFlags);
      case 239 /* TemplateSpan */:
        Debug.assert(parent.parent.kind === 228 /* TemplateExpression */);
        return getContextualTypeForSubstitutionExpression(parent.parent, node);
      case 217 /* ParenthesizedExpression */: {
        if (isInJSFile(parent)) {
          if (isJSDocSatisfiesExpression(parent)) {
            return getTypeFromTypeNode(getJSDocSatisfiesExpressionType(parent));
          }
          const typeTag = getJSDocTypeTag(parent);
          if (typeTag && !isConstTypeReference(typeTag.typeExpression.type)) {
            return getTypeFromTypeNode(typeTag.typeExpression.type);
          }
        }
        return getContextualType(parent, contextFlags);
      }
      case 235 /* NonNullExpression */:
        return getContextualType(parent, contextFlags);
      case 238 /* SatisfiesExpression */:
        return getTypeFromTypeNode(parent.type);
      case 277 /* ExportAssignment */:
        return tryGetTypeFromEffectiveTypeNode(parent);
      case 294 /* JsxExpression */:
        return getContextualTypeForJsxExpression(parent, contextFlags);
      case 291 /* JsxAttribute */:
      case 293 /* JsxSpreadAttribute */:
        return getContextualTypeForJsxAttribute(parent, contextFlags);
      case 286 /* JsxOpeningElement */:
      case 285 /* JsxSelfClosingElement */:
        return getContextualJsxElementAttributesType(parent, contextFlags);
      case 301 /* ImportAttribute */:
        return getContextualImportAttributeType(parent);
    }
    return void 0;
  }
  function pushCachedContextualType(node) {
    pushContextualType(
      node,
      getContextualType(
        node,
        /*contextFlags*/
        void 0
      ),
      /*isCache*/
      true
    );
  }
  function pushContextualType(node, type, isCache) {
    contextualTypeNodes[contextualTypeCount] = node;
    contextualTypes[contextualTypeCount] = type;
    contextualIsCache[contextualTypeCount] = isCache;
    contextualTypeCount++;
  }
  function popContextualType() {
    contextualTypeCount--;
  }
  function findContextualNode(node, includeCaches) {
    for (let i = contextualTypeCount - 1; i >= 0; i--) {
      if (node === contextualTypeNodes[i] && (includeCaches || !contextualIsCache[i])) {
        return i;
      }
    }
    return -1;
  }
  function pushInferenceContext(node, inferenceContext) {
    inferenceContextNodes[inferenceContextCount] = node;
    inferenceContexts[inferenceContextCount] = inferenceContext;
    inferenceContextCount++;
  }
  function popInferenceContext() {
    inferenceContextCount--;
  }
  function getInferenceContext(node) {
    for (let i = inferenceContextCount - 1; i >= 0; i--) {
      if (isNodeDescendantOf(node, inferenceContextNodes[i])) {
        return inferenceContexts[i];
      }
    }
  }
  function getContextualImportAttributeType(node) {
    return getTypeOfPropertyOfContextualType(getGlobalImportAttributesType(
      /*reportErrors*/
      false
    ), getNameFromImportAttribute(node));
  }
  function getContextualJsxElementAttributesType(node, contextFlags) {
    if (isJsxOpeningElement(node) && contextFlags !== 4 /* Completions */) {
      const index = findContextualNode(
        node.parent,
        /*includeCaches*/
        !contextFlags
      );
      if (index >= 0) {
        return contextualTypes[index];
      }
    }
    return getContextualTypeForArgumentAtIndex(node, 0);
  }
  function getEffectiveFirstArgumentForJsxSignature(signature, node) {
    return isJsxOpeningFragment(node) || getJsxReferenceKind(node) !== 0 /* Component */ ? getJsxPropsTypeFromCallSignature(signature, node) : getJsxPropsTypeFromClassType(signature, node);
  }
  function getJsxPropsTypeFromCallSignature(sig, context) {
    let propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
    propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
    const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
    if (!isErrorType(intrinsicAttribs)) {
      propsType = intersectTypes(intrinsicAttribs, propsType);
    }
    return propsType;
  }
  function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
    if (sig.compositeSignatures) {
      const results = [];
      for (const signature of sig.compositeSignatures) {
        const instance = getReturnTypeOfSignature(signature);
        if (isTypeAny(instance)) {
          return instance;
        }
        const propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
        if (!propType) {
          return;
        }
        results.push(propType);
      }
      return getIntersectionType(results);
    }
    const instanceType = getReturnTypeOfSignature(sig);
    return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
  }
  function getStaticTypeOfReferencedJsxConstructor(context) {
    if (isJsxOpeningFragment(context)) return getJSXFragmentType(context);
    if (isJsxIntrinsicTagName(context.tagName)) {
      const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
      const fakeSignature = createSignatureForJSXIntrinsic(context, result);
      return getOrCreateTypeFromSignature(fakeSignature);
    }
    const tagType = checkExpressionCached(context.tagName);
    if (tagType.flags & 128 /* StringLiteral */) {
      const result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
      if (!result) {
        return errorType;
      }
      const fakeSignature = createSignatureForJSXIntrinsic(context, result);
      return getOrCreateTypeFromSignature(fakeSignature);
    }
    return tagType;
  }
  function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
    const managedSym = getJsxLibraryManagedAttributes(ns);
    if (managedSym) {
      const ctorType = getStaticTypeOfReferencedJsxConstructor(context);
      const result = instantiateAliasOrInterfaceWithDefaults(managedSym, isInJSFile(context), ctorType, attributesType);
      if (result) {
        return result;
      }
    }
    return attributesType;
  }
  function getJsxPropsTypeFromClassType(sig, context) {
    const ns = getJsxNamespaceAt(context);
    const forcedLookupLocation = getJsxElementPropertiesName(ns);
    let attributesType = forcedLookupLocation === void 0 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType) : forcedLookupLocation === "" ? getReturnTypeOfSignature(sig) : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
    if (!attributesType) {
      if (!!forcedLookupLocation && !!length(context.attributes.properties)) {
        error(context, Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, unescapeLeadingUnderscores(forcedLookupLocation));
      }
      return unknownType;
    }
    attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
    if (isTypeAny(attributesType)) {
      return attributesType;
    } else {
      let apparentAttributesType = attributesType;
      const intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
      if (!isErrorType(intrinsicClassAttribs)) {
        const typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
        const hostClassType = getReturnTypeOfSignature(sig);
        let libraryManagedAttributeType;
        if (typeParams) {
          const inferredArgs = fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), isInJSFile(context));
          libraryManagedAttributeType = instantiateType(intrinsicClassAttribs, createTypeMapper(typeParams, inferredArgs));
        } else libraryManagedAttributeType = intrinsicClassAttribs;
        apparentAttributesType = intersectTypes(libraryManagedAttributeType, apparentAttributesType);
      }
      const intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
      if (!isErrorType(intrinsicAttribs)) {
        apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
      }
      return apparentAttributesType;
    }
  }
  function getIntersectedSignatures(signatures) {
    return getStrictOptionValue(compilerOptions, "noImplicitAny") ? reduceLeft(
      signatures,
      (left, right) => left === right || !left ? left : compareTypeParametersIdentical(left.typeParameters, right.typeParameters) ? combineSignaturesOfIntersectionMembers(left, right) : void 0
    ) : void 0;
  }
  function combineIntersectionThisParam(left, right, mapper) {
    if (!left || !right) {
      return left || right;
    }
    const thisType = getUnionType([getTypeOfSymbol(left), instantiateType(getTypeOfSymbol(right), mapper)]);
    return createSymbolWithType(left, thisType);
  }
  function combineIntersectionParameters(left, right, mapper) {
    const leftCount = getParameterCount(left);
    const rightCount = getParameterCount(right);
    const longest = leftCount >= rightCount ? left : right;
    const shorter = longest === left ? right : left;
    const longestCount = longest === left ? leftCount : rightCount;
    const eitherHasEffectiveRest = hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right);
    const needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
    const params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
    for (let i = 0; i < longestCount; i++) {
      let longestParamType = tryGetTypeAtPosition(longest, i);
      if (longest === right) {
        longestParamType = instantiateType(longestParamType, mapper);
      }
      let shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
      if (shorter === right) {
        shorterParamType = instantiateType(shorterParamType, mapper);
      }
      const unionParamType = getUnionType([longestParamType, shorterParamType]);
      const isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === longestCount - 1;
      const isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
      const leftName = i >= leftCount ? void 0 : getParameterNameAtPosition(left, i);
      const rightName = i >= rightCount ? void 0 : getParameterNameAtPosition(right, i);
      const paramName = leftName === rightName ? leftName : !leftName ? rightName : !rightName ? leftName : void 0;
      const paramSymbol = createSymbol(
        1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0),
        paramName || `arg${i}`,
        isRestParam ? 32768 /* RestParameter */ : isOptional ? 16384 /* OptionalParameter */ : 0
      );
      paramSymbol.links.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
      params[i] = paramSymbol;
    }
    if (needsExtraRestElement) {
      const restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args", 32768 /* RestParameter */);
      restParamSymbol.links.type = createArrayType(getTypeAtPosition(shorter, longestCount));
      if (shorter === right) {
        restParamSymbol.links.type = instantiateType(restParamSymbol.links.type, mapper);
      }
      params[longestCount] = restParamSymbol;
    }
    return params;
  }
  function combineSignaturesOfIntersectionMembers(left, right) {
    const typeParams = left.typeParameters || right.typeParameters;
    let paramMapper;
    if (left.typeParameters && right.typeParameters) {
      paramMapper = createTypeMapper(right.typeParameters, left.typeParameters);
    }
    let flags = (left.flags | right.flags) & (167 /* PropagatingFlags */ & ~1 /* HasRestParameter */);
    const declaration = left.declaration;
    const params = combineIntersectionParameters(left, right, paramMapper);
    const lastParam = lastOrUndefined(params);
    if (lastParam && getCheckFlags(lastParam) & 32768 /* RestParameter */) {
      flags |= 1 /* HasRestParameter */;
    }
    const thisParam = combineIntersectionThisParam(left.thisParameter, right.thisParameter, paramMapper);
    const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
    const result = createSignature(
      declaration,
      typeParams,
      thisParam,
      params,
      /*resolvedReturnType*/
      void 0,
      /*resolvedTypePredicate*/
      void 0,
      minArgCount,
      flags
    );
    result.compositeKind = 2097152 /* Intersection */;
    result.compositeSignatures = concatenate(left.compositeKind === 2097152 /* Intersection */ && left.compositeSignatures || [left], [right]);
    if (paramMapper) {
      result.mapper = left.compositeKind === 2097152 /* Intersection */ && left.mapper && left.compositeSignatures ? combineTypeMappers(left.mapper, paramMapper) : paramMapper;
    }
    return result;
  }
  function getContextualCallSignature(type, node) {
    const signatures = getSignaturesOfType(type, 0 /* Call */);
    const applicableByArity = filter(signatures, (s) => !isAritySmaller(s, node));
    return applicableByArity.length === 1 ? applicableByArity[0] : getIntersectedSignatures(applicableByArity);
  }
  function isAritySmaller(signature, target) {
    let targetParameterCount = 0;
    for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
      const param = target.parameters[targetParameterCount];
      if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
        break;
      }
    }
    if (target.parameters.length && parameterIsThisKeyword(target.parameters[0])) {
      targetParameterCount--;
    }
    return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
  }
  function getContextualSignatureForFunctionLikeDeclaration(node) {
    return isFunctionExpressionOrArrowFunction(node) || isObjectLiteralMethod(node) ? getContextualSignature(node) : void 0;
  }
  function getContextualSignature(node) {
    Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node));
    const typeTagSignature = getSignatureOfTypeTag(node);
    if (typeTagSignature) {
      return typeTagSignature;
    }
    const type = getApparentTypeOfContextualType(node, 1 /* Signature */);
    if (!type) {
      return void 0;
    }
    if (!(type.flags & 1048576 /* Union */)) {
      return getContextualCallSignature(type, node);
    }
    let signatureList;
    const types = type.types;
    for (const current of types) {
      const signature = getContextualCallSignature(current, node);
      if (signature) {
        if (!signatureList) {
          signatureList = [signature];
        } else if (!compareSignaturesIdentical(
          signatureList[0],
          signature,
          /*partialMatch*/
          false,
          /*ignoreThisTypes*/
          true,
          /*ignoreReturnTypes*/
          true,
          compareTypesIdentical
        )) {
          return void 0;
        } else {
          signatureList.push(signature);
        }
      }
    }
    if (signatureList) {
      return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
    }
  }
  function checkGrammarRegularExpressionLiteral(node) {
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile) && !node.isUnterminated) {
      let lastError;
      scanner ?? (scanner = createScanner(
        99 /* ESNext */,
        /*skipTrivia*/
        true
      ));
      scanner.setScriptTarget(sourceFile.languageVersion);
      scanner.setLanguageVariant(sourceFile.languageVariant);
      scanner.setOnError((message, length2, arg0) => {
        const start = scanner.getTokenEnd();
        if (message.category === 3 /* Message */ && lastError && start === lastError.start && length2 === lastError.length) {
          const error2 = createDetachedDiagnostic(sourceFile.fileName, sourceFile.text, start, length2, message, arg0);
          addRelatedInfo(lastError, error2);
        } else if (!lastError || start !== lastError.start) {
          lastError = createFileDiagnostic(sourceFile, start, length2, message, arg0);
          diagnostics.add(lastError);
        }
      });
      scanner.setText(sourceFile.text, node.pos, node.end - node.pos);
      try {
        scanner.scan();
        Debug.assert(scanner.reScanSlashToken(
          /*reportErrors*/
          true
        ) === 14 /* RegularExpressionLiteral */, "Expected scanner to rescan RegularExpressionLiteral");
        return !!lastError;
      } finally {
        scanner.setText("");
        scanner.setOnError(
          /*onError*/
          void 0
        );
      }
    }
    return false;
  }
  function checkRegularExpressionLiteral(node) {
    const nodeLinks2 = getNodeLinks(node);
    if (!(nodeLinks2.flags & 1 /* TypeChecked */)) {
      nodeLinks2.flags |= 1 /* TypeChecked */;
      addLazyDiagnostic(() => checkGrammarRegularExpressionLiteral(node));
    }
    return globalRegExpType;
  }
  function checkSpreadExpression(node, checkMode) {
    if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) {
      checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
    }
    const arrayOrIterableType = checkExpression(node.expression, checkMode);
    return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
  }
  function checkSyntheticExpression(node) {
    return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type;
  }
  function hasDefaultValue(node) {
    return node.kind === 208 /* BindingElement */ && !!node.initializer || node.kind === 303 /* PropertyAssignment */ && hasDefaultValue(node.initializer) || node.kind === 304 /* ShorthandPropertyAssignment */ && !!node.objectAssignmentInitializer || node.kind === 226 /* BinaryExpression */ && node.operatorToken.kind === 64 /* EqualsToken */;
  }
  function isSpreadIntoCallOrNew(node) {
    const parent = walkUpParenthesizedExpressions(node.parent);
    return isSpreadElement(parent) && isCallOrNewExpression(parent.parent);
  }
  function checkArrayLiteral(node, checkMode, forceTuple) {
    const elements = node.elements;
    const elementCount = elements.length;
    const elementTypes = [];
    const elementFlags = [];
    pushCachedContextualType(node);
    const inDestructuringPattern = isAssignmentTarget(node);
    const inConstContext = isConstContext(node);
    const contextualType = getApparentTypeOfContextualType(
      node,
      /*contextFlags*/
      void 0
    );
    const inTupleContext = isSpreadIntoCallOrNew(node) || !!contextualType && someType(contextualType, (t) => isTupleLikeType(t) || isGenericMappedType(t) && !t.nameType && !!getHomomorphicTypeVariable(t.target || t));
    let hasOmittedExpression = false;
    for (let i = 0; i < elementCount; i++) {
      const e = elements[i];
      if (e.kind === 230 /* SpreadElement */) {
        if (languageVersion < LanguageFeatureMinimumTarget.SpreadElements) {
          checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 1024 /* SpreadArray */);
        }
        const spreadType = checkExpression(e.expression, checkMode, forceTuple);
        if (isArrayLikeType(spreadType)) {
          elementTypes.push(spreadType);
          elementFlags.push(8 /* Variadic */);
        } else if (inDestructuringPattern) {
          const restElementType = getIndexTypeOfType(spreadType, numberType) || getIteratedTypeOrElementType(
            65 /* Destructuring */,
            spreadType,
            undefinedType,
            /*errorNode*/
            void 0,
            /*checkAssignability*/
            false
          ) || unknownType;
          elementTypes.push(restElementType);
          elementFlags.push(4 /* Rest */);
        } else {
          elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
          elementFlags.push(4 /* Rest */);
        }
      } else if (exactOptionalPropertyTypes && e.kind === 232 /* OmittedExpression */) {
        hasOmittedExpression = true;
        elementTypes.push(undefinedOrMissingType);
        elementFlags.push(2 /* Optional */);
      } else {
        const type = checkExpressionForMutableLocation(e, checkMode, forceTuple);
        elementTypes.push(addOptionality(
          type,
          /*isProperty*/
          true,
          hasOmittedExpression
        ));
        elementFlags.push(hasOmittedExpression ? 2 /* Optional */ : 1 /* Required */);
        if (inTupleContext && checkMode && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(e)) {
          const inferenceContext = getInferenceContext(node);
          Debug.assert(inferenceContext);
          addIntraExpressionInferenceSite(inferenceContext, e, type);
        }
      }
    }
    popContextualType();
    if (inDestructuringPattern) {
      return createTupleType(elementTypes, elementFlags);
    }
    if (forceTuple || inConstContext || inTupleContext) {
      return createArrayLiteralType(createTupleType(
        elementTypes,
        elementFlags,
        /*readonly*/
        inConstContext && !(contextualType && someType(contextualType, isMutableArrayLikeType))
      ));
    }
    return createArrayLiteralType(createArrayType(
      elementTypes.length ? getUnionType(sameMap(elementTypes, (t, i) => elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t), 2 /* Subtype */) : strictNullChecks ? implicitNeverType : undefinedWideningType,
      inConstContext
    ));
  }
  function createArrayLiteralType(type) {
    if (!(getObjectFlags(type) & 4 /* Reference */)) {
      return type;
    }
    let literalType = type.literalType;
    if (!literalType) {
      literalType = type.literalType = cloneTypeReference(type);
      literalType.objectFlags |= 16384 /* ArrayLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
    }
    return literalType;
  }
  function isNumericName(name) {
    switch (name.kind) {
      case 167 /* ComputedPropertyName */:
        return isNumericComputedName(name);
      case 80 /* Identifier */:
        return isNumericLiteralName(name.escapedText);
      case 9 /* NumericLiteral */:
      case 11 /* StringLiteral */:
        return isNumericLiteralName(name.text);
      default:
        return false;
    }
  }
  function isNumericComputedName(name) {
    return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
  }
  function checkComputedPropertyName(node) {
    const links = getNodeLinks(node.expression);
    if (!links.resolvedType) {
      if ((isTypeLiteralNode(node.parent.parent) || isClassLike(node.parent.parent) || isInterfaceDeclaration(node.parent.parent)) && isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 103 /* InKeyword */ && node.parent.kind !== 177 /* GetAccessor */ && node.parent.kind !== 178 /* SetAccessor */) {
        return links.resolvedType = errorType;
      }
      links.resolvedType = checkExpression(node.expression);
      if (isPropertyDeclaration(node.parent) && !hasStaticModifier(node.parent) && isClassExpression(node.parent.parent)) {
        const container = getEnclosingBlockScopeContainer(node.parent.parent);
        const enclosingIterationStatement = getEnclosingIterationStatement(container);
        if (enclosingIterationStatement) {
          getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */;
          getNodeLinks(node).flags |= 32768 /* BlockScopedBindingInLoop */;
          getNodeLinks(node.parent.parent).flags |= 32768 /* BlockScopedBindingInLoop */;
        }
      }
      if (links.resolvedType.flags & 98304 /* Nullable */ || !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) && !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
        error(node, Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
      }
    }
    return links.resolvedType;
  }
  function isSymbolWithNumericName(symbol) {
    var _a;
    const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0];
    return isNumericLiteralName(symbol.escapedName) || firstDecl && isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name);
  }
  function isSymbolWithSymbolName(symbol) {
    var _a;
    const firstDecl = (_a = symbol.declarations) == null ? void 0 : _a[0];
    return isKnownSymbol(symbol) || firstDecl && isNamedDeclaration(firstDecl) && isComputedPropertyName(firstDecl.name) && isTypeAssignableToKind(checkComputedPropertyName(firstDecl.name), 4096 /* ESSymbol */);
  }
  function getObjectLiteralIndexInfo(isReadonly, offset, properties, keyType) {
    const propTypes = [];
    for (let i = offset; i < properties.length; i++) {
      const prop = properties[i];
      if (keyType === stringType && !isSymbolWithSymbolName(prop) || keyType === numberType && isSymbolWithNumericName(prop) || keyType === esSymbolType && isSymbolWithSymbolName(prop)) {
        propTypes.push(getTypeOfSymbol(properties[i]));
      }
    }
    const unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
    return createIndexInfo(keyType, unionType, isReadonly);
  }
  function getImmediateAliasedSymbol(symbol) {
    Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
    const links = getSymbolLinks(symbol);
    if (!links.immediateTarget) {
      const node = getDeclarationOfAliasSymbol(symbol);
      if (!node) return Debug.fail();
      links.immediateTarget = getTargetOfAliasDeclaration(
        node,
        /*dontRecursivelyResolve*/
        true
      );
    }
    return links.immediateTarget;
  }
  function checkObjectLiteral(node, checkMode = 0 /* Normal */) {
    const inDestructuringPattern = isAssignmentTarget(node);
    checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
    const allPropertiesTable = strictNullChecks ? createSymbolTable() : void 0;
    let propertiesTable = createSymbolTable();
    let propertiesArray = [];
    let spread = emptyObjectType;
    pushCachedContextualType(node);
    const contextualType = getApparentTypeOfContextualType(
      node,
      /*contextFlags*/
      void 0
    );
    const contextualTypeHasPattern = contextualType && contextualType.pattern && (contextualType.pattern.kind === 206 /* ObjectBindingPattern */ || contextualType.pattern.kind === 210 /* ObjectLiteralExpression */);
    const inConstContext = isConstContext(node);
    const checkFlags = inConstContext ? 8 /* Readonly */ : 0;
    const isInJavascript = isInJSFile(node) && !isInJsonFile(node);
    const enumTag = isInJavascript ? getJSDocEnumTag(node) : void 0;
    const isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
    let objectFlags = 8192 /* FreshLiteral */;
    let patternWithComputedProperties = false;
    let hasComputedStringProperty = false;
    let hasComputedNumberProperty = false;
    let hasComputedSymbolProperty = false;
    for (const elem of node.properties) {
      if (elem.name && isComputedPropertyName(elem.name)) {
        checkComputedPropertyName(elem.name);
      }
    }
    let offset = 0;
    for (const memberDecl of node.properties) {
      let member = getSymbolOfDeclaration(memberDecl);
      const computedNameType = memberDecl.name && memberDecl.name.kind === 167 /* ComputedPropertyName */ ? checkComputedPropertyName(memberDecl.name) : void 0;
      if (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 304 /* ShorthandPropertyAssignment */ || isObjectLiteralMethod(memberDecl)) {
        let type = memberDecl.kind === 303 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) : (
          // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring
          // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`.
          // we don't want to say "could not find 'a'".
          memberDecl.kind === 304 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) : checkObjectLiteralMethod(memberDecl, checkMode)
        );
        if (isInJavascript) {
          const jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
          if (jsDocType) {
            checkTypeAssignableTo(type, jsDocType, memberDecl);
            type = jsDocType;
          } else if (enumTag && enumTag.typeExpression) {
            checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
          }
        }
        objectFlags |= getObjectFlags(type) & 458752 /* PropagatingFlags */;
        const nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : void 0;
        const prop = nameType ? createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) : createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
        if (nameType) {
          prop.links.nameType = nameType;
        }
        if (inDestructuringPattern && hasDefaultValue(memberDecl)) {
          prop.flags |= 16777216 /* Optional */;
        } else if (contextualTypeHasPattern && !(getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
          const impliedProp = getPropertyOfType(contextualType, member.escapedName);
          if (impliedProp) {
            prop.flags |= impliedProp.flags & 16777216 /* Optional */;
          } else if (!getIndexInfoOfType(contextualType, stringType)) {
            error(memberDecl.name, Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
          }
        }
        prop.declarations = member.declarations;
        prop.parent = member.parent;
        if (member.valueDeclaration) {
          prop.valueDeclaration = member.valueDeclaration;
        }
        prop.links.type = type;
        prop.links.target = member;
        member = prop;
        allPropertiesTable == null ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
        if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && (memberDecl.kind === 303 /* PropertyAssignment */ || memberDecl.kind === 174 /* MethodDeclaration */) && isContextSensitive(memberDecl)) {
          const inferenceContext = getInferenceContext(node);
          Debug.assert(inferenceContext);
          const inferenceNode = memberDecl.kind === 303 /* PropertyAssignment */ ? memberDecl.initializer : memberDecl;
          addIntraExpressionInferenceSite(inferenceContext, inferenceNode, type);
        }
      } else if (memberDecl.kind === 305 /* SpreadAssignment */) {
        if (languageVersion < LanguageFeatureMinimumTarget.ObjectAssign) {
          checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
        }
        if (propertiesArray.length > 0) {
          spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
          propertiesArray = [];
          propertiesTable = createSymbolTable();
          hasComputedStringProperty = false;
          hasComputedNumberProperty = false;
          hasComputedSymbolProperty = false;
        }
        const type = getReducedType(checkExpression(memberDecl.expression, checkMode & 2 /* Inferential */));
        if (isValidSpreadType(type)) {
          const mergedType = tryMergeUnionOfObjectTypeAndEmptyObject(type, inConstContext);
          if (allPropertiesTable) {
            checkSpreadPropOverrides(mergedType, allPropertiesTable, memberDecl);
          }
          offset = propertiesArray.length;
          if (isErrorType(spread)) {
            continue;
          }
          spread = getSpreadType(spread, mergedType, node.symbol, objectFlags, inConstContext);
        } else {
          error(memberDecl, Diagnostics.Spread_types_may_only_be_created_from_object_types);
          spread = errorType;
        }
        continue;
      } else {
        Debug.assert(memberDecl.kind === 177 /* GetAccessor */ || memberDecl.kind === 178 /* SetAccessor */);
        checkNodeDeferred(memberDecl);
      }
      if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
        if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
          if (isTypeAssignableTo(computedNameType, numberType)) {
            hasComputedNumberProperty = true;
          } else if (isTypeAssignableTo(computedNameType, esSymbolType)) {
            hasComputedSymbolProperty = true;
          } else {
            hasComputedStringProperty = true;
          }
          if (inDestructuringPattern) {
            patternWithComputedProperties = true;
          }
        }
      } else {
        propertiesTable.set(member.escapedName, member);
      }
      propertiesArray.push(member);
    }
    popContextualType();
    if (isErrorType(spread)) {
      return errorType;
    }
    if (spread !== emptyObjectType) {
      if (propertiesArray.length > 0) {
        spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
        propertiesArray = [];
        propertiesTable = createSymbolTable();
        hasComputedStringProperty = false;
        hasComputedNumberProperty = false;
      }
      return mapType(spread, (t) => t === emptyObjectType ? createObjectLiteralType() : t);
    }
    return createObjectLiteralType();
    function createObjectLiteralType() {
      const indexInfos = [];
      const isReadonly = isConstContext(node);
      if (hasComputedStringProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, stringType));
      if (hasComputedNumberProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, numberType));
      if (hasComputedSymbolProperty) indexInfos.push(getObjectLiteralIndexInfo(isReadonly, offset, propertiesArray, esSymbolType));
      const result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, indexInfos);
      result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
      if (isJSObjectLiteral) {
        result.objectFlags |= 4096 /* JSLiteral */;
      }
      if (patternWithComputedProperties) {
        result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
      }
      if (inDestructuringPattern) {
        result.pattern = node;
      }
      return result;
    }
  }
  function isValidSpreadType(type) {
    const t = removeDefinitelyFalsyTypes(mapType(type, getBaseConstraintOrType));
    return !!(t.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) || t.flags & 3145728 /* UnionOrIntersection */ && every(t.types, isValidSpreadType));
  }
  function checkJsxSelfClosingElementDeferred(node) {
    checkJsxOpeningLikeElementOrOpeningFragment(node);
  }
  function checkJsxSelfClosingElement(node, _checkMode) {
    checkNodeDeferred(node);
    return getJsxElementTypeAt(node) || anyType;
  }
  function checkJsxElementDeferred(node) {
    checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
    if (isJsxIntrinsicTagName(node.closingElement.tagName)) {
      getIntrinsicTagSymbol(node.closingElement);
    } else {
      checkExpression(node.closingElement.tagName);
    }
    checkJsxChildren(node);
  }
  function checkJsxElement(node, _checkMode) {
    checkNodeDeferred(node);
    return getJsxElementTypeAt(node) || anyType;
  }
  function checkJsxFragment(node) {
    checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
    const nodeSourceFile = getSourceFileOfNode(node);
    if (getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx")) && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) {
      error(
        node,
        compilerOptions.jsxFactory ? Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option : Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments
      );
    }
    checkJsxChildren(node);
    const jsxElementType = getJsxElementTypeAt(node);
    return isErrorType(jsxElementType) ? anyType : jsxElementType;
  }
  function isHyphenatedJsxName(name) {
    return name.includes("-");
  }
  function isJsxIntrinsicTagName(tagName) {
    return isIdentifier(tagName) && isIntrinsicJsxName(tagName.escapedText) || isJsxNamespacedName(tagName);
  }
  function checkJsxAttribute(node, checkMode) {
    return node.initializer ? checkExpressionForMutableLocation(node.initializer, checkMode) : trueType;
  }
  function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode = 0 /* Normal */) {
    const allAttributesTable = strictNullChecks ? createSymbolTable() : void 0;
    let attributesTable = createSymbolTable();
    let spread = emptyJsxObjectType;
    let hasSpreadAnyType = false;
    let typeToIntersect;
    let explicitlySpecifyChildrenAttribute = false;
    let objectFlags = 2048 /* JsxAttributes */;
    const jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
    const isJsxOpenFragment = isJsxOpeningFragment(openingLikeElement);
    let attributesSymbol;
    let attributeParent = openingLikeElement;
    if (!isJsxOpenFragment) {
      const attributes = openingLikeElement.attributes;
      attributesSymbol = attributes.symbol;
      attributeParent = attributes;
      const contextualType = getContextualType(attributes, 0 /* None */);
      for (const attributeDecl of attributes.properties) {
        const member = attributeDecl.symbol;
        if (isJsxAttribute(attributeDecl)) {
          const exprType = checkJsxAttribute(attributeDecl, checkMode);
          objectFlags |= getObjectFlags(exprType) & 458752 /* PropagatingFlags */;
          const attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName);
          attributeSymbol.declarations = member.declarations;
          attributeSymbol.parent = member.parent;
          if (member.valueDeclaration) {
            attributeSymbol.valueDeclaration = member.valueDeclaration;
          }
          attributeSymbol.links.type = exprType;
          attributeSymbol.links.target = member;
          attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
          allAttributesTable == null ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
          if (getEscapedTextOfJsxAttributeName(attributeDecl.name) === jsxChildrenPropertyName) {
            explicitlySpecifyChildrenAttribute = true;
          }
          if (contextualType) {
            const prop = getPropertyOfType(contextualType, member.escapedName);
            if (prop && prop.declarations && isDeprecatedSymbol(prop) && isIdentifier(attributeDecl.name)) {
              addDeprecatedSuggestion(attributeDecl.name, prop.declarations, attributeDecl.name.escapedText);
            }
          }
          if (contextualType && checkMode & 2 /* Inferential */ && !(checkMode & 4 /* SkipContextSensitive */) && isContextSensitive(attributeDecl)) {
            const inferenceContext = getInferenceContext(attributes);
            Debug.assert(inferenceContext);
            const inferenceNode = attributeDecl.initializer.expression;
            addIntraExpressionInferenceSite(inferenceContext, inferenceNode, exprType);
          }
        } else {
          Debug.assert(attributeDecl.kind === 293 /* JsxSpreadAttribute */);
          if (attributesTable.size > 0) {
            spread = getSpreadType(
              spread,
              createJsxAttributesTypeHelper(),
              attributes.symbol,
              objectFlags,
              /*readonly*/
              false
            );
            attributesTable = createSymbolTable();
          }
          const exprType = getReducedType(checkExpression(attributeDecl.expression, checkMode & 2 /* Inferential */));
          if (isTypeAny(exprType)) {
            hasSpreadAnyType = true;
          }
          if (isValidSpreadType(exprType)) {
            spread = getSpreadType(
              spread,
              exprType,
              attributes.symbol,
              objectFlags,
              /*readonly*/
              false
            );
            if (allAttributesTable) {
              checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
            }
          } else {
            error(attributeDecl.expression, Diagnostics.Spread_types_may_only_be_created_from_object_types);
            typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
          }
        }
      }
      if (!hasSpreadAnyType) {
        if (attributesTable.size > 0) {
          spread = getSpreadType(
            spread,
            createJsxAttributesTypeHelper(),
            attributes.symbol,
            objectFlags,
            /*readonly*/
            false
          );
        }
      }
    }
    const parent = openingLikeElement.parent;
    if ((isJsxElement(parent) && parent.openingElement === openingLikeElement || isJsxFragment(parent) && parent.openingFragment === openingLikeElement) && getSemanticJsxChildren(parent.children).length > 0) {
      const childrenTypes = checkJsxChildren(parent, checkMode);
      if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
        if (explicitlySpecifyChildrenAttribute) {
          error(attributeParent, Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, unescapeLeadingUnderscores(jsxChildrenPropertyName));
        }
        const contextualType = isJsxOpeningElement(openingLikeElement) ? getApparentTypeOfContextualType(
          openingLikeElement.attributes,
          /*contextFlags*/
          void 0
        ) : void 0;
        const childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
        const childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName);
        childrenPropSymbol.links.type = childrenTypes.length === 1 ? childrenTypes[0] : childrenContextualType && someType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) : createArrayType(getUnionType(childrenTypes));
        childrenPropSymbol.valueDeclaration = factory.createPropertySignature(
          /*modifiers*/
          void 0,
          unescapeLeadingUnderscores(jsxChildrenPropertyName),
          /*questionToken*/
          void 0,
          /*type*/
          void 0
        );
        setParent(childrenPropSymbol.valueDeclaration, attributeParent);
        childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
        const childPropMap = createSymbolTable();
        childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
        spread = getSpreadType(
          spread,
          createAnonymousType(attributesSymbol, childPropMap, emptyArray, emptyArray, emptyArray),
          attributesSymbol,
          objectFlags,
          /*readonly*/
          false
        );
      }
    }
    if (hasSpreadAnyType) {
      return anyType;
    }
    if (typeToIntersect && spread !== emptyJsxObjectType) {
      return getIntersectionType([typeToIntersect, spread]);
    }
    return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesTypeHelper() : spread);
    function createJsxAttributesTypeHelper() {
      objectFlags |= 8192 /* FreshLiteral */;
      return createJsxAttributesType(objectFlags, attributesSymbol, attributesTable);
    }
  }
  function createJsxAttributesType(objectFlags, attributesSymbol, attributesTable) {
    const result = createAnonymousType(attributesSymbol, attributesTable, emptyArray, emptyArray, emptyArray);
    result.objectFlags |= objectFlags | 8192 /* FreshLiteral */ | 128 /* ObjectLiteral */ | 131072 /* ContainsObjectOrArrayLiteral */;
    return result;
  }
  function checkJsxChildren(node, checkMode) {
    const childrenTypes = [];
    for (const child of node.children) {
      if (child.kind === 12 /* JsxText */) {
        if (!child.containsOnlyTriviaWhiteSpaces) {
          childrenTypes.push(stringType);
        }
      } else if (child.kind === 294 /* JsxExpression */ && !child.expression) {
        continue;
      } else {
        childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
      }
    }
    return childrenTypes;
  }
  function checkSpreadPropOverrides(type, props, spread) {
    for (const right of getPropertiesOfType(type)) {
      if (!(right.flags & 16777216 /* Optional */)) {
        const left = props.get(right.escapedName);
        if (left) {
          const diagnostic = error(left.valueDeclaration, Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, unescapeLeadingUnderscores(left.escapedName));
          addRelatedInfo(diagnostic, createDiagnosticForNode(spread, Diagnostics.This_spread_always_overwrites_this_property));
        }
      }
    }
  }
  function checkJsxAttributes(node, checkMode) {
    return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
  }
  function getJsxType(name, location) {
    const namespace = getJsxNamespaceAt(location);
    const exports2 = namespace && getExportsOfSymbol(namespace);
    const typeSymbol = exports2 && getSymbol(exports2, name, 788968 /* Type */);
    return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
  }
  function getIntrinsicTagSymbol(node) {
    const links = getNodeLinks(node);
    if (!links.resolvedSymbol) {
      const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
      if (!isErrorType(intrinsicElementsType)) {
        if (!isIdentifier(node.tagName) && !isJsxNamespacedName(node.tagName)) return Debug.fail();
        const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText;
        const intrinsicProp = getPropertyOfType(intrinsicElementsType, propName);
        if (intrinsicProp) {
          links.jsxFlags |= 1 /* IntrinsicNamedElement */;
          return links.resolvedSymbol = intrinsicProp;
        }
        const indexSymbol = getApplicableIndexSymbol(intrinsicElementsType, getStringLiteralType(unescapeLeadingUnderscores(propName)));
        if (indexSymbol) {
          links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
          return links.resolvedSymbol = indexSymbol;
        }
        if (getTypeOfPropertyOrIndexSignatureOfType(intrinsicElementsType, propName)) {
          links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
          return links.resolvedSymbol = intrinsicElementsType.symbol;
        }
        error(node, Diagnostics.Property_0_does_not_exist_on_type_1, intrinsicTagNameToString(node.tagName), "JSX." + JsxNames.IntrinsicElements);
        return links.resolvedSymbol = unknownSymbol;
      } else {
        if (noImplicitAny) {
          error(node, Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
        }
        return links.resolvedSymbol = unknownSymbol;
      }
    }
    return links.resolvedSymbol;
  }
  function getJsxNamespaceContainerForImplicitImport(location) {
    const file = location && getSourceFileOfNode(location);
    const links = file && getNodeLinks(file);
    if (links && links.jsxImplicitImportContainer === false) {
      return void 0;
    }
    if (links && links.jsxImplicitImportContainer) {
      return links.jsxImplicitImportContainer;
    }
    const runtimeImportSpecifier = getJSXRuntimeImport(getJSXImplicitImportBase(compilerOptions, file), compilerOptions);
    if (!runtimeImportSpecifier) {
      return void 0;
    }
    const isClassic = getEmitModuleResolutionKind(compilerOptions) === 1 /* Classic */;
    const errorMessage = isClassic ? Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_nodenext_or_to_add_aliases_to_the_paths_option : Diagnostics.This_JSX_tag_requires_the_module_path_0_to_exist_but_none_could_be_found_Make_sure_you_have_types_for_the_appropriate_package_installed;
    const specifier = getJSXRuntimeImportSpecifier(file, runtimeImportSpecifier);
    const mod = resolveExternalModule(specifier || location, runtimeImportSpecifier, errorMessage, location);
    const result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : void 0;
    if (links) {
      links.jsxImplicitImportContainer = result || false;
    }
    return result;
  }
  function getJsxNamespaceAt(location) {
    const links = location && getNodeLinks(location);
    if (links && links.jsxNamespace) {
      return links.jsxNamespace;
    }
    if (!links || links.jsxNamespace !== false) {
      let resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location);
      if (!resolvedNamespace || resolvedNamespace === unknownSymbol) {
        const namespaceName = getJsxNamespace(location);
        resolvedNamespace = resolveName(
          location,
          namespaceName,
          1920 /* Namespace */,
          /*nameNotFoundMessage*/
          void 0,
          /*isUse*/
          false
        );
      }
      if (resolvedNamespace) {
        const candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
        if (candidate && candidate !== unknownSymbol) {
          if (links) {
            links.jsxNamespace = candidate;
          }
          return candidate;
        }
      }
      if (links) {
        links.jsxNamespace = false;
      }
    }
    const s = resolveSymbol(getGlobalSymbol(
      JsxNames.JSX,
      1920 /* Namespace */,
      /*diagnostic*/
      void 0
    ));
    if (s === unknownSymbol) {
      return void 0;
    }
    return s;
  }
  function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
    const jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
    const jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
    const propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
    if (propertiesOfJsxElementAttribPropInterface) {
      if (propertiesOfJsxElementAttribPropInterface.length === 0) {
        return "";
      } else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
        return propertiesOfJsxElementAttribPropInterface[0].escapedName;
      } else if (propertiesOfJsxElementAttribPropInterface.length > 1 && jsxElementAttribPropInterfaceSym.declarations) {
        error(jsxElementAttribPropInterfaceSym.declarations[0], Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, unescapeLeadingUnderscores(nameOfAttribPropContainer));
      }
    }
    return void 0;
  }
  function getJsxLibraryManagedAttributes(jsxNamespace) {
    return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
  }
  function getJsxElementTypeSymbol(jsxNamespace) {
    return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.ElementType, 788968 /* Type */);
  }
  function getJsxElementPropertiesName(jsxNamespace) {
    return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
  }
  function getJsxElementChildrenPropertyName(jsxNamespace) {
    return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
  }
  function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
    if (elementType.flags & 4 /* String */) {
      return [anySignature];
    } else if (elementType.flags & 128 /* StringLiteral */) {
      const intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
      if (!intrinsicType) {
        error(caller, Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
        return emptyArray;
      } else {
        const fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
        return [fakeSignature];
      }
    }
    const apparentElemType = getApparentType(elementType);
    let signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
    if (signatures.length === 0) {
      signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
    }
    if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
      signatures = getUnionSignatures(map(apparentElemType.types, (t) => getUninstantiatedJsxSignaturesOfType(t, caller)));
    }
    return signatures;
  }
  function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
    const intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
    if (!isErrorType(intrinsicElementsType)) {
      const stringLiteralTypeName = type.value;
      const intrinsicProp = getPropertyOfType(intrinsicElementsType, escapeLeadingUnderscores(stringLiteralTypeName));
      if (intrinsicProp) {
        return getTypeOfSymbol(intrinsicProp);
      }
      const indexSignatureType = getIndexTypeOfType(intrinsicElementsType, stringType);
      if (indexSignatureType) {
        return indexSignatureType;
      }
      return void 0;
    }
    return anyType;
  }
  function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
    if (refKind === 1 /* Function */) {
      const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
      if (sfcReturnConstraint) {
        checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
      }
    } else if (refKind === 0 /* Component */) {
      const classConstraint = getJsxElementClassTypeAt(openingLikeElement);
      if (classConstraint) {
        checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
      }
    } else {
      const sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
      const classConstraint = getJsxElementClassTypeAt(openingLikeElement);
      if (!sfcReturnConstraint || !classConstraint) {
        return;
      }
      const combined = getUnionType([sfcReturnConstraint, classConstraint]);
      checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
    }
    function generateInitialErrorChain() {
      const componentName = getTextOfNode(openingLikeElement.tagName);
      return chainDiagnosticMessages(
        /*details*/
        void 0,
        Diagnostics._0_cannot_be_used_as_a_JSX_component,
        componentName
      );
    }
  }
  function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
    var _a;
    Debug.assert(isJsxIntrinsicTagName(node.tagName));
    const links = getNodeLinks(node);
    if (!links.resolvedJsxElementAttributesType) {
      const symbol = getIntrinsicTagSymbol(node);
      if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
        return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol) || errorType;
      } else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
        const propName = isJsxNamespacedName(node.tagName) ? getEscapedTextOfJsxNamespacedName(node.tagName) : node.tagName.escapedText;
        return links.resolvedJsxElementAttributesType = ((_a = getApplicableIndexInfoForName(getJsxType(JsxNames.IntrinsicElements, node), propName)) == null ? void 0 : _a.type) || errorType;
      } else {
        return links.resolvedJsxElementAttributesType = errorType;
      }
    }
    return links.resolvedJsxElementAttributesType;
  }
  function getJsxElementClassTypeAt(location) {
    const type = getJsxType(JsxNames.ElementClass, location);
    if (isErrorType(type)) return void 0;
    return type;
  }
  function getJsxElementTypeAt(location) {
    return getJsxType(JsxNames.Element, location);
  }
  function getJsxStatelessElementTypeAt(location) {
    const jsxElementType = getJsxElementTypeAt(location);
    if (jsxElementType) {
      return getUnionType([jsxElementType, nullType]);
    }
  }
  function getJsxElementTypeTypeAt(location) {
    const ns = getJsxNamespaceAt(location);
    if (!ns) return void 0;
    const sym = getJsxElementTypeSymbol(ns);
    if (!sym) return void 0;
    const type = instantiateAliasOrInterfaceWithDefaults(sym, isInJSFile(location));
    if (!type || isErrorType(type)) return void 0;
    return type;
  }
  function instantiateAliasOrInterfaceWithDefaults(managedSym, inJs, ...typeArguments) {
    const declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
    if (managedSym.flags & 524288 /* TypeAlias */) {
      const params = getSymbolLinks(managedSym).typeParameters;
      if (length(params) >= typeArguments.length) {
        const args = fillMissingTypeArguments(typeArguments, params, typeArguments.length, inJs);
        return length(args) === 0 ? declaredManagedType : getTypeAliasInstantiation(managedSym, args);
      }
    }
    if (length(declaredManagedType.typeParameters) >= typeArguments.length) {
      const args = fillMissingTypeArguments(typeArguments, declaredManagedType.typeParameters, typeArguments.length, inJs);
      return createTypeReference(declaredManagedType, args);
    }
    return void 0;
  }
  function getJsxIntrinsicTagNamesAt(location) {
    const intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
    return intrinsics ? getPropertiesOfType(intrinsics) : emptyArray;
  }
  function checkJsxPreconditions(errorNode) {
    if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
      error(errorNode, Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
    }
    if (getJsxElementTypeAt(errorNode) === void 0) {
      if (noImplicitAny) {
        error(errorNode, Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
      }
    }
  }
  function checkJsxOpeningLikeElementOrOpeningFragment(node) {
    const isNodeOpeningLikeElement = isJsxOpeningLikeElement(node);
    if (isNodeOpeningLikeElement) {
      checkGrammarJsxElement(node);
    }
    checkJsxPreconditions(node);
    markJsxAliasReferenced(node);
    const sig = getResolvedSignature(node);
    checkDeprecatedSignature(sig, node);
    if (isNodeOpeningLikeElement) {
      const jsxOpeningLikeNode = node;
      const elementTypeConstraint = getJsxElementTypeTypeAt(jsxOpeningLikeNode);
      if (elementTypeConstraint !== void 0) {
        const tagName = jsxOpeningLikeNode.tagName;
        const tagType = isJsxIntrinsicTagName(tagName) ? getStringLiteralType(intrinsicTagNameToString(tagName)) : checkExpression(tagName);
        checkTypeRelatedTo(tagType, elementTypeConstraint, assignableRelation, tagName, Diagnostics.Its_type_0_is_not_a_valid_JSX_element_type, () => {
          const componentName = getTextOfNode(tagName);
          return chainDiagnosticMessages(
            /*details*/
            void 0,
            Diagnostics._0_cannot_be_used_as_a_JSX_component,
            componentName
          );
        });
      } else {
        checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
      }
    }
  }
  function isKnownProperty(targetType, name, isComparingJsxAttributes) {
    if (targetType.flags & 524288 /* Object */) {
      if (getPropertyOfObjectType(targetType, name) || getApplicableIndexInfoForName(targetType, name) || isLateBoundName(name) && getIndexInfoOfType(targetType, stringType) || isComparingJsxAttributes && isHyphenatedJsxName(name)) {
        return true;
      }
    }
    if (targetType.flags & 33554432 /* Substitution */) {
      return isKnownProperty(targetType.baseType, name, isComparingJsxAttributes);
    }
    if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
      for (const t of targetType.types) {
        if (isKnownProperty(t, name, isComparingJsxAttributes)) {
          return true;
        }
      }
    }
    return false;
  }
  function isExcessPropertyCheckTarget(type) {
    return !!(type.flags & 524288 /* Object */ && !(getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) || type.flags & 67108864 /* NonPrimitive */ || type.flags & 33554432 /* Substitution */ && isExcessPropertyCheckTarget(type.baseType) || type.flags & 1048576 /* Union */ && some(type.types, isExcessPropertyCheckTarget) || type.flags & 2097152 /* Intersection */ && every(type.types, isExcessPropertyCheckTarget));
  }
  function checkJsxExpression(node, checkMode) {
    checkGrammarJsxExpression(node);
    if (node.expression) {
      const type = checkExpression(node.expression, checkMode);
      if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
        error(node, Diagnostics.JSX_spread_child_must_be_an_array_type);
      }
      return type;
    } else {
      return errorType;
    }
  }
  function getDeclarationNodeFlagsFromSymbol(s) {
    return s.valueDeclaration ? getCombinedNodeFlagsCached(s.valueDeclaration) : 0;
  }
  function isPrototypeProperty(symbol) {
    if (symbol.flags & 8192 /* Method */ || getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
      return true;
    }
    if (isInJSFile(symbol.valueDeclaration)) {
      const parent = symbol.valueDeclaration.parent;
      return parent && isBinaryExpression(parent) && getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
    }
  }
  function checkPropertyAccessibility(node, isSuper, writing, type, prop, reportError = true) {
    const errorNode = !reportError ? void 0 : node.kind === 166 /* QualifiedName */ ? node.right : node.kind === 205 /* ImportType */ ? node : node.kind === 208 /* BindingElement */ && node.propertyName ? node.propertyName : node.name;
    return checkPropertyAccessibilityAtLocation(node, isSuper, writing, type, prop, errorNode);
  }
  function checkPropertyAccessibilityAtLocation(location, isSuper, writing, containingType, prop, errorNode) {
    var _a;
    const flags = getDeclarationModifierFlagsFromSymbol(prop, writing);
    if (isSuper) {
      if (languageVersion < 2 /* ES2015 */) {
        if (symbolHasNonMethodDeclaration(prop)) {
          if (errorNode) {
            error(errorNode, Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
          }
          return false;
        }
      }
      if (flags & 64 /* Abstract */) {
        if (errorNode) {
          error(errorNode, Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
        }
        return false;
      }
      if (!(flags & 256 /* Static */) && ((_a = prop.declarations) == null ? void 0 : _a.some(isClassInstanceProperty))) {
        if (errorNode) {
          error(errorNode, Diagnostics.Class_field_0_defined_by_the_parent_class_is_not_accessible_in_the_child_class_via_super, symbolToString(prop));
        }
        return false;
      }
    }
    if (flags & 64 /* Abstract */ && symbolHasNonMethodDeclaration(prop) && (isThisProperty(location) || isThisInitializedObjectBindingExpression(location) || isObjectBindingPattern(location.parent) && isThisInitializedDeclaration(location.parent.parent))) {
      const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
      if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(location)) {
        if (errorNode) {
          error(errorNode, Diagnostics.Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor, symbolToString(prop), getTextOfIdentifierOrLiteral(declaringClassDeclaration.name));
        }
        return false;
      }
    }
    if (!(flags & 6 /* NonPublicAccessibilityModifier */)) {
      return true;
    }
    if (flags & 2 /* Private */) {
      const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
      if (!isNodeWithinClass(location, declaringClassDeclaration)) {
        if (errorNode) {
          error(errorNode, Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
        }
        return false;
      }
      return true;
    }
    if (isSuper) {
      return true;
    }
    let enclosingClass = forEachEnclosingClass(location, (enclosingDeclaration) => {
      const enclosingClass2 = getDeclaredTypeOfSymbol(getSymbolOfDeclaration(enclosingDeclaration));
      return isClassDerivedFromDeclaringClasses(enclosingClass2, prop, writing);
    });
    if (!enclosingClass) {
      enclosingClass = getEnclosingClassFromThisParameter(location);
      enclosingClass = enclosingClass && isClassDerivedFromDeclaringClasses(enclosingClass, prop, writing);
      if (flags & 256 /* Static */ || !enclosingClass) {
        if (errorNode) {
          error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || containingType));
        }
        return false;
      }
    }
    if (flags & 256 /* Static */) {
      return true;
    }
    if (containingType.flags & 262144 /* TypeParameter */) {
      containingType = containingType.isThisType ? getConstraintOfTypeParameter(containingType) : getBaseConstraintOfType(containingType);
    }
    if (!containingType || !hasBaseType(containingType, enclosingClass)) {
      if (errorNode) {
        error(errorNode, Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1_This_is_an_instance_of_class_2, symbolToString(prop), typeToString(enclosingClass), typeToString(containingType));
      }
      return false;
    }
    return true;
  }
  function getEnclosingClassFromThisParameter(node) {
    const thisParameter = getThisParameterFromNodeContext(node);
    let thisType = (thisParameter == null ? void 0 : thisParameter.type) && getTypeFromTypeNode(thisParameter.type);
    if (thisType) {
      if (thisType.flags & 262144 /* TypeParameter */) {
        thisType = getConstraintOfTypeParameter(thisType);
      }
    } else {
      const thisContainer = getThisContainer(
        node,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (isFunctionLike(thisContainer)) {
        thisType = getContextualThisParameterType(thisContainer);
      }
    }
    if (thisType && getObjectFlags(thisType) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
      return getTargetType(thisType);
    }
    return void 0;
  }
  function getThisParameterFromNodeContext(node) {
    const thisContainer = getThisContainer(
      node,
      /*includeArrowFunctions*/
      false,
      /*includeClassComputedPropertyName*/
      false
    );
    return thisContainer && isFunctionLike(thisContainer) ? getThisParameter(thisContainer) : void 0;
  }
  function symbolHasNonMethodDeclaration(symbol) {
    return !!forEachProperty(symbol, (prop) => !(prop.flags & 8192 /* Method */));
  }
  function checkNonNullExpression(node) {
    return checkNonNullType(checkExpression(node), node);
  }
  function isNullableType(type) {
    return hasTypeFacts(type, 50331648 /* IsUndefinedOrNull */);
  }
  function getNonNullableTypeIfNeeded(type) {
    return isNullableType(type) ? getNonNullableType(type) : type;
  }
  function reportObjectPossiblyNullOrUndefinedError(node, facts) {
    const nodeText = isEntityNameExpression(node) ? entityNameToString(node) : void 0;
    if (node.kind === 106 /* NullKeyword */) {
      error(node, Diagnostics.The_value_0_cannot_be_used_here, "null");
      return;
    }
    if (nodeText !== void 0 && nodeText.length < 100) {
      if (isIdentifier(node) && nodeText === "undefined") {
        error(node, Diagnostics.The_value_0_cannot_be_used_here, "undefined");
        return;
      }
      error(
        node,
        facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics._0_is_possibly_null_or_undefined : Diagnostics._0_is_possibly_undefined : Diagnostics._0_is_possibly_null,
        nodeText
      );
    } else {
      error(
        node,
        facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Object_is_possibly_null_or_undefined : Diagnostics.Object_is_possibly_undefined : Diagnostics.Object_is_possibly_null
      );
    }
  }
  function reportCannotInvokePossiblyNullOrUndefinedError(node, facts) {
    error(
      node,
      facts & 16777216 /* IsUndefined */ ? facts & 33554432 /* IsNull */ ? Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : Diagnostics.Cannot_invoke_an_object_which_is_possibly_null
    );
  }
  function checkNonNullTypeWithReporter(type, node, reportError) {
    if (strictNullChecks && type.flags & 2 /* Unknown */) {
      if (isEntityNameExpression(node)) {
        const nodeText = entityNameToString(node);
        if (nodeText.length < 100) {
          error(node, Diagnostics._0_is_of_type_unknown, nodeText);
          return errorType;
        }
      }
      error(node, Diagnostics.Object_is_of_type_unknown);
      return errorType;
    }
    const facts = getTypeFacts(type, 50331648 /* IsUndefinedOrNull */);
    if (facts & 50331648 /* IsUndefinedOrNull */) {
      reportError(node, facts);
      const t = getNonNullableType(type);
      return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
    }
    return type;
  }
  function checkNonNullType(type, node) {
    return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
  }
  function checkNonNullNonVoidType(type, node) {
    const nonNullType = checkNonNullType(type, node);
    if (nonNullType.flags & 16384 /* Void */) {
      if (isEntityNameExpression(node)) {
        const nodeText = entityNameToString(node);
        if (isIdentifier(node) && nodeText === "undefined") {
          error(node, Diagnostics.The_value_0_cannot_be_used_here, nodeText);
          return nonNullType;
        }
        if (nodeText.length < 100) {
          error(node, Diagnostics._0_is_possibly_undefined, nodeText);
          return nonNullType;
        }
      }
      error(node, Diagnostics.Object_is_possibly_undefined);
    }
    return nonNullType;
  }
  function checkPropertyAccessExpression(node, checkMode, writeOnly) {
    return node.flags & 64 /* OptionalChain */ ? checkPropertyAccessChain(node, checkMode) : checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name, checkMode, writeOnly);
  }
  function checkPropertyAccessChain(node, checkMode) {
    const leftType = checkExpression(node.expression);
    const nonOptionalType = getOptionalExpressionType(leftType, node.expression);
    return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name, checkMode), node, nonOptionalType !== leftType);
  }
  function checkQualifiedName(node, checkMode) {
    const leftType = isPartOfTypeQuery(node) && isThisIdentifier(node.left) ? checkNonNullType(checkThisExpression(node.left), node.left) : checkNonNullExpression(node.left);
    return checkPropertyAccessExpressionOrQualifiedName(node, node.left, leftType, node.right, checkMode);
  }
  function isMethodAccessForCall(node) {
    while (node.parent.kind === 217 /* ParenthesizedExpression */) {
      node = node.parent;
    }
    return isCallOrNewExpression(node.parent) && node.parent.expression === node;
  }
  function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
    for (let containingClass = getContainingClassExcludingClassDecorators(location); !!containingClass; containingClass = getContainingClass(containingClass)) {
      const { symbol } = containingClass;
      const name = getSymbolNameForPrivateIdentifier(symbol, propName);
      const prop = symbol.members && symbol.members.get(name) || symbol.exports && symbol.exports.get(name);
      if (prop) {
        return prop;
      }
    }
  }
  function checkGrammarPrivateIdentifierExpression(privId) {
    if (!getContainingClass(privId)) {
      return grammarErrorOnNode(privId, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
    }
    if (!isForInStatement(privId.parent)) {
      if (!isExpressionNode(privId)) {
        return grammarErrorOnNode(privId, Diagnostics.Private_identifiers_are_only_allowed_in_class_bodies_and_may_only_be_used_as_part_of_a_class_member_declaration_property_access_or_on_the_left_hand_side_of_an_in_expression);
      }
      const isInOperation = isBinaryExpression(privId.parent) && privId.parent.operatorToken.kind === 103 /* InKeyword */;
      if (!getSymbolForPrivateIdentifierExpression(privId) && !isInOperation) {
        return grammarErrorOnNode(privId, Diagnostics.Cannot_find_name_0, idText(privId));
      }
    }
    return false;
  }
  function checkPrivateIdentifierExpression(privId) {
    checkGrammarPrivateIdentifierExpression(privId);
    const symbol = getSymbolForPrivateIdentifierExpression(privId);
    if (symbol) {
      markPropertyAsReferenced(
        symbol,
        /*nodeForCheckWriteOnly*/
        void 0,
        /*isSelfTypeAccess*/
        false
      );
    }
    return anyType;
  }
  function getSymbolForPrivateIdentifierExpression(privId) {
    if (!isExpressionNode(privId)) {
      return void 0;
    }
    const links = getNodeLinks(privId);
    if (links.resolvedSymbol === void 0) {
      links.resolvedSymbol = lookupSymbolForPrivateIdentifierDeclaration(privId.escapedText, privId);
    }
    return links.resolvedSymbol;
  }
  function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
    return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
  }
  function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
    let propertyOnType;
    const properties = getPropertiesOfType(leftType);
    if (properties) {
      forEach(properties, (symbol) => {
        const decl = symbol.valueDeclaration;
        if (decl && isNamedDeclaration(decl) && isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
          propertyOnType = symbol;
          return true;
        }
      });
    }
    const diagName = diagnosticName(right);
    if (propertyOnType) {
      const typeValueDecl = Debug.checkDefined(propertyOnType.valueDeclaration);
      const typeClass = Debug.checkDefined(getContainingClass(typeValueDecl));
      if (lexicallyScopedIdentifier == null ? void 0 : lexicallyScopedIdentifier.valueDeclaration) {
        const lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
        const lexicalClass = getContainingClass(lexicalValueDecl);
        Debug.assert(!!lexicalClass);
        if (findAncestor(lexicalClass, (n) => typeClass === n)) {
          const diagnostic = error(
            right,
            Diagnostics.The_property_0_cannot_be_accessed_on_type_1_within_this_class_because_it_is_shadowed_by_another_private_identifier_with_the_same_spelling,
            diagName,
            typeToString(leftType)
          );
          addRelatedInfo(
            diagnostic,
            createDiagnosticForNode(
              lexicalValueDecl,
              Diagnostics.The_shadowing_declaration_of_0_is_defined_here,
              diagName
            ),
            createDiagnosticForNode(
              typeValueDecl,
              Diagnostics.The_declaration_of_0_that_you_probably_intended_to_use_is_defined_here,
              diagName
            )
          );
          return true;
        }
      }
      error(
        right,
        Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier,
        diagName,
        diagnosticName(typeClass.name || anon)
      );
      return true;
    }
    return false;
  }
  function isThisPropertyAccessInConstructor(node, prop) {
    return (isConstructorDeclaredProperty(prop) || isThisProperty(node) && isAutoTypedProperty(prop)) && getThisContainer(
      node,
      /*includeArrowFunctions*/
      true,
      /*includeClassComputedPropertyName*/
      false
    ) === getDeclaringConstructor(prop);
  }
  function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right, checkMode, writeOnly) {
    const parentSymbol = getNodeLinks(left).resolvedSymbol;
    const assignmentKind = getAssignmentTargetKind(node);
    const apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
    const isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
    let prop;
    if (isPrivateIdentifier(right)) {
      if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) {
        if (assignmentKind !== 0 /* None */) {
          checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldSet */);
        }
        if (assignmentKind !== 1 /* Definite */) {
          checkExternalEmitHelpers(node, 524288 /* ClassPrivateFieldGet */);
        }
      }
      const lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
      if (assignmentKind && lexicallyScopedSymbol && lexicallyScopedSymbol.valueDeclaration && isMethodDeclaration(lexicallyScopedSymbol.valueDeclaration)) {
        grammarErrorOnNode(right, Diagnostics.Cannot_assign_to_private_method_0_Private_methods_are_not_writable, idText(right));
      }
      if (isAnyLike) {
        if (lexicallyScopedSymbol) {
          return isErrorType(apparentType) ? errorType : apparentType;
        }
        if (getContainingClassExcludingClassDecorators(right) === void 0) {
          grammarErrorOnNode(right, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
          return anyType;
        }
      }
      prop = lexicallyScopedSymbol && getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol);
      if (prop === void 0) {
        if (checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
          return errorType;
        }
        const containingClass = getContainingClassExcludingClassDecorators(right);
        if (containingClass && isPlainJsFile(getSourceFileOfNode(containingClass), compilerOptions.checkJs)) {
          grammarErrorOnNode(right, Diagnostics.Private_field_0_must_be_declared_in_an_enclosing_class, idText(right));
        }
      } else {
        const isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
        if (isSetonlyAccessor && assignmentKind !== 1 /* Definite */) {
          error(node, Diagnostics.Private_accessor_was_defined_without_a_getter);
        }
      }
    } else {
      if (isAnyLike) {
        if (isIdentifier(left) && parentSymbol) {
          markLinkedReferences(
            node,
            2 /* Property */,
            /*propSymbol*/
            void 0,
            leftType
          );
        }
        return isErrorType(apparentType) ? errorType : apparentType;
      }
      prop = getPropertyOfType(
        apparentType,
        right.escapedText,
        /*skipObjectFunctionPropertyAugment*/
        isConstEnumObjectType(apparentType),
        /*includeTypeOnlyMembers*/
        node.kind === 166 /* QualifiedName */
      );
    }
    markLinkedReferences(node, 2 /* Property */, prop, leftType);
    let propType;
    if (!prop) {
      const indexInfo = !isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getApplicableIndexInfoForName(apparentType, right.escapedText) : void 0;
      if (!(indexInfo && indexInfo.type)) {
        const isUncheckedJS = isUncheckedJSSuggestion(
          node,
          leftType.symbol,
          /*excludeClasses*/
          true
        );
        if (!isUncheckedJS && isJSLiteralType(leftType)) {
          return anyType;
        }
        if (leftType.symbol === globalThisSymbol) {
          if (globalThisSymbol.exports.has(right.escapedText) && globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */) {
            error(right, Diagnostics.Property_0_does_not_exist_on_type_1, unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
          } else if (noImplicitAny) {
            error(right, Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
          }
          return anyType;
        }
        if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
          reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType, isUncheckedJS);
        }
        return errorType;
      }
      if (indexInfo.isReadonly && (isAssignmentTarget(node) || isDeleteTarget(node))) {
        error(node, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
      }
      propType = indexInfo.type;
      if (compilerOptions.noUncheckedIndexedAccess && getAssignmentTargetKind(node) !== 1 /* Definite */) {
        propType = getUnionType([propType, missingType]);
      }
      if (compilerOptions.noPropertyAccessFromIndexSignature && isPropertyAccessExpression(node)) {
        error(right, Diagnostics.Property_0_comes_from_an_index_signature_so_it_must_be_accessed_with_0, unescapeLeadingUnderscores(right.escapedText));
      }
      if (indexInfo.declaration && isDeprecatedDeclaration(indexInfo.declaration)) {
        addDeprecatedSuggestion(right, [indexInfo.declaration], right.escapedText);
      }
    } else {
      const targetPropSymbol = resolveAliasWithDeprecationCheck(prop, right);
      if (isDeprecatedSymbol(targetPropSymbol) && isUncalledFunctionReference(node, targetPropSymbol) && targetPropSymbol.declarations) {
        addDeprecatedSuggestion(right, targetPropSymbol.declarations, right.escapedText);
      }
      checkPropertyNotUsedBeforeDeclaration(prop, node, right);
      markPropertyAsReferenced(prop, node, isSelfTypeAccess(left, parentSymbol));
      getNodeLinks(node).resolvedSymbol = prop;
      checkPropertyAccessibility(node, left.kind === 108 /* SuperKeyword */, isWriteAccess(node), apparentType, prop);
      if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
        error(right, Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, idText(right));
        return errorType;
      }
      propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : writeOnly || isWriteOnlyAccess(node) ? getWriteTypeOfSymbol(prop) : getTypeOfSymbol(prop);
    }
    return getFlowTypeOfAccessExpression(node, prop, propType, right, checkMode);
  }
  function isUncheckedJSSuggestion(node, suggestion, excludeClasses) {
    var _a;
    const file = getSourceFileOfNode(node);
    if (file) {
      if (compilerOptions.checkJs === void 0 && file.checkJsDirective === void 0 && (file.scriptKind === 1 /* JS */ || file.scriptKind === 2 /* JSX */)) {
        const declarationFile = forEach(suggestion == null ? void 0 : suggestion.declarations, getSourceFileOfNode);
        const suggestionHasNoExtendsOrDecorators = !(suggestion == null ? void 0 : suggestion.valueDeclaration) || !isClassLike(suggestion.valueDeclaration) || ((_a = suggestion.valueDeclaration.heritageClauses) == null ? void 0 : _a.length) || classOrConstructorParameterIsDecorated(
          /*useLegacyDecorators*/
          false,
          suggestion.valueDeclaration
        );
        return !(file !== declarationFile && !!declarationFile && isGlobalSourceFile(declarationFile)) && !(excludeClasses && suggestion && suggestion.flags & 32 /* Class */ && suggestionHasNoExtendsOrDecorators) && !(!!node && excludeClasses && isPropertyAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */ && suggestionHasNoExtendsOrDecorators);
      }
    }
    return false;
  }
  function getFlowTypeOfAccessExpression(node, prop, propType, errorNode, checkMode) {
    const assignmentKind = getAssignmentTargetKind(node);
    if (assignmentKind === 1 /* Definite */) {
      return removeMissingType(propType, !!(prop && prop.flags & 16777216 /* Optional */));
    }
    if (prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */) && !isDuplicatedCommonJSExport(prop.declarations)) {
      return propType;
    }
    if (propType === autoType) {
      return getFlowTypeOfProperty(node, prop);
    }
    propType = getNarrowableTypeForReference(propType, node, checkMode);
    let assumeUninitialized = false;
    if (strictNullChecks && strictPropertyInitialization && isAccessExpression(node) && node.expression.kind === 110 /* ThisKeyword */) {
      const declaration = prop && prop.valueDeclaration;
      if (declaration && isPropertyWithoutInitializer(declaration)) {
        if (!isStatic(declaration)) {
          const flowContainer = getControlFlowContainer(node);
          if (flowContainer.kind === 176 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 33554432 /* Ambient */)) {
            assumeUninitialized = true;
          }
        }
      }
    } else if (strictNullChecks && prop && prop.valueDeclaration && isPropertyAccessExpression(prop.valueDeclaration) && getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) && getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
      assumeUninitialized = true;
    }
    const flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
    if (assumeUninitialized && !containsUndefinedType(propType) && containsUndefinedType(flowType)) {
      error(errorNode, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop));
      return propType;
    }
    return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
  }
  function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
    const { valueDeclaration } = prop;
    if (!valueDeclaration || getSourceFileOfNode(node).isDeclarationFile) {
      return;
    }
    let diagnosticMessage;
    const declarationName = idText(right);
    if (isInPropertyInitializerOrClassStaticBlock(node) && !isOptionalPropertyDeclaration(valueDeclaration) && !(isAccessExpression(node) && isAccessExpression(node.expression)) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right) && !(isMethodDeclaration(valueDeclaration) && getCombinedModifierFlagsCached(valueDeclaration) & 256 /* Static */) && (useDefineForClassFields || !isPropertyDeclaredInAncestorClass(prop))) {
      diagnosticMessage = error(right, Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
    } else if (valueDeclaration.kind === 263 /* ClassDeclaration */ && node.parent.kind !== 183 /* TypeReference */ && !(valueDeclaration.flags & 33554432 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
      diagnosticMessage = error(right, Diagnostics.Class_0_used_before_its_declaration, declarationName);
    }
    if (diagnosticMessage) {
      addRelatedInfo(diagnosticMessage, createDiagnosticForNode(valueDeclaration, Diagnostics._0_is_declared_here, declarationName));
    }
  }
  function isInPropertyInitializerOrClassStaticBlock(node) {
    return !!findAncestor(node, (node2) => {
      switch (node2.kind) {
        case 172 /* PropertyDeclaration */:
          return true;
        case 303 /* PropertyAssignment */:
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 305 /* SpreadAssignment */:
        case 167 /* ComputedPropertyName */:
        case 239 /* TemplateSpan */:
        case 294 /* JsxExpression */:
        case 291 /* JsxAttribute */:
        case 292 /* JsxAttributes */:
        case 293 /* JsxSpreadAttribute */:
        case 286 /* JsxOpeningElement */:
        case 233 /* ExpressionWithTypeArguments */:
        case 298 /* HeritageClause */:
          return false;
        case 219 /* ArrowFunction */:
        case 244 /* ExpressionStatement */:
          return isBlock(node2.parent) && isClassStaticBlockDeclaration(node2.parent.parent) ? true : "quit";
        default:
          return isExpressionNode(node2) ? false : "quit";
      }
    });
  }
  function isPropertyDeclaredInAncestorClass(prop) {
    if (!(prop.parent.flags & 32 /* Class */)) {
      return false;
    }
    let classType = getTypeOfSymbol(prop.parent);
    while (true) {
      classType = classType.symbol && getSuperClass(classType);
      if (!classType) {
        return false;
      }
      const superProperty = getPropertyOfType(classType, prop.escapedName);
      if (superProperty && superProperty.valueDeclaration) {
        return true;
      }
    }
  }
  function getSuperClass(classType) {
    const x = getBaseTypes(classType);
    if (x.length === 0) {
      return void 0;
    }
    return getIntersectionType(x);
  }
  function reportNonexistentProperty(propNode, containingType, isUncheckedJS) {
    const links = getNodeLinks(propNode);
    const cache = links.nonExistentPropCheckCache || (links.nonExistentPropCheckCache = /* @__PURE__ */ new Set());
    const key = `${getTypeId(containingType)}|${isUncheckedJS}`;
    if (cache.has(key)) {
      return;
    }
    cache.add(key);
    let errorInfo;
    let relatedInfo;
    if (!isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 402784252 /* Primitive */)) {
      for (const subtype of containingType.types) {
        if (!getPropertyOfType(subtype, propNode.escapedText) && !getApplicableIndexInfoForName(subtype, propNode.escapedText)) {
          errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(subtype));
          break;
        }
      }
    }
    if (typeHasStaticProperty(propNode.escapedText, containingType)) {
      const propName = declarationNameToString(propNode);
      const typeName = typeToString(containingType);
      errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_to_access_the_static_member_2_instead, propName, typeName, typeName + "." + propName);
    } else {
      const promisedType = getPromisedTypeOfPromise(containingType);
      if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
        errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1, declarationNameToString(propNode), typeToString(containingType));
        relatedInfo = createDiagnosticForNode(propNode, Diagnostics.Did_you_forget_to_use_await);
      } else {
        const missingProperty = declarationNameToString(propNode);
        const container = typeToString(containingType);
        const libSuggestion = getSuggestedLibForNonExistentProperty(missingProperty, containingType);
        if (libSuggestion !== void 0) {
          errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later, missingProperty, container, libSuggestion);
        } else {
          const suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
          if (suggestion !== void 0) {
            const suggestedName = symbolName(suggestion);
            const message = isUncheckedJS ? Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2 : Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2;
            errorInfo = chainDiagnosticMessages(errorInfo, message, missingProperty, container, suggestedName);
            relatedInfo = suggestion.valueDeclaration && createDiagnosticForNode(suggestion.valueDeclaration, Diagnostics._0_is_declared_here, suggestedName);
          } else {
            const diagnostic = containerSeemsToBeEmptyDomElement(containingType) ? Diagnostics.Property_0_does_not_exist_on_type_1_Try_changing_the_lib_compiler_option_to_include_dom : Diagnostics.Property_0_does_not_exist_on_type_1;
            errorInfo = chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), diagnostic, missingProperty, container);
          }
        }
      }
    }
    const resultDiagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(propNode), propNode, errorInfo);
    if (relatedInfo) {
      addRelatedInfo(resultDiagnostic, relatedInfo);
    }
    addErrorOrSuggestion(!isUncheckedJS || errorInfo.code !== Diagnostics.Property_0_may_not_exist_on_type_1_Did_you_mean_2.code, resultDiagnostic);
  }
  function containerSeemsToBeEmptyDomElement(containingType) {
    return compilerOptions.lib && !compilerOptions.lib.includes("dom") && everyContainedType(containingType, (type) => type.symbol && /^(?:EventTarget|Node|(?:HTML[a-zA-Z]*)?Element)$/.test(unescapeLeadingUnderscores(type.symbol.escapedName))) && isEmptyObjectType(containingType);
  }
  function typeHasStaticProperty(propName, containingType) {
    const prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
    return prop !== void 0 && !!prop.valueDeclaration && isStatic(prop.valueDeclaration);
  }
  function getSuggestedLibForNonExistentName(name) {
    const missingName = diagnosticName(name);
    const allFeatures = getScriptTargetFeatures();
    const typeFeatures = allFeatures.get(missingName);
    return typeFeatures && firstIterator(typeFeatures.keys());
  }
  function getSuggestedLibForNonExistentProperty(missingProperty, containingType) {
    const container = getApparentType(containingType).symbol;
    if (!container) {
      return void 0;
    }
    const containingTypeName = symbolName(container);
    const allFeatures = getScriptTargetFeatures();
    const typeFeatures = allFeatures.get(containingTypeName);
    if (typeFeatures) {
      for (const [libTarget, featuresOfType] of typeFeatures) {
        if (contains(featuresOfType, missingProperty)) {
          return libTarget;
        }
      }
    }
  }
  function getSuggestedSymbolForNonexistentClassMember(name, baseType) {
    return getSpellingSuggestionForName(name, getPropertiesOfType(baseType), 106500 /* ClassMember */);
  }
  function getSuggestedSymbolForNonexistentProperty(name, containingType) {
    let props = getPropertiesOfType(containingType);
    if (typeof name !== "string") {
      const parent = name.parent;
      if (isPropertyAccessExpression(parent)) {
        props = filter(props, (prop) => isValidPropertyAccessForCompletions(parent, containingType, prop));
      }
      name = idText(name);
    }
    return getSpellingSuggestionForName(name, props, 111551 /* Value */);
  }
  function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) {
    const strName = isString(name) ? name : idText(name);
    const properties = getPropertiesOfType(containingType);
    const jsxSpecific = strName === "for" ? find(properties, (x) => symbolName(x) === "htmlFor") : strName === "class" ? find(properties, (x) => symbolName(x) === "className") : void 0;
    return jsxSpecific ?? getSpellingSuggestionForName(strName, properties, 111551 /* Value */);
  }
  function getSuggestionForNonexistentProperty(name, containingType) {
    const suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
    return suggestion && symbolName(suggestion);
  }
  function getSuggestionForSymbolNameLookup(symbols, name, meaning) {
    const symbol = getSymbol(symbols, name, meaning);
    if (symbol) return symbol;
    let candidates;
    if (symbols === globals) {
      const primitives = mapDefined(
        ["string", "number", "boolean", "object", "bigint", "symbol"],
        (s) => symbols.has(s.charAt(0).toUpperCase() + s.slice(1)) ? createSymbol(524288 /* TypeAlias */, s) : void 0
      );
      candidates = primitives.concat(arrayFrom(symbols.values()));
    } else {
      candidates = arrayFrom(symbols.values());
    }
    return getSpellingSuggestionForName(unescapeLeadingUnderscores(name), candidates, meaning);
  }
  function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
    Debug.assert(outerName !== void 0, "outername should always be defined");
    const result = resolveNameForSymbolSuggestion(
      location,
      outerName,
      meaning,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false,
      /*excludeGlobals*/
      false
    );
    return result;
  }
  function getSuggestedSymbolForNonexistentModule(name, targetModule) {
    return targetModule.exports && getSpellingSuggestionForName(idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
  }
  function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
    function hasProp(name) {
      const prop = getPropertyOfObjectType(objectType, name);
      if (prop) {
        const s = getSingleCallSignature(getTypeOfSymbol(prop));
        return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
      }
      return false;
    }
    const suggestedMethod = isAssignmentTarget(expr) ? "set" : "get";
    if (!hasProp(suggestedMethod)) {
      return void 0;
    }
    let suggestion = tryGetPropertyAccessOrIdentifierToString(expr.expression);
    if (suggestion === void 0) {
      suggestion = suggestedMethod;
    } else {
      suggestion += "." + suggestedMethod;
    }
    return suggestion;
  }
  function getSuggestedTypeForNonexistentStringLiteralType(source, target) {
    const candidates = target.types.filter((type) => !!(type.flags & 128 /* StringLiteral */));
    return getSpellingSuggestion(source.value, candidates, (type) => type.value);
  }
  function getSpellingSuggestionForName(name, symbols, meaning) {
    return getSpellingSuggestion(name, symbols, getCandidateName);
    function getCandidateName(candidate) {
      const candidateName = symbolName(candidate);
      if (startsWith(candidateName, '"')) {
        return void 0;
      }
      if (candidate.flags & meaning) {
        return candidateName;
      }
      if (candidate.flags & 2097152 /* Alias */) {
        const alias = tryResolveAlias(candidate);
        if (alias && alias.flags & meaning) {
          return candidateName;
        }
      }
      return void 0;
    }
  }
  function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isSelfTypeAccess2) {
    const valueDeclaration = prop && prop.flags & 106500 /* ClassMember */ && prop.valueDeclaration;
    if (!valueDeclaration) {
      return;
    }
    const hasPrivateModifier = hasEffectiveModifier(valueDeclaration, 2 /* Private */);
    const hasPrivateIdentifier = prop.valueDeclaration && isNamedDeclaration(prop.valueDeclaration) && isPrivateIdentifier(prop.valueDeclaration.name);
    if (!hasPrivateModifier && !hasPrivateIdentifier) {
      return;
    }
    if (nodeForCheckWriteOnly && isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
      return;
    }
    if (isSelfTypeAccess2) {
      const containingMethod = findAncestor(nodeForCheckWriteOnly, isFunctionLikeDeclaration);
      if (containingMethod && containingMethod.symbol === prop) {
        return;
      }
    }
    (getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = -1 /* All */;
  }
  function isSelfTypeAccess(name, parent) {
    return name.kind === 110 /* ThisKeyword */ || !!parent && isEntityNameExpression(name) && parent === getResolvedSymbol(getFirstIdentifier(name));
  }
  function isValidPropertyAccess(node, propertyName) {
    switch (node.kind) {
      case 211 /* PropertyAccessExpression */:
        return isValidPropertyAccessWithType(node, node.expression.kind === 108 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
      case 166 /* QualifiedName */:
        return isValidPropertyAccessWithType(
          node,
          /*isSuper*/
          false,
          propertyName,
          getWidenedType(checkExpression(node.left))
        );
      case 205 /* ImportType */:
        return isValidPropertyAccessWithType(
          node,
          /*isSuper*/
          false,
          propertyName,
          getTypeFromTypeNode(node)
        );
    }
  }
  function isValidPropertyAccessForCompletions(node, type, property) {
    return isPropertyAccessible(
      node,
      node.kind === 211 /* PropertyAccessExpression */ && node.expression.kind === 108 /* SuperKeyword */,
      /*isWrite*/
      false,
      type,
      property
    );
  }
  function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
    if (isTypeAny(type)) {
      return true;
    }
    const prop = getPropertyOfType(type, propertyName);
    return !!prop && isPropertyAccessible(
      node,
      isSuper,
      /*isWrite*/
      false,
      type,
      prop
    );
  }
  function isPropertyAccessible(node, isSuper, isWrite, containingType, property) {
    if (isTypeAny(containingType)) {
      return true;
    }
    if (property.valueDeclaration && isPrivateIdentifierClassElementDeclaration(property.valueDeclaration)) {
      const declClass = getContainingClass(property.valueDeclaration);
      return !isOptionalChain(node) && !!findAncestor(node, (parent) => parent === declClass);
    }
    return checkPropertyAccessibilityAtLocation(node, isSuper, isWrite, containingType, property);
  }
  function getForInVariableSymbol(node) {
    const initializer = node.initializer;
    if (initializer.kind === 261 /* VariableDeclarationList */) {
      const variable = initializer.declarations[0];
      if (variable && !isBindingPattern(variable.name)) {
        return getSymbolOfDeclaration(variable);
      }
    } else if (initializer.kind === 80 /* Identifier */) {
      return getResolvedSymbol(initializer);
    }
    return void 0;
  }
  function hasNumericPropertyNames(type) {
    return getIndexInfosOfType(type).length === 1 && !!getIndexInfoOfType(type, numberType);
  }
  function isForInVariableForNumericPropertyNames(expr) {
    const e = skipParentheses(expr);
    if (e.kind === 80 /* Identifier */) {
      const symbol = getResolvedSymbol(e);
      if (symbol.flags & 3 /* Variable */) {
        let child = expr;
        let node = expr.parent;
        while (node) {
          if (node.kind === 249 /* ForInStatement */ && child === node.statement && getForInVariableSymbol(node) === symbol && hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
            return true;
          }
          child = node;
          node = node.parent;
        }
      }
    }
    return false;
  }
  function checkIndexedAccess(node, checkMode) {
    return node.flags & 64 /* OptionalChain */ ? checkElementAccessChain(node, checkMode) : checkElementAccessExpression(node, checkNonNullExpression(node.expression), checkMode);
  }
  function checkElementAccessChain(node, checkMode) {
    const exprType = checkExpression(node.expression);
    const nonOptionalType = getOptionalExpressionType(exprType, node.expression);
    return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression), checkMode), node, nonOptionalType !== exprType);
  }
  function checkElementAccessExpression(node, exprType, checkMode) {
    const objectType = getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
    const indexExpression = node.argumentExpression;
    const indexType = checkExpression(indexExpression);
    if (isErrorType(objectType) || objectType === silentNeverType) {
      return objectType;
    }
    if (isConstEnumObjectType(objectType) && !isStringLiteralLike(indexExpression)) {
      error(indexExpression, Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
      return errorType;
    }
    const effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
    const assignmentTargetKind = getAssignmentTargetKind(node);
    let accessFlags;
    if (assignmentTargetKind === 0 /* None */) {
      accessFlags = 32 /* ExpressionPosition */;
    } else {
      accessFlags = 4 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 2 /* NoIndexSignatures */ : 0);
      if (assignmentTargetKind === 2 /* Compound */) {
        accessFlags |= 32 /* ExpressionPosition */;
      }
    }
    const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, accessFlags, node) || errorType;
    return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, getNodeLinks(node).resolvedSymbol, indexedAccessType, indexExpression, checkMode), node);
  }
  function callLikeExpressionMayHaveTypeArguments(node) {
    return isCallOrNewExpression(node) || isTaggedTemplateExpression(node) || isJsxOpeningLikeElement(node);
  }
  function resolveUntypedCall(node) {
    if (callLikeExpressionMayHaveTypeArguments(node)) {
      forEach(node.typeArguments, checkSourceElement);
    }
    if (node.kind === 215 /* TaggedTemplateExpression */) {
      checkExpression(node.template);
    } else if (isJsxOpeningLikeElement(node)) {
      checkExpression(node.attributes);
    } else if (isBinaryExpression(node)) {
      checkExpression(node.left);
    } else if (isCallOrNewExpression(node)) {
      forEach(node.arguments, (argument) => {
        checkExpression(argument);
      });
    }
    return anySignature;
  }
  function resolveErrorCall(node) {
    resolveUntypedCall(node);
    return unknownSignature;
  }
  function reorderCandidates(signatures, result, callChainFlags) {
    let lastParent;
    let lastSymbol;
    let cutoffIndex = 0;
    let index;
    let specializedIndex = -1;
    let spliceIndex;
    Debug.assert(!result.length);
    for (const signature of signatures) {
      const symbol = signature.declaration && getSymbolOfDeclaration(signature.declaration);
      const parent = signature.declaration && signature.declaration.parent;
      if (!lastSymbol || symbol === lastSymbol) {
        if (lastParent && parent === lastParent) {
          index = index + 1;
        } else {
          lastParent = parent;
          index = cutoffIndex;
        }
      } else {
        index = cutoffIndex = result.length;
        lastParent = parent;
      }
      lastSymbol = symbol;
      if (signatureHasLiteralTypes(signature)) {
        specializedIndex++;
        spliceIndex = specializedIndex;
        cutoffIndex++;
      } else {
        spliceIndex = index;
      }
      result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
    }
  }
  function isSpreadArgument(arg) {
    return !!arg && (arg.kind === 230 /* SpreadElement */ || arg.kind === 237 /* SyntheticExpression */ && arg.isSpread);
  }
  function getSpreadArgumentIndex(args) {
    return findIndex(args, isSpreadArgument);
  }
  function acceptsVoid(t) {
    return !!(t.flags & 16384 /* Void */);
  }
  function acceptsVoidUndefinedUnknownOrAny(t) {
    return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */));
  }
  function hasCorrectArity(node, args, signature, signatureHelpTrailingComma = false) {
    if (isJsxOpeningFragment(node)) return true;
    let argCount;
    let callIsIncomplete = false;
    let effectiveParameterCount = getParameterCount(signature);
    let effectiveMinimumArguments = getMinArgumentCount(signature);
    if (node.kind === 215 /* TaggedTemplateExpression */) {
      argCount = args.length;
      if (node.template.kind === 228 /* TemplateExpression */) {
        const lastSpan = last(node.template.templateSpans);
        callIsIncomplete = nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
      } else {
        const templateLiteral = node.template;
        Debug.assert(templateLiteral.kind === 15 /* NoSubstitutionTemplateLiteral */);
        callIsIncomplete = !!templateLiteral.isUnterminated;
      }
    } else if (node.kind === 170 /* Decorator */) {
      argCount = getDecoratorArgumentCount(node, signature);
    } else if (node.kind === 226 /* BinaryExpression */) {
      argCount = 1;
    } else if (isJsxOpeningLikeElement(node)) {
      callIsIncomplete = node.attributes.end === node.end;
      if (callIsIncomplete) {
        return true;
      }
      argCount = effectiveMinimumArguments === 0 ? args.length : 1;
      effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1;
      effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1);
    } else if (!node.arguments) {
      Debug.assert(node.kind === 214 /* NewExpression */);
      return getMinArgumentCount(signature) === 0;
    } else {
      argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
      callIsIncomplete = node.arguments.end === node.end;
      const spreadArgIndex = getSpreadArgumentIndex(args);
      if (spreadArgIndex >= 0) {
        return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
      }
    }
    if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
      return false;
    }
    if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
      return true;
    }
    for (let i = argCount; i < effectiveMinimumArguments; i++) {
      const type = getTypeAtPosition(signature, i);
      if (filterType(type, isInJSFile(node) && !strictNullChecks ? acceptsVoidUndefinedUnknownOrAny : acceptsVoid).flags & 131072 /* Never */) {
        return false;
      }
    }
    return true;
  }
  function hasCorrectTypeArgumentArity(signature, typeArguments) {
    const numTypeParameters = length(signature.typeParameters);
    const minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
    return !some(typeArguments) || typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters;
  }
  function isInstantiatedGenericParameter(signature, pos) {
    let type;
    return !!(signature.target && (type = tryGetTypeAtPosition(signature.target, pos)) && isGenericType(type));
  }
  function getSingleCallSignature(type) {
    return getSingleSignature(
      type,
      0 /* Call */,
      /*allowMembers*/
      false
    );
  }
  function getSingleCallOrConstructSignature(type) {
    return getSingleSignature(
      type,
      0 /* Call */,
      /*allowMembers*/
      false
    ) || getSingleSignature(
      type,
      1 /* Construct */,
      /*allowMembers*/
      false
    );
  }
  function getSingleSignature(type, kind, allowMembers) {
    if (type.flags & 524288 /* Object */) {
      const resolved = resolveStructuredTypeMembers(type);
      if (allowMembers || resolved.properties.length === 0 && resolved.indexInfos.length === 0) {
        if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
          return resolved.callSignatures[0];
        }
        if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
          return resolved.constructSignatures[0];
        }
      }
    }
    return void 0;
  }
  function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
    const context = createInferenceContext(getTypeParametersForMapper(signature), signature, 0 /* None */, compareTypes);
    const restType = getEffectiveRestType(contextualSignature);
    const mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
    const sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
    applyToParameterTypes(sourceSignature, signature, (source, target) => {
      inferTypes(context.inferences, source, target);
    });
    if (!inferenceContext) {
      applyToReturnTypes(contextualSignature, signature, (source, target) => {
        inferTypes(context.inferences, source, target, 128 /* ReturnType */);
      });
    }
    return getSignatureInstantiation(signature, getInferredTypes(context), isInJSFile(contextualSignature.declaration));
  }
  function inferJsxTypeArguments(node, signature, checkMode, context) {
    const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
    const checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
    inferTypes(context.inferences, checkAttrType, paramType);
    return getInferredTypes(context);
  }
  function getThisArgumentType(thisArgumentNode) {
    if (!thisArgumentNode) {
      return voidType;
    }
    const thisArgumentType = checkExpression(thisArgumentNode);
    return isRightSideOfInstanceofExpression(thisArgumentNode) ? thisArgumentType : isOptionalChainRoot(thisArgumentNode.parent) ? getNonNullableType(thisArgumentType) : isOptionalChain(thisArgumentNode.parent) ? removeOptionalTypeMarker(thisArgumentType) : thisArgumentType;
  }
  function inferTypeArguments(node, signature, args, checkMode, context) {
    if (isJsxOpeningLikeElement(node)) {
      return inferJsxTypeArguments(node, signature, checkMode, context);
    }
    if (node.kind !== 170 /* Decorator */ && node.kind !== 226 /* BinaryExpression */) {
      const skipBindingPatterns = every(signature.typeParameters, (p) => !!getDefaultFromTypeParameter(p));
      const contextualType = getContextualType(node, skipBindingPatterns ? 8 /* SkipBindingPatterns */ : 0 /* None */);
      if (contextualType) {
        const inferenceTargetType = getReturnTypeOfSignature(signature);
        if (couldContainTypeVariables(inferenceTargetType)) {
          const outerContext = getInferenceContext(node);
          const isFromBindingPattern = !skipBindingPatterns && getContextualType(node, 8 /* SkipBindingPatterns */) !== contextualType;
          if (!isFromBindingPattern) {
            const outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
            const instantiatedType = instantiateType(contextualType, outerMapper);
            const contextualSignature = getSingleCallSignature(instantiatedType);
            const inferenceSourceType = contextualSignature && contextualSignature.typeParameters ? getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) : instantiatedType;
            inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 128 /* ReturnType */);
          }
          const returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
          const returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
          inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
          context.returnMapper = some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : void 0;
        }
      }
    }
    const restType = getNonArrayRestType(signature);
    const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
    if (restType && restType.flags & 262144 /* TypeParameter */) {
      const info = find(context.inferences, (info2) => info2.typeParameter === restType);
      if (info) {
        info.impliedArity = findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : void 0;
      }
    }
    const thisType = getThisTypeOfSignature(signature);
    if (thisType && couldContainTypeVariables(thisType)) {
      const thisArgumentNode = getThisArgumentOfCall(node);
      inferTypes(context.inferences, getThisArgumentType(thisArgumentNode), thisType);
    }
    for (let i = 0; i < argCount; i++) {
      const arg = args[i];
      if (arg.kind !== 232 /* OmittedExpression */) {
        const paramType = getTypeAtPosition(signature, i);
        if (couldContainTypeVariables(paramType)) {
          const argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
          inferTypes(context.inferences, argType, paramType);
        }
      }
    }
    if (restType && couldContainTypeVariables(restType)) {
      const spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode);
      inferTypes(context.inferences, spreadType, restType);
    }
    return getInferredTypes(context);
  }
  function getMutableArrayOrTupleType(type) {
    return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) : type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type : isTupleType(type) ? createTupleType(
      getElementTypes(type),
      type.target.elementFlags,
      /*readonly*/
      false,
      type.target.labeledElementDeclarations
    ) : createTupleType([type], [8 /* Variadic */]);
  }
  function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) {
    const inConstContext = isConstTypeVariable(restType);
    if (index >= argCount - 1) {
      const arg = args[argCount - 1];
      if (isSpreadArgument(arg)) {
        const spreadType = arg.kind === 237 /* SyntheticExpression */ ? arg.type : checkExpressionWithContextualType(arg.expression, restType, context, checkMode);
        if (isArrayLikeType(spreadType)) {
          return getMutableArrayOrTupleType(spreadType);
        }
        return createArrayType(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 230 /* SpreadElement */ ? arg.expression : arg), inConstContext);
      }
    }
    const types = [];
    const flags = [];
    const names = [];
    for (let i = index; i < argCount; i++) {
      const arg = args[i];
      if (isSpreadArgument(arg)) {
        const spreadType = arg.kind === 237 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression);
        if (isArrayLikeType(spreadType)) {
          types.push(spreadType);
          flags.push(8 /* Variadic */);
        } else {
          types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 230 /* SpreadElement */ ? arg.expression : arg));
          flags.push(4 /* Rest */);
        }
      } else {
        const contextualType = isTupleType(restType) ? getContextualTypeForElementExpression(restType, i - index, argCount - index) || unknownType : getIndexedAccessType(restType, getNumberLiteralType(i - index), 256 /* Contextual */);
        const argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
        const hasPrimitiveContextualType = inConstContext || maybeTypeOfKind(contextualType, 402784252 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
        types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
        flags.push(1 /* Required */);
      }
      if (arg.kind === 237 /* SyntheticExpression */ && arg.tupleNameSource) {
        names.push(arg.tupleNameSource);
      } else {
        names.push(void 0);
      }
    }
    return createTupleType(types, flags, inConstContext && !someType(restType, isMutableArrayLikeType), names);
  }
  function checkTypeArguments(signature, typeArgumentNodes, reportErrors2, headMessage) {
    const isJavascript = isInJSFile(signature.declaration);
    const typeParameters = signature.typeParameters;
    const typeArgumentTypes = fillMissingTypeArguments(map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
    let mapper;
    for (let i = 0; i < typeArgumentNodes.length; i++) {
      Debug.assert(typeParameters[i] !== void 0, "Should not call checkTypeArguments with too many type arguments");
      const constraint = getConstraintOfTypeParameter(typeParameters[i]);
      if (constraint) {
        const errorInfo = reportErrors2 && headMessage ? () => chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Type_0_does_not_satisfy_the_constraint_1
        ) : void 0;
        const typeArgumentHeadMessage = headMessage || Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
        if (!mapper) {
          mapper = createTypeMapper(typeParameters, typeArgumentTypes);
        }
        const typeArgument = typeArgumentTypes[i];
        if (!checkTypeAssignableTo(
          typeArgument,
          getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument),
          reportErrors2 ? typeArgumentNodes[i] : void 0,
          typeArgumentHeadMessage,
          errorInfo
        )) {
          return void 0;
        }
      }
    }
    return typeArgumentTypes;
  }
  function getJsxReferenceKind(node) {
    if (isJsxIntrinsicTagName(node.tagName)) {
      return 2 /* Mixed */;
    }
    const tagType = getApparentType(checkExpression(node.tagName));
    if (length(getSignaturesOfType(tagType, 1 /* Construct */))) {
      return 0 /* Component */;
    }
    if (length(getSignaturesOfType(tagType, 0 /* Call */))) {
      return 1 /* Function */;
    }
    return 2 /* Mixed */;
  }
  function checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer) {
    const paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
    const attributesType = isJsxOpeningFragment(node) ? createJsxAttributesTypeFromAttributesProperty(node) : checkExpressionWithContextualType(
      node.attributes,
      paramType,
      /*inferenceContext*/
      void 0,
      checkMode
    );
    const checkAttributesType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(attributesType) : attributesType;
    return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(
      checkAttributesType,
      paramType,
      relation,
      reportErrors2 ? isJsxOpeningFragment(node) ? node : node.tagName : void 0,
      isJsxOpeningFragment(node) ? void 0 : node.attributes,
      /*headMessage*/
      void 0,
      containingMessageChain,
      errorOutputContainer
    );
    function checkTagNameDoesNotExpectTooManyArguments() {
      var _a;
      if (getJsxNamespaceContainerForImplicitImport(node)) {
        return true;
      }
      const tagType = (isJsxOpeningElement(node) || isJsxSelfClosingElement(node)) && !(isJsxIntrinsicTagName(node.tagName) || isJsxNamespacedName(node.tagName)) ? checkExpression(node.tagName) : void 0;
      if (!tagType) {
        return true;
      }
      const tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
      if (!length(tagCallSignatures)) {
        return true;
      }
      const factory2 = getJsxFactoryEntity(node);
      if (!factory2) {
        return true;
      }
      const factorySymbol = resolveEntityName(
        factory2,
        111551 /* Value */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        false,
        node
      );
      if (!factorySymbol) {
        return true;
      }
      const factoryType = getTypeOfSymbol(factorySymbol);
      const callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
      if (!length(callSignatures)) {
        return true;
      }
      let hasFirstParamSignatures = false;
      let maxParamCount = 0;
      for (const sig of callSignatures) {
        const firstparam = getTypeAtPosition(sig, 0);
        const signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
        if (!length(signaturesOfParam)) continue;
        for (const paramSig of signaturesOfParam) {
          hasFirstParamSignatures = true;
          if (hasEffectiveRestParameter(paramSig)) {
            return true;
          }
          const paramCount = getParameterCount(paramSig);
          if (paramCount > maxParamCount) {
            maxParamCount = paramCount;
          }
        }
      }
      if (!hasFirstParamSignatures) {
        return true;
      }
      let absoluteMinArgCount = Infinity;
      for (const tagSig of tagCallSignatures) {
        const tagRequiredArgCount = getMinArgumentCount(tagSig);
        if (tagRequiredArgCount < absoluteMinArgCount) {
          absoluteMinArgCount = tagRequiredArgCount;
        }
      }
      if (absoluteMinArgCount <= maxParamCount) {
        return true;
      }
      if (reportErrors2) {
        const tagName = node.tagName;
        const diag2 = createDiagnosticForNode(tagName, Diagnostics.Tag_0_expects_at_least_1_arguments_but_the_JSX_factory_2_provides_at_most_3, entityNameToString(tagName), absoluteMinArgCount, entityNameToString(factory2), maxParamCount);
        const tagNameDeclaration = (_a = getSymbolAtLocation(tagName)) == null ? void 0 : _a.valueDeclaration;
        if (tagNameDeclaration) {
          addRelatedInfo(diag2, createDiagnosticForNode(tagNameDeclaration, Diagnostics._0_is_declared_here, entityNameToString(tagName)));
        }
        if (errorOutputContainer && errorOutputContainer.skipLogging) {
          (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag2);
        }
        if (!errorOutputContainer.skipLogging) {
          diagnostics.add(diag2);
        }
      }
      return false;
    }
  }
  function getEffectiveCheckNode(argument) {
    argument = skipParentheses(argument);
    return isSatisfiesExpression(argument) ? skipParentheses(argument.expression) : argument;
  }
  function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors2, containingMessageChain, inferenceContext) {
    const errorOutputContainer = { errors: void 0, skipLogging: true };
    if (isJsxCallLike(node)) {
      if (!checkApplicableSignatureForJsxCallLikeElement(node, signature, relation, checkMode, reportErrors2, containingMessageChain, errorOutputContainer)) {
        Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
        return errorOutputContainer.errors || emptyArray;
      }
      return void 0;
    }
    const thisType = getThisTypeOfSignature(signature);
    if (thisType && thisType !== voidType && !(isNewExpression(node) || isCallExpression(node) && isSuperProperty(node.expression))) {
      const thisArgumentNode = getThisArgumentOfCall(node);
      const thisArgumentType = getThisArgumentType(thisArgumentNode);
      const errorNode = reportErrors2 ? thisArgumentNode || node : void 0;
      const headMessage2 = Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
      if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage2, containingMessageChain, errorOutputContainer)) {
        Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
        return errorOutputContainer.errors || emptyArray;
      }
    }
    const headMessage = Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
    const restType = getNonArrayRestType(signature);
    const argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
    for (let i = 0; i < argCount; i++) {
      const arg = args[i];
      if (arg.kind !== 232 /* OmittedExpression */) {
        const paramType = getTypeAtPosition(signature, i);
        const argType = checkExpressionWithContextualType(
          arg,
          paramType,
          /*inferenceContext*/
          void 0,
          checkMode
        );
        const regularArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
        const checkArgType = inferenceContext ? instantiateType(regularArgType, inferenceContext.nonFixingMapper) : regularArgType;
        const effectiveCheckArgumentNode = getEffectiveCheckNode(arg);
        if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors2 ? effectiveCheckArgumentNode : void 0, effectiveCheckArgumentNode, headMessage, containingMessageChain, errorOutputContainer)) {
          Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
          maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
          return errorOutputContainer.errors || emptyArray;
        }
      }
    }
    if (restType) {
      const spreadType = getSpreadArgumentType(
        args,
        argCount,
        args.length,
        restType,
        /*context*/
        void 0,
        checkMode
      );
      const restArgCount = args.length - argCount;
      const errorNode = !reportErrors2 ? void 0 : restArgCount === 0 ? node : restArgCount === 1 ? getEffectiveCheckNode(args[argCount]) : setTextRangePosEnd(createSyntheticExpression(node, spreadType), args[argCount].pos, args[args.length - 1].end);
      if (!checkTypeRelatedTo(
        spreadType,
        restType,
        relation,
        errorNode,
        headMessage,
        /*containingMessageChain*/
        void 0,
        errorOutputContainer
      )) {
        Debug.assert(!reportErrors2 || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
        maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
        return errorOutputContainer.errors || emptyArray;
      }
    }
    return void 0;
    function maybeAddMissingAwaitInfo(errorNode, source, target) {
      if (errorNode && reportErrors2 && errorOutputContainer.errors && errorOutputContainer.errors.length) {
        if (getAwaitedTypeOfPromise(target)) {
          return;
        }
        const awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
        if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
          addRelatedInfo(errorOutputContainer.errors[0], createDiagnosticForNode(errorNode, Diagnostics.Did_you_forget_to_use_await));
        }
      }
    }
  }
  function getThisArgumentOfCall(node) {
    if (node.kind === 226 /* BinaryExpression */) {
      return node.right;
    }
    const expression = node.kind === 213 /* CallExpression */ ? node.expression : node.kind === 215 /* TaggedTemplateExpression */ ? node.tag : node.kind === 170 /* Decorator */ && !legacyDecorators ? node.expression : void 0;
    if (expression) {
      const callee = skipOuterExpressions(expression);
      if (isAccessExpression(callee)) {
        return callee.expression;
      }
    }
  }
  function createSyntheticExpression(parent, type, isSpread, tupleNameSource) {
    const result = parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
    setTextRange(result, parent);
    setParent(result, parent);
    return result;
  }
  function getEffectiveCallArguments(node) {
    if (isJsxOpeningFragment(node)) {
      return [createSyntheticExpression(node, emptyFreshJsxObjectType)];
    }
    if (node.kind === 215 /* TaggedTemplateExpression */) {
      const template = node.template;
      const args2 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
      if (template.kind === 228 /* TemplateExpression */) {
        forEach(template.templateSpans, (span) => {
          args2.push(span.expression);
        });
      }
      return args2;
    }
    if (node.kind === 170 /* Decorator */) {
      return getEffectiveDecoratorArguments(node);
    }
    if (node.kind === 226 /* BinaryExpression */) {
      return [node.left];
    }
    if (isJsxOpeningLikeElement(node)) {
      return node.attributes.properties.length > 0 || isJsxOpeningElement(node) && node.parent.children.length > 0 ? [node.attributes] : emptyArray;
    }
    const args = node.arguments || emptyArray;
    const spreadIndex = getSpreadArgumentIndex(args);
    if (spreadIndex >= 0) {
      const effectiveArgs = args.slice(0, spreadIndex);
      for (let i = spreadIndex; i < args.length; i++) {
        const arg = args[i];
        const spreadType = arg.kind === 230 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
        if (spreadType && isTupleType(spreadType)) {
          forEach(getElementTypes(spreadType), (t, i2) => {
            var _a;
            const flags = spreadType.target.elementFlags[i2];
            const syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */), (_a = spreadType.target.labeledElementDeclarations) == null ? void 0 : _a[i2]);
            effectiveArgs.push(syntheticArg);
          });
        } else {
          effectiveArgs.push(arg);
        }
      }
      return effectiveArgs;
    }
    return args;
  }
  function getEffectiveDecoratorArguments(node) {
    const expr = node.expression;
    const signature = getDecoratorCallSignature(node);
    if (signature) {
      const args = [];
      for (const param of signature.parameters) {
        const type = getTypeOfSymbol(param);
        args.push(createSyntheticExpression(expr, type));
      }
      return args;
    }
    return Debug.fail();
  }
  function getDecoratorArgumentCount(node, signature) {
    return compilerOptions.experimentalDecorators ? getLegacyDecoratorArgumentCount(node, signature) : (
      // Allow the runtime to oversupply arguments to an ES decorator as long as there's at least one parameter.
      Math.min(Math.max(getParameterCount(signature), 1), 2)
    );
  }
  function getLegacyDecoratorArgumentCount(node, signature) {
    switch (node.parent.kind) {
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
        return 1;
      case 172 /* PropertyDeclaration */:
        return hasAccessorModifier(node.parent) ? 3 : 2;
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return signature.parameters.length <= 2 ? 2 : 3;
      case 169 /* Parameter */:
        return 3;
      default:
        return Debug.fail();
    }
  }
  function getDiagnosticSpanForCallNode(node) {
    const sourceFile = getSourceFileOfNode(node);
    const { start, length: length2 } = getErrorSpanForNode(sourceFile, isPropertyAccessExpression(node.expression) ? node.expression.name : node.expression);
    return { start, length: length2, sourceFile };
  }
  function getDiagnosticForCallNode(node, message, ...args) {
    if (isCallExpression(node)) {
      const { sourceFile, start, length: length2 } = getDiagnosticSpanForCallNode(node);
      if ("message" in message) {
        return createFileDiagnostic(sourceFile, start, length2, message, ...args);
      }
      return createDiagnosticForFileFromMessageChain(sourceFile, message);
    } else {
      if ("message" in message) {
        return createDiagnosticForNode(node, message, ...args);
      }
      return createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), node, message);
    }
  }
  function getErrorNodeForCallNode(callLike) {
    if (isCallOrNewExpression(callLike)) {
      return isPropertyAccessExpression(callLike.expression) ? callLike.expression.name : callLike.expression;
    }
    if (isTaggedTemplateExpression(callLike)) {
      return isPropertyAccessExpression(callLike.tag) ? callLike.tag.name : callLike.tag;
    }
    if (isJsxOpeningLikeElement(callLike)) {
      return callLike.tagName;
    }
    return callLike;
  }
  function isPromiseResolveArityError(node) {
    if (!isCallExpression(node) || !isIdentifier(node.expression)) return false;
    const symbol = resolveName(
      node.expression,
      node.expression.escapedText,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
    const decl = symbol == null ? void 0 : symbol.valueDeclaration;
    if (!decl || !isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !isNewExpression(decl.parent.parent) || !isIdentifier(decl.parent.parent.expression)) {
      return false;
    }
    const globalPromiseSymbol = getGlobalPromiseConstructorSymbol(
      /*reportErrors*/
      false
    );
    if (!globalPromiseSymbol) return false;
    const constructorSymbol = getSymbolAtLocation(
      decl.parent.parent.expression,
      /*ignoreErrors*/
      true
    );
    return constructorSymbol === globalPromiseSymbol;
  }
  function getArgumentArityError(node, signatures, args, headMessage) {
    var _a;
    const spreadIndex = getSpreadArgumentIndex(args);
    if (spreadIndex > -1) {
      return createDiagnosticForNode(args[spreadIndex], Diagnostics.A_spread_argument_must_either_have_a_tuple_type_or_be_passed_to_a_rest_parameter);
    }
    let min2 = Number.POSITIVE_INFINITY;
    let max = Number.NEGATIVE_INFINITY;
    let maxBelow = Number.NEGATIVE_INFINITY;
    let minAbove = Number.POSITIVE_INFINITY;
    let closestSignature;
    for (const sig of signatures) {
      const minParameter = getMinArgumentCount(sig);
      const maxParameter = getParameterCount(sig);
      if (minParameter < min2) {
        min2 = minParameter;
        closestSignature = sig;
      }
      max = Math.max(max, maxParameter);
      if (minParameter < args.length && minParameter > maxBelow) maxBelow = minParameter;
      if (args.length < maxParameter && maxParameter < minAbove) minAbove = maxParameter;
    }
    const hasRestParameter2 = some(signatures, hasEffectiveRestParameter);
    const parameterRange = hasRestParameter2 ? min2 : min2 < max ? min2 + "-" + max : min2;
    const isVoidPromiseError = !hasRestParameter2 && parameterRange === 1 && args.length === 0 && isPromiseResolveArityError(node);
    if (isVoidPromiseError && isInJSFile(node)) {
      return getDiagnosticForCallNode(node, Diagnostics.Expected_1_argument_but_got_0_new_Promise_needs_a_JSDoc_hint_to_produce_a_resolve_that_can_be_called_without_arguments);
    }
    const error2 = isDecorator(node) ? hasRestParameter2 ? Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_at_least_0 : Diagnostics.The_runtime_will_invoke_the_decorator_with_1_arguments_but_the_decorator_expects_0 : hasRestParameter2 ? Diagnostics.Expected_at_least_0_arguments_but_got_1 : isVoidPromiseError ? Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise : Diagnostics.Expected_0_arguments_but_got_1;
    if (min2 < args.length && args.length < max) {
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments,
          args.length,
          maxBelow,
          minAbove
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return getDiagnosticForCallNode(node, chain);
      }
      return getDiagnosticForCallNode(node, Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, args.length, maxBelow, minAbove);
    } else if (args.length < min2) {
      let diagnostic;
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          error2,
          parameterRange,
          args.length
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        diagnostic = getDiagnosticForCallNode(node, chain);
      } else {
        diagnostic = getDiagnosticForCallNode(node, error2, parameterRange, args.length);
      }
      const parameter = (_a = closestSignature == null ? void 0 : closestSignature.declaration) == null ? void 0 : _a.parameters[closestSignature.thisParameter ? args.length + 1 : args.length];
      if (parameter) {
        const messageAndArgs = isBindingPattern(parameter.name) ? [Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided] : isRestParameter(parameter) ? [Diagnostics.Arguments_for_the_rest_parameter_0_were_not_provided, idText(getFirstIdentifier(parameter.name))] : [Diagnostics.An_argument_for_0_was_not_provided, !parameter.name ? args.length : idText(getFirstIdentifier(parameter.name))];
        const parameterError = createDiagnosticForNode(parameter, ...messageAndArgs);
        return addRelatedInfo(diagnostic, parameterError);
      }
      return diagnostic;
    } else {
      const errorSpan = factory.createNodeArray(args.slice(max));
      const pos = first(errorSpan).pos;
      let end = last(errorSpan).end;
      if (end === pos) {
        end++;
      }
      setTextRangePosEnd(errorSpan, pos, end);
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          error2,
          parameterRange,
          args.length
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), errorSpan, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), errorSpan, error2, parameterRange, args.length);
    }
  }
  function getTypeArgumentArityError(node, signatures, typeArguments, headMessage) {
    const argCount = typeArguments.length;
    if (signatures.length === 1) {
      const sig = signatures[0];
      const min2 = getMinTypeArgumentCount(sig.typeParameters);
      const max = length(sig.typeParameters);
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.Expected_0_type_arguments_but_got_1,
          min2 < max ? min2 + "-" + max : min2,
          argCount
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, min2 < max ? min2 + "-" + max : min2, argCount);
    }
    let belowArgCount = -Infinity;
    let aboveArgCount = Infinity;
    for (const sig of signatures) {
      const min2 = getMinTypeArgumentCount(sig.typeParameters);
      const max = length(sig.typeParameters);
      if (min2 > argCount) {
        aboveArgCount = Math.min(aboveArgCount, min2);
      } else if (max < argCount) {
        belowArgCount = Math.max(belowArgCount, max);
      }
    }
    if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
      if (headMessage) {
        let chain = chainDiagnosticMessages(
          /*details*/
          void 0,
          Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments,
          argCount,
          belowArgCount,
          aboveArgCount
        );
        chain = chainDiagnosticMessages(chain, headMessage);
        return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain);
      }
      return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.No_overload_expects_0_type_arguments_but_overloads_do_exist_that_expect_either_1_or_2_type_arguments, argCount, belowArgCount, aboveArgCount);
    }
    if (headMessage) {
      let chain = chainDiagnosticMessages(
        /*details*/
        void 0,
        Diagnostics.Expected_0_type_arguments_but_got_1,
        belowArgCount === -Infinity ? aboveArgCount : belowArgCount,
        argCount
      );
      chain = chainDiagnosticMessages(chain, headMessage);
      return createDiagnosticForNodeArrayFromMessageChain(getSourceFileOfNode(node), typeArguments, chain);
    }
    return createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
  }
  function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, headMessage) {
    const isTaggedTemplate = node.kind === 215 /* TaggedTemplateExpression */;
    const isDecorator2 = node.kind === 170 /* Decorator */;
    const isJsxOpeningOrSelfClosingElement = isJsxOpeningLikeElement(node);
    const isJsxOpenFragment = isJsxOpeningFragment(node);
    const isInstanceof = node.kind === 226 /* BinaryExpression */;
    const reportErrors2 = !isInferencePartiallyBlocked && !candidatesOutArray;
    let candidatesForArgumentError;
    let candidateForArgumentArityError;
    let candidateForTypeArgumentError;
    let result;
    let argCheckMode = 0 /* Normal */;
    let candidates = [];
    let typeArguments;
    if (!isDecorator2 && !isInstanceof && !isSuperCall(node) && !isJsxOpenFragment) {
      typeArguments = node.typeArguments;
      if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 108 /* SuperKeyword */) {
        forEach(typeArguments, checkSourceElement);
      }
    }
    candidates = candidatesOutArray || [];
    reorderCandidates(signatures, candidates, callChainFlags);
    if (!isJsxOpenFragment) {
      Debug.assert(candidates.length, "Revert #54442 and add a testcase with whatever triggered this");
    }
    const args = getEffectiveCallArguments(node);
    const isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
    if (!isDecorator2 && !isSingleNonGenericCandidate && some(args, isContextSensitive)) {
      argCheckMode = 4 /* SkipContextSensitive */;
    }
    const signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 213 /* CallExpression */ && node.arguments.hasTrailingComma;
    if (candidates.length > 1) {
      result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
    }
    if (!result) {
      result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
    }
    if (result) {
      return result;
    }
    result = getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray, checkMode);
    getNodeLinks(node).resolvedSignature = result;
    if (reportErrors2) {
      if (!headMessage && isInstanceof) {
        headMessage = Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_assignable_to_the_first_argument_of_the_right_hand_side_s_Symbol_hasInstance_method;
      }
      if (candidatesForArgumentError) {
        if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
          const last2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
          let chain;
          if (candidatesForArgumentError.length > 3) {
            chain = chainDiagnosticMessages(chain, Diagnostics.The_last_overload_gave_the_following_error);
            chain = chainDiagnosticMessages(chain, Diagnostics.No_overload_matches_this_call);
          }
          if (headMessage) {
            chain = chainDiagnosticMessages(chain, headMessage);
          }
          const diags = getSignatureApplicabilityError(
            node,
            args,
            last2,
            assignableRelation,
            0 /* Normal */,
            /*reportErrors*/
            true,
            () => chain,
            /*inferenceContext*/
            void 0
          );
          if (diags) {
            for (const d of diags) {
              if (last2.declaration && candidatesForArgumentError.length > 3) {
                addRelatedInfo(d, createDiagnosticForNode(last2.declaration, Diagnostics.The_last_overload_is_declared_here));
              }
              addImplementationSuccessElaboration(last2, d);
              diagnostics.add(d);
            }
          } else {
            Debug.fail("No error for last overload signature");
          }
        } else {
          const allDiagnostics = [];
          let max = 0;
          let min2 = Number.MAX_VALUE;
          let minIndex = 0;
          let i = 0;
          for (const c of candidatesForArgumentError) {
            const chain2 = () => chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.Overload_0_of_1_2_gave_the_following_error,
              i + 1,
              candidates.length,
              signatureToString(c)
            );
            const diags2 = getSignatureApplicabilityError(
              node,
              args,
              c,
              assignableRelation,
              0 /* Normal */,
              /*reportErrors*/
              true,
              chain2,
              /*inferenceContext*/
              void 0
            );
            if (diags2) {
              if (diags2.length <= min2) {
                min2 = diags2.length;
                minIndex = i;
              }
              max = Math.max(max, diags2.length);
              allDiagnostics.push(diags2);
            } else {
              Debug.fail("No error for 3 or fewer overload signatures");
            }
            i++;
          }
          const diags = max > 1 ? allDiagnostics[minIndex] : flatten(allDiagnostics);
          Debug.assert(diags.length > 0, "No errors reported for 3 or fewer overload signatures");
          let chain = chainDiagnosticMessages(
            map(diags, createDiagnosticMessageChainFromDiagnostic),
            Diagnostics.No_overload_matches_this_call
          );
          if (headMessage) {
            chain = chainDiagnosticMessages(chain, headMessage);
          }
          const related = [...flatMap(diags, (d) => d.relatedInformation)];
          let diag2;
          if (every(diags, (d) => d.start === diags[0].start && d.length === diags[0].length && d.file === diags[0].file)) {
            const { file, start, length: length2 } = diags[0];
            diag2 = { file, start, length: length2, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
          } else {
            diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node), getErrorNodeForCallNode(node), chain, related);
          }
          addImplementationSuccessElaboration(candidatesForArgumentError[0], diag2);
          diagnostics.add(diag2);
        }
      } else if (candidateForArgumentArityError) {
        diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args, headMessage));
      } else if (candidateForTypeArgumentError) {
        checkTypeArguments(
          candidateForTypeArgumentError,
          node.typeArguments,
          /*reportErrors*/
          true,
          headMessage
        );
      } else if (!isJsxOpenFragment) {
        const signaturesWithCorrectTypeArgumentArity = filter(signatures, (s) => hasCorrectTypeArgumentArity(s, typeArguments));
        if (signaturesWithCorrectTypeArgumentArity.length === 0) {
          diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments, headMessage));
        } else {
          diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args, headMessage));
        }
      }
    }
    return result;
    function addImplementationSuccessElaboration(failed2, diagnostic) {
      var _a, _b;
      const oldCandidatesForArgumentError = candidatesForArgumentError;
      const oldCandidateForArgumentArityError = candidateForArgumentArityError;
      const oldCandidateForTypeArgumentError = candidateForTypeArgumentError;
      const failedSignatureDeclarations = ((_b = (_a = failed2.declaration) == null ? void 0 : _a.symbol) == null ? void 0 : _b.declarations) || emptyArray;
      const isOverload = failedSignatureDeclarations.length > 1;
      const implDecl = isOverload ? find(failedSignatureDeclarations, (d) => isFunctionLikeDeclaration(d) && nodeIsPresent(d.body)) : void 0;
      if (implDecl) {
        const candidate = getSignatureFromDeclaration(implDecl);
        const isSingleNonGenericCandidate2 = !candidate.typeParameters;
        if (chooseOverload([candidate], assignableRelation, isSingleNonGenericCandidate2)) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(implDecl, Diagnostics.The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible));
        }
      }
      candidatesForArgumentError = oldCandidatesForArgumentError;
      candidateForArgumentArityError = oldCandidateForArgumentArityError;
      candidateForTypeArgumentError = oldCandidateForTypeArgumentError;
    }
    function chooseOverload(candidates2, relation, isSingleNonGenericCandidate2, signatureHelpTrailingComma2 = false) {
      var _a, _b;
      candidatesForArgumentError = void 0;
      candidateForArgumentArityError = void 0;
      candidateForTypeArgumentError = void 0;
      if (isSingleNonGenericCandidate2) {
        const candidate = candidates2[0];
        if (some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma2)) {
          return void 0;
        }
        if (getSignatureApplicabilityError(
          node,
          args,
          candidate,
          relation,
          0 /* Normal */,
          /*reportErrors*/
          false,
          /*containingMessageChain*/
          void 0,
          /*inferenceContext*/
          void 0
        )) {
          candidatesForArgumentError = [candidate];
          return void 0;
        }
        return candidate;
      }
      for (let candidateIndex = 0; candidateIndex < candidates2.length; candidateIndex++) {
        let candidate = candidates2[candidateIndex];
        if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma2)) {
          continue;
        }
        let checkCandidate;
        let inferenceContext;
        if (candidate.typeParameters) {
          const paramLocation = (_b = (_a = candidate.typeParameters[0].symbol.declarations) == null ? void 0 : _a[0]) == null ? void 0 : _b.parent;
          const candidateParameterContext = paramLocation || (candidate.declaration && isConstructorDeclaration(candidate.declaration) ? candidate.declaration.parent : candidate.declaration);
          if (candidateParameterContext && findAncestor(node, (a) => a === candidateParameterContext)) {
            candidate = getImplementationSignature(candidate);
          }
          let typeArgumentTypes;
          if (some(typeArguments)) {
            typeArgumentTypes = checkTypeArguments(
              candidate,
              typeArguments,
              /*reportErrors*/
              false
            );
            if (!typeArgumentTypes) {
              candidateForTypeArgumentError = candidate;
              continue;
            }
          } else {
            inferenceContext = createInferenceContext(
              candidate.typeParameters,
              candidate,
              /*flags*/
              isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */
            );
            typeArgumentTypes = instantiateTypes(inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext), inferenceContext.nonFixingMapper);
            argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
          }
          checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
          if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma2)) {
            candidateForArgumentArityError = checkCandidate;
            continue;
          }
        } else {
          checkCandidate = candidate;
        }
        if (getSignatureApplicabilityError(
          node,
          args,
          checkCandidate,
          relation,
          argCheckMode,
          /*reportErrors*/
          false,
          /*containingMessageChain*/
          void 0,
          inferenceContext
        )) {
          (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
          continue;
        }
        if (argCheckMode) {
          argCheckMode = 0 /* Normal */;
          if (inferenceContext) {
            const typeArgumentTypes = instantiateTypes(inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext), inferenceContext.mapper);
            checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, isInJSFile(candidate.declaration), inferenceContext.inferredTypeParameters);
            if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma2)) {
              candidateForArgumentArityError = checkCandidate;
              continue;
            }
          }
          if (getSignatureApplicabilityError(
            node,
            args,
            checkCandidate,
            relation,
            argCheckMode,
            /*reportErrors*/
            false,
            /*containingMessageChain*/
            void 0,
            inferenceContext
          )) {
            (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
            continue;
          }
        }
        candidates2[candidateIndex] = checkCandidate;
        return checkCandidate;
      }
      return void 0;
    }
  }
  function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray, checkMode) {
    Debug.assert(candidates.length > 0);
    checkNodeDeferred(node);
    return hasCandidatesOutArray || candidates.length === 1 || candidates.some((c) => !!c.typeParameters) ? pickLongestCandidateSignature(node, candidates, args, checkMode) : createUnionOfSignaturesForOverloadFailure(candidates);
  }
  function createUnionOfSignaturesForOverloadFailure(candidates) {
    const thisParameters = mapDefined(candidates, (c) => c.thisParameter);
    let thisParameter;
    if (thisParameters.length) {
      thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
    }
    const { min: minArgumentCount, max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters);
    const parameters = [];
    for (let i = 0; i < maxNonRestParam; i++) {
      const symbols = mapDefined(candidates, (s) => signatureHasRestParameter(s) ? i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : i < s.parameters.length ? s.parameters[i] : void 0);
      Debug.assert(symbols.length !== 0);
      parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, (candidate) => tryGetTypeAtPosition(candidate, i))));
    }
    const restParameterSymbols = mapDefined(candidates, (c) => signatureHasRestParameter(c) ? last(c.parameters) : void 0);
    let flags = 128 /* IsSignatureCandidateForOverloadFailure */;
    if (restParameterSymbols.length !== 0) {
      const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
      parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
      flags |= 1 /* HasRestParameter */;
    }
    if (candidates.some(signatureHasLiteralTypes)) {
      flags |= 2 /* HasLiteralTypes */;
    }
    return createSignature(
      candidates[0].declaration,
      /*typeParameters*/
      void 0,
      // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
      thisParameter,
      parameters,
      /*resolvedReturnType*/
      getIntersectionType(candidates.map(getReturnTypeOfSignature)),
      /*resolvedTypePredicate*/
      void 0,
      minArgumentCount,
      flags
    );
  }
  function getNumNonRestParameters(signature) {
    const numParams = signature.parameters.length;
    return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
  }
  function createCombinedSymbolFromTypes(sources, types) {
    return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
  }
  function createCombinedSymbolForOverloadFailure(sources, type) {
    return createSymbolWithType(first(sources), type);
  }
  function pickLongestCandidateSignature(node, candidates, args, checkMode) {
    const bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === void 0 ? args.length : apparentArgumentCount);
    const candidate = candidates[bestIndex];
    const { typeParameters } = candidate;
    if (!typeParameters) {
      return candidate;
    }
    const typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : void 0;
    const instantiated = typeArgumentNodes ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isInJSFile(node))) : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode);
    candidates[bestIndex] = instantiated;
    return instantiated;
  }
  function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
    const typeArguments = typeArgumentNodes.map(getTypeOfNode);
    while (typeArguments.length > typeParameters.length) {
      typeArguments.pop();
    }
    while (typeArguments.length < typeParameters.length) {
      typeArguments.push(getDefaultFromTypeParameter(typeParameters[typeArguments.length]) || getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
    }
    return typeArguments;
  }
  function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args, checkMode) {
    const inferenceContext = createInferenceContext(
      typeParameters,
      candidate,
      /*flags*/
      isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */
    );
    const typeArgumentTypes = inferTypeArguments(node, candidate, args, checkMode | 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
    return createSignatureInstantiation(candidate, typeArgumentTypes);
  }
  function getLongestCandidateIndex(candidates, argsCount) {
    let maxParamsIndex = -1;
    let maxParams = -1;
    for (let i = 0; i < candidates.length; i++) {
      const candidate = candidates[i];
      const paramCount = getParameterCount(candidate);
      if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
        return i;
      }
      if (paramCount > maxParams) {
        maxParams = paramCount;
        maxParamsIndex = i;
      }
    }
    return maxParamsIndex;
  }
  function resolveCallExpression(node, candidatesOutArray, checkMode) {
    if (node.expression.kind === 108 /* SuperKeyword */) {
      const superType = checkSuperExpression(node.expression);
      if (isTypeAny(superType)) {
        for (const arg of node.arguments) {
          checkExpression(arg);
        }
        return anySignature;
      }
      if (!isErrorType(superType)) {
        const baseTypeNode = getEffectiveBaseTypeNode(getContainingClass(node));
        if (baseTypeNode) {
          const baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
          return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
        }
      }
      return resolveUntypedCall(node);
    }
    let callChainFlags;
    let funcType = checkExpression(node.expression);
    if (isCallChain(node)) {
      const nonOptionalType = getOptionalExpressionType(funcType, node.expression);
      callChainFlags = nonOptionalType === funcType ? 0 /* None */ : isOutermostOptionalChain(node) ? 16 /* IsOuterCallChain */ : 8 /* IsInnerCallChain */;
      funcType = nonOptionalType;
    } else {
      callChainFlags = 0 /* None */;
    }
    funcType = checkNonNullTypeWithReporter(
      funcType,
      node.expression,
      reportCannotInvokePossiblyNullOrUndefinedError
    );
    if (funcType === silentNeverType) {
      return silentNeverSignature;
    }
    const apparentType = getApparentType(funcType);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
    const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
    if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
      if (!isErrorType(funcType) && node.typeArguments) {
        error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
      }
      return resolveUntypedCall(node);
    }
    if (!callSignatures.length) {
      if (numConstructSignatures) {
        error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
      } else {
        let relatedInformation;
        if (node.arguments.length === 1) {
          const text = getSourceFileOfNode(node).text;
          if (isLineBreak(text.charCodeAt(skipTrivia(
            text,
            node.expression.end,
            /*stopAfterLineBreak*/
            true
          ) - 1))) {
            relatedInformation = createDiagnosticForNode(node.expression, Diagnostics.Are_you_missing_a_semicolon);
          }
        }
        invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
      }
      return resolveErrorCall(node);
    }
    if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
      skippedGenericFunction(node, checkMode);
      return resolvingSignature;
    }
    if (callSignatures.some((sig) => isInJSFile(sig.declaration) && !!getJSDocClassTag(sig.declaration))) {
      error(node, Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
  }
  function isGenericFunctionReturningFunction(signature) {
    return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
  }
  function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
    return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) || !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & 1048576 /* Union */) && !(getReducedType(apparentFuncType).flags & 131072 /* Never */) && isTypeAssignableTo(funcType, globalFunctionType);
  }
  function resolveNewExpression(node, candidatesOutArray, checkMode) {
    let expressionType = checkNonNullExpression(node.expression);
    if (expressionType === silentNeverType) {
      return silentNeverSignature;
    }
    expressionType = getApparentType(expressionType);
    if (isErrorType(expressionType)) {
      return resolveErrorCall(node);
    }
    if (isTypeAny(expressionType)) {
      if (node.typeArguments) {
        error(node, Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
      }
      return resolveUntypedCall(node);
    }
    const constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
    if (constructSignatures.length) {
      if (!isConstructorAccessible(node, constructSignatures[0])) {
        return resolveErrorCall(node);
      }
      if (someSignature(constructSignatures, (signature) => !!(signature.flags & 4 /* Abstract */))) {
        error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
        return resolveErrorCall(node);
      }
      const valueDecl = expressionType.symbol && getClassLikeDeclarationOfSymbol(expressionType.symbol);
      if (valueDecl && hasSyntacticModifier(valueDecl, 64 /* Abstract */)) {
        error(node, Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
        return resolveErrorCall(node);
      }
      return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
    }
    const callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
    if (callSignatures.length) {
      const signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
      if (!noImplicitAny) {
        if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
          error(node, Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
        }
        if (getThisTypeOfSignature(signature) === voidType) {
          error(node, Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
        }
      }
      return signature;
    }
    invocationError(node.expression, expressionType, 1 /* Construct */);
    return resolveErrorCall(node);
  }
  function someSignature(signatures, f) {
    if (isArray(signatures)) {
      return some(signatures, (signature) => someSignature(signature, f));
    }
    return signatures.compositeKind === 1048576 /* Union */ ? some(signatures.compositeSignatures, f) : f(signatures);
  }
  function typeHasProtectedAccessibleBase(target, type) {
    const baseTypes = getBaseTypes(type);
    if (!length(baseTypes)) {
      return false;
    }
    const firstBase = baseTypes[0];
    if (firstBase.flags & 2097152 /* Intersection */) {
      const types = firstBase.types;
      const mixinFlags = findMixins(types);
      let i = 0;
      for (const intersectionMember of firstBase.types) {
        if (!mixinFlags[i]) {
          if (getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
            if (intersectionMember.symbol === target) {
              return true;
            }
            if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
              return true;
            }
          }
        }
        i++;
      }
      return false;
    }
    if (firstBase.symbol === target) {
      return true;
    }
    return typeHasProtectedAccessibleBase(target, firstBase);
  }
  function isConstructorAccessible(node, signature) {
    if (!signature || !signature.declaration) {
      return true;
    }
    const declaration = signature.declaration;
    const modifiers = getSelectedEffectiveModifierFlags(declaration, 6 /* NonPublicAccessibilityModifier */);
    if (!modifiers || declaration.kind !== 176 /* Constructor */) {
      return true;
    }
    const declaringClassDeclaration = getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
    const declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
    if (!isNodeWithinClass(node, declaringClassDeclaration)) {
      const containingClass = getContainingClass(node);
      if (containingClass && modifiers & 4 /* Protected */) {
        const containingType = getTypeOfNode(containingClass);
        if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
          return true;
        }
      }
      if (modifiers & 2 /* Private */) {
        error(node, Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
      }
      if (modifiers & 4 /* Protected */) {
        error(node, Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
      }
      return false;
    }
    return true;
  }
  function invocationErrorDetails(errorTarget, apparentType, kind) {
    let errorInfo;
    const isCall = kind === 0 /* Call */;
    const awaitedType = getAwaitedType(apparentType);
    const maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
    if (apparentType.flags & 1048576 /* Union */) {
      const types = apparentType.types;
      let hasSignatures = false;
      for (const constituent of types) {
        const signatures = getSignaturesOfType(constituent, kind);
        if (signatures.length !== 0) {
          hasSignatures = true;
          if (errorInfo) {
            break;
          }
        } else {
          if (!errorInfo) {
            errorInfo = chainDiagnosticMessages(
              errorInfo,
              isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures,
              typeToString(constituent)
            );
            errorInfo = chainDiagnosticMessages(
              errorInfo,
              isCall ? Diagnostics.Not_all_constituents_of_type_0_are_callable : Diagnostics.Not_all_constituents_of_type_0_are_constructable,
              typeToString(apparentType)
            );
          }
          if (hasSignatures) {
            break;
          }
        }
      }
      if (!hasSignatures) {
        errorInfo = chainDiagnosticMessages(
          /*details*/
          void 0,
          isCall ? Diagnostics.No_constituent_of_type_0_is_callable : Diagnostics.No_constituent_of_type_0_is_constructable,
          typeToString(apparentType)
        );
      }
      if (!errorInfo) {
        errorInfo = chainDiagnosticMessages(
          errorInfo,
          isCall ? Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other : Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other,
          typeToString(apparentType)
        );
      }
    } else {
      errorInfo = chainDiagnosticMessages(
        errorInfo,
        isCall ? Diagnostics.Type_0_has_no_call_signatures : Diagnostics.Type_0_has_no_construct_signatures,
        typeToString(apparentType)
      );
    }
    let headMessage = isCall ? Diagnostics.This_expression_is_not_callable : Diagnostics.This_expression_is_not_constructable;
    if (isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) {
      const { resolvedSymbol } = getNodeLinks(errorTarget);
      if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) {
        headMessage = Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without;
      }
    }
    return {
      messageChain: chainDiagnosticMessages(errorInfo, headMessage),
      relatedMessage: maybeMissingAwait ? Diagnostics.Did_you_forget_to_use_await : void 0
    };
  }
  function invocationError(errorTarget, apparentType, kind, relatedInformation) {
    const { messageChain, relatedMessage: relatedInfo } = invocationErrorDetails(errorTarget, apparentType, kind);
    const diagnostic = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorTarget), errorTarget, messageChain);
    if (relatedInfo) {
      addRelatedInfo(diagnostic, createDiagnosticForNode(errorTarget, relatedInfo));
    }
    if (isCallExpression(errorTarget.parent)) {
      const { start, length: length2 } = getDiagnosticSpanForCallNode(errorTarget.parent);
      diagnostic.start = start;
      diagnostic.length = length2;
    }
    diagnostics.add(diagnostic);
    invocationErrorRecovery(apparentType, kind, relatedInformation ? addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
  }
  function invocationErrorRecovery(apparentType, kind, diagnostic) {
    if (!apparentType.symbol) {
      return;
    }
    const importNode = getSymbolLinks(apparentType.symbol).originatingImport;
    if (importNode && !isImportCall(importNode)) {
      const sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
      if (!sigs || !sigs.length) return;
      addRelatedInfo(diagnostic, createDiagnosticForNode(importNode, Diagnostics.Type_originates_at_this_import_A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_Consider_using_a_default_import_or_import_require_here_instead));
    }
  }
  function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
    const tagType = checkExpression(node.tag);
    const apparentType = getApparentType(tagType);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
    const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
    if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
      return resolveUntypedCall(node);
    }
    if (!callSignatures.length) {
      if (isArrayLiteralExpression(node.parent)) {
        const diagnostic = createDiagnosticForNode(node.tag, Diagnostics.It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked);
        diagnostics.add(diagnostic);
        return resolveErrorCall(node);
      }
      invocationError(node.tag, apparentType, 0 /* Call */);
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
  }
  function getDiagnosticHeadMessageForDecoratorResolution(node) {
    switch (node.parent.kind) {
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
        return Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
      case 169 /* Parameter */:
        return Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
      case 172 /* PropertyDeclaration */:
        return Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
      default:
        return Debug.fail();
    }
  }
  function resolveDecorator(node, candidatesOutArray, checkMode) {
    const funcType = checkExpression(node.expression);
    const apparentType = getApparentType(funcType);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
    const numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
    if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
      return resolveUntypedCall(node);
    }
    if (isPotentiallyUncalledDecorator(node, callSignatures) && !isParenthesizedExpression(node.expression)) {
      const nodeStr = getTextOfNode(
        node.expression,
        /*includeTrivia*/
        false
      );
      error(node, Diagnostics._0_accepts_too_few_arguments_to_be_used_as_a_decorator_here_Did_you_mean_to_call_it_first_and_write_0, nodeStr);
      return resolveErrorCall(node);
    }
    const headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
    if (!callSignatures.length) {
      const errorDetails = invocationErrorDetails(node.expression, apparentType, 0 /* Call */);
      const messageChain = chainDiagnosticMessages(errorDetails.messageChain, headMessage);
      const diag2 = createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(node.expression), node.expression, messageChain);
      if (errorDetails.relatedMessage) {
        addRelatedInfo(diag2, createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
      }
      diagnostics.add(diag2);
      invocationErrorRecovery(apparentType, 0 /* Call */, diag2);
      return resolveErrorCall(node);
    }
    return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
  }
  function createSignatureForJSXIntrinsic(node, result) {
    const namespace = getJsxNamespaceAt(node);
    const exports2 = namespace && getExportsOfSymbol(namespace);
    const typeSymbol = exports2 && getSymbol(exports2, JsxNames.Element, 788968 /* Type */);
    const returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
    const declaration = factory.createFunctionTypeNode(
      /*typeParameters*/
      void 0,
      [factory.createParameterDeclaration(
        /*modifiers*/
        void 0,
        /*dotDotDotToken*/
        void 0,
        "props",
        /*questionToken*/
        void 0,
        nodeBuilder.typeToTypeNode(result, node)
      )],
      returnNode ? factory.createTypeReferenceNode(
        returnNode,
        /*typeArguments*/
        void 0
      ) : factory.createKeywordTypeNode(133 /* AnyKeyword */)
    );
    const parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
    parameterSymbol.links.type = result;
    return createSignature(
      declaration,
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [parameterSymbol],
      typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType,
      /*resolvedTypePredicate*/
      void 0,
      1,
      0 /* None */
    );
  }
  function getJSXFragmentType(node) {
    const sourceFileLinks = getNodeLinks(getSourceFileOfNode(node));
    if (sourceFileLinks.jsxFragmentType !== void 0) return sourceFileLinks.jsxFragmentType;
    const jsxFragmentFactoryName = getJsxNamespace(node);
    const shouldResolveFactoryReference = (compilerOptions.jsx === 2 /* React */ || compilerOptions.jsxFragmentFactory !== void 0) && jsxFragmentFactoryName !== "null";
    if (!shouldResolveFactoryReference) return sourceFileLinks.jsxFragmentType = anyType;
    const shouldModuleRefErr = compilerOptions.jsx !== 1 /* Preserve */ && compilerOptions.jsx !== 3 /* ReactNative */;
    const jsxFactoryRefErr = diagnostics ? Diagnostics.Using_JSX_fragments_requires_fragment_factory_0_to_be_in_scope_but_it_could_not_be_found : void 0;
    const jsxFactorySymbol = getJsxNamespaceContainerForImplicitImport(node) ?? resolveName(
      node,
      jsxFragmentFactoryName,
      shouldModuleRefErr ? 111551 /* Value */ : 111551 /* Value */ & ~384 /* Enum */,
      /*nameNotFoundMessage*/
      jsxFactoryRefErr,
      /*isUse*/
      true
    );
    if (jsxFactorySymbol === void 0) return sourceFileLinks.jsxFragmentType = errorType;
    if (jsxFactorySymbol.escapedName === ReactNames.Fragment) return sourceFileLinks.jsxFragmentType = getTypeOfSymbol(jsxFactorySymbol);
    const resolvedAlias = (jsxFactorySymbol.flags & 2097152 /* Alias */) === 0 ? jsxFactorySymbol : resolveAlias(jsxFactorySymbol);
    const reactExports = jsxFactorySymbol && getExportsOfSymbol(resolvedAlias);
    const typeSymbol = reactExports && getSymbol(reactExports, ReactNames.Fragment, 2 /* BlockScopedVariable */);
    const type = typeSymbol && getTypeOfSymbol(typeSymbol);
    return sourceFileLinks.jsxFragmentType = type === void 0 ? errorType : type;
  }
  function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
    const isJsxOpenFragment = isJsxOpeningFragment(node);
    let exprTypes;
    if (!isJsxOpenFragment) {
      if (isJsxIntrinsicTagName(node.tagName)) {
        const result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
        const fakeSignature = createSignatureForJSXIntrinsic(node, result);
        checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(
          node.attributes,
          getEffectiveFirstArgumentForJsxSignature(fakeSignature, node),
          /*inferenceContext*/
          void 0,
          0 /* Normal */
        ), result, node.tagName, node.attributes);
        if (length(node.typeArguments)) {
          forEach(node.typeArguments, checkSourceElement);
          diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), node.typeArguments, Diagnostics.Expected_0_type_arguments_but_got_1, 0, length(node.typeArguments)));
        }
        return fakeSignature;
      }
      exprTypes = checkExpression(node.tagName);
    } else {
      exprTypes = getJSXFragmentType(node);
    }
    const apparentType = getApparentType(exprTypes);
    if (isErrorType(apparentType)) {
      return resolveErrorCall(node);
    }
    const signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
    if (isUntypedFunctionCall(
      exprTypes,
      apparentType,
      signatures.length,
      /*constructSignatures*/
      0
    )) {
      return resolveUntypedCall(node);
    }
    if (signatures.length === 0) {
      if (isJsxOpenFragment) {
        error(node, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node));
      } else {
        error(node.tagName, Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, getTextOfNode(node.tagName));
      }
      return resolveErrorCall(node);
    }
    return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
  }
  function resolveInstanceofExpression(node, candidatesOutArray, checkMode) {
    const rightType = checkExpression(node.right);
    if (!isTypeAny(rightType)) {
      const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(rightType);
      if (hasInstanceMethodType) {
        const apparentType = getApparentType(hasInstanceMethodType);
        if (isErrorType(apparentType)) {
          return resolveErrorCall(node);
        }
        const callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
        const constructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */);
        if (isUntypedFunctionCall(hasInstanceMethodType, apparentType, callSignatures.length, constructSignatures.length)) {
          return resolveUntypedCall(node);
        }
        if (callSignatures.length) {
          return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
        }
      } else if (!(typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
        error(node.right, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_be_either_of_type_any_a_class_function_or_other_type_assignable_to_the_Function_interface_type_or_an_object_type_with_a_Symbol_hasInstance_method);
        return resolveErrorCall(node);
      }
    }
    return anySignature;
  }
  function isPotentiallyUncalledDecorator(decorator, signatures) {
    return signatures.length && every(signatures, (signature) => signature.minArgumentCount === 0 && !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature));
  }
  function resolveSignature(node, candidatesOutArray, checkMode) {
    switch (node.kind) {
      case 213 /* CallExpression */:
        return resolveCallExpression(node, candidatesOutArray, checkMode);
      case 214 /* NewExpression */:
        return resolveNewExpression(node, candidatesOutArray, checkMode);
      case 215 /* TaggedTemplateExpression */:
        return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
      case 170 /* Decorator */:
        return resolveDecorator(node, candidatesOutArray, checkMode);
      case 289 /* JsxOpeningFragment */:
      case 286 /* JsxOpeningElement */:
      case 285 /* JsxSelfClosingElement */:
        return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
      case 226 /* BinaryExpression */:
        return resolveInstanceofExpression(node, candidatesOutArray, checkMode);
    }
    Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
  }
  function getResolvedSignature(node, candidatesOutArray, checkMode) {
    const links = getNodeLinks(node);
    const cached = links.resolvedSignature;
    if (cached && cached !== resolvingSignature && !candidatesOutArray) {
      return cached;
    }
    const saveResolutionStart = resolutionStart;
    if (!cached) {
      resolutionStart = resolutionTargets.length;
    }
    links.resolvedSignature = resolvingSignature;
    let result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
    resolutionStart = saveResolutionStart;
    if (result !== resolvingSignature) {
      if (links.resolvedSignature !== resolvingSignature) {
        result = links.resolvedSignature;
      }
      links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
    }
    return result;
  }
  function isJSConstructor(node) {
    var _a;
    if (!node || !isInJSFile(node)) {
      return false;
    }
    const func = isFunctionDeclaration(node) || isFunctionExpression(node) ? node : (isVariableDeclaration(node) || isPropertyAssignment(node)) && node.initializer && isFunctionExpression(node.initializer) ? node.initializer : void 0;
    if (func) {
      if (getJSDocClassTag(node)) return true;
      if (isPropertyAssignment(walkUpParenthesizedExpressions(func.parent))) return false;
      const symbol = getSymbolOfDeclaration(func);
      return !!((_a = symbol == null ? void 0 : symbol.members) == null ? void 0 : _a.size);
    }
    return false;
  }
  function mergeJSSymbols(target, source) {
    var _a, _b;
    if (source) {
      const links = getSymbolLinks(source);
      if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) {
        const inferred = isTransientSymbol(target) ? target : cloneSymbol(target);
        inferred.exports = inferred.exports || createSymbolTable();
        inferred.members = inferred.members || createSymbolTable();
        inferred.flags |= source.flags & 32 /* Class */;
        if ((_a = source.exports) == null ? void 0 : _a.size) {
          mergeSymbolTable(inferred.exports, source.exports);
        }
        if ((_b = source.members) == null ? void 0 : _b.size) {
          mergeSymbolTable(inferred.members, source.members);
        }
        (links.inferredClassSymbol || (links.inferredClassSymbol = /* @__PURE__ */ new Map())).set(getSymbolId(inferred), inferred);
        return inferred;
      }
      return links.inferredClassSymbol.get(getSymbolId(target));
    }
  }
  function getAssignedClassSymbol(decl) {
    var _a;
    const assignmentSymbol = decl && getSymbolOfExpando(
      decl,
      /*allowDeclaration*/
      true
    );
    const prototype = (_a = assignmentSymbol == null ? void 0 : assignmentSymbol.exports) == null ? void 0 : _a.get("prototype");
    const init = (prototype == null ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration);
    return init ? getSymbolOfDeclaration(init) : void 0;
  }
  function getSymbolOfExpando(node, allowDeclaration) {
    if (!node.parent) {
      return void 0;
    }
    let name;
    let decl;
    if (isVariableDeclaration(node.parent) && node.parent.initializer === node) {
      if (!isInJSFile(node) && !(isVarConstLike2(node.parent) && isFunctionLikeDeclaration(node))) {
        return void 0;
      }
      name = node.parent.name;
      decl = node.parent;
    } else if (isBinaryExpression(node.parent)) {
      const parentNode = node.parent;
      const parentNodeOperator = node.parent.operatorToken.kind;
      if (parentNodeOperator === 64 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) {
        name = parentNode.left;
        decl = name;
      } else if (parentNodeOperator === 57 /* BarBarToken */ || parentNodeOperator === 61 /* QuestionQuestionToken */) {
        if (isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
          name = parentNode.parent.name;
          decl = parentNode.parent;
        } else if (isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 64 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) {
          name = parentNode.parent.left;
          decl = name;
        }
        if (!name || !isBindableStaticNameExpression(name) || !isSameEntityName(name, parentNode.left)) {
          return void 0;
        }
      }
    } else if (allowDeclaration && isFunctionDeclaration(node)) {
      name = node.name;
      decl = node;
    }
    if (!decl || !name || !allowDeclaration && !getExpandoInitializer(node, isPrototypeAccess(name))) {
      return void 0;
    }
    return getSymbolOfNode(decl);
  }
  function getAssignedJSPrototype(node) {
    if (!node.parent) {
      return false;
    }
    let parent = node.parent;
    while (parent && parent.kind === 211 /* PropertyAccessExpression */) {
      parent = parent.parent;
    }
    if (parent && isBinaryExpression(parent) && isPrototypeAccess(parent.left) && parent.operatorToken.kind === 64 /* EqualsToken */) {
      const right = getInitializerOfBinaryExpression(parent);
      return isObjectLiteralExpression(right) && right;
    }
  }
  function checkCallExpression(node, checkMode) {
    var _a, _b, _c;
    checkGrammarTypeArguments(node, node.typeArguments);
    const signature = getResolvedSignature(
      node,
      /*candidatesOutArray*/
      void 0,
      checkMode
    );
    if (signature === resolvingSignature) {
      return silentNeverType;
    }
    checkDeprecatedSignature(signature, node);
    if (node.expression.kind === 108 /* SuperKeyword */) {
      return voidType;
    }
    if (node.kind === 214 /* NewExpression */) {
      const declaration = signature.declaration;
      if (declaration && declaration.kind !== 176 /* Constructor */ && declaration.kind !== 180 /* ConstructSignature */ && declaration.kind !== 185 /* ConstructorType */ && !(isJSDocSignature(declaration) && ((_b = (_a = getJSDocRoot(declaration)) == null ? void 0 : _a.parent) == null ? void 0 : _b.kind) === 176 /* Constructor */) && !isJSDocConstructSignature(declaration) && !isJSConstructor(declaration)) {
        if (noImplicitAny) {
          error(node, Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
        }
        return anyType;
      }
    }
    if (isInJSFile(node) && isCommonJsRequire(node)) {
      return resolveExternalModuleTypeByLiteral(node.arguments[0]);
    }
    const returnType = getReturnTypeOfSignature(signature);
    if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
      return getESSymbolLikeTypeForNode(walkUpParenthesizedExpressions(node.parent));
    }
    if (node.kind === 213 /* CallExpression */ && !node.questionDotToken && node.parent.kind === 244 /* ExpressionStatement */ && returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
      if (!isDottedName(node.expression)) {
        error(node.expression, Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
      } else if (!getEffectsSignature(node)) {
        const diagnostic = error(node.expression, Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
        getTypeOfDottedName(node.expression, diagnostic);
      }
    }
    if (isInJSFile(node)) {
      const jsSymbol = getSymbolOfExpando(
        node,
        /*allowDeclaration*/
        false
      );
      if ((_c = jsSymbol == null ? void 0 : jsSymbol.exports) == null ? void 0 : _c.size) {
        const jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, emptyArray, emptyArray, emptyArray);
        jsAssignmentType.objectFlags |= 4096 /* JSLiteral */;
        return getIntersectionType([returnType, jsAssignmentType]);
      }
    }
    return returnType;
  }
  function checkDeprecatedSignature(signature, node) {
    if (signature.flags & 128 /* IsSignatureCandidateForOverloadFailure */) return;
    if (signature.declaration && signature.declaration.flags & 536870912 /* Deprecated */) {
      const suggestionNode = getDeprecatedSuggestionNode(node);
      const name = tryGetPropertyAccessOrIdentifierToString(getInvokedExpression(node));
      addDeprecatedSuggestionWithSignature(suggestionNode, signature.declaration, name, signatureToString(signature));
    }
  }
  function getDeprecatedSuggestionNode(node) {
    node = skipParentheses(node);
    switch (node.kind) {
      case 213 /* CallExpression */:
      case 170 /* Decorator */:
      case 214 /* NewExpression */:
        return getDeprecatedSuggestionNode(node.expression);
      case 215 /* TaggedTemplateExpression */:
        return getDeprecatedSuggestionNode(node.tag);
      case 286 /* JsxOpeningElement */:
      case 285 /* JsxSelfClosingElement */:
        return getDeprecatedSuggestionNode(node.tagName);
      case 212 /* ElementAccessExpression */:
        return node.argumentExpression;
      case 211 /* PropertyAccessExpression */:
        return node.name;
      case 183 /* TypeReference */:
        const typeReference = node;
        return isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference;
      default:
        return node;
    }
  }
  function isSymbolOrSymbolForCall(node) {
    if (!isCallExpression(node)) return false;
    let left = node.expression;
    if (isPropertyAccessExpression(left) && left.name.escapedText === "for") {
      left = left.expression;
    }
    if (!isIdentifier(left) || left.escapedText !== "Symbol") {
      return false;
    }
    const globalESSymbol = getGlobalESSymbolConstructorSymbol(
      /*reportErrors*/
      false
    );
    if (!globalESSymbol) {
      return false;
    }
    return globalESSymbol === resolveName(
      left,
      "Symbol",
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false
    );
  }
  function checkImportCallExpression(node) {
    checkGrammarImportCallExpression(node);
    if (node.arguments.length === 0) {
      return createPromiseReturnType(node, anyType);
    }
    const specifier = node.arguments[0];
    const specifierType = checkExpressionCached(specifier);
    const optionsType = node.arguments.length > 1 ? checkExpressionCached(node.arguments[1]) : void 0;
    for (let i = 2; i < node.arguments.length; ++i) {
      checkExpressionCached(node.arguments[i]);
    }
    if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
      error(specifier, Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
    }
    if (optionsType) {
      const importCallOptionsType = getGlobalImportCallOptionsType(
        /*reportErrors*/
        true
      );
      if (importCallOptionsType !== emptyObjectType) {
        checkTypeAssignableTo(optionsType, getNullableType(importCallOptionsType, 32768 /* Undefined */), node.arguments[1]);
      }
    }
    const moduleSymbol = resolveExternalModuleName(node, specifier);
    if (moduleSymbol) {
      const esModuleSymbol = resolveESModuleSymbol(
        moduleSymbol,
        specifier,
        /*dontResolveAlias*/
        true,
        /*suppressInteropError*/
        false
      );
      if (esModuleSymbol) {
        return createPromiseReturnType(
          node,
          getTypeWithSyntheticDefaultOnly(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier) || getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol, specifier)
        );
      }
    }
    return createPromiseReturnType(node, anyType);
  }
  function createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol) {
    const memberTable = createSymbolTable();
    const newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
    newSymbol.parent = originalSymbol;
    newSymbol.links.nameType = getStringLiteralType("default");
    newSymbol.links.aliasTarget = resolveSymbol(symbol);
    memberTable.set("default" /* Default */, newSymbol);
    return createAnonymousType(anonymousSymbol, memberTable, emptyArray, emptyArray, emptyArray);
  }
  function getTypeWithSyntheticDefaultOnly(type, symbol, originalSymbol, moduleSpecifier) {
    const hasDefaultOnly = isOnlyImportableAsDefault(moduleSpecifier);
    if (hasDefaultOnly && type && !isErrorType(type)) {
      const synthType = type;
      if (!synthType.defaultOnlyType) {
        const type2 = createDefaultPropertyWrapperForModule(symbol, originalSymbol);
        synthType.defaultOnlyType = type2;
      }
      return synthType.defaultOnlyType;
    }
    return void 0;
  }
  function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol, moduleSpecifier) {
    var _a;
    if (allowSyntheticDefaultImports && type && !isErrorType(type)) {
      const synthType = type;
      if (!synthType.syntheticType) {
        const file = (_a = originalSymbol.declarations) == null ? void 0 : _a.find(isSourceFile);
        const hasSyntheticDefault = canHaveSyntheticDefault(
          file,
          originalSymbol,
          /*dontResolveAlias*/
          false,
          moduleSpecifier
        );
        if (hasSyntheticDefault) {
          const anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
          const defaultContainingObject = createDefaultPropertyWrapperForModule(symbol, originalSymbol, anonymousSymbol);
          anonymousSymbol.links.type = defaultContainingObject;
          synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(
            type,
            defaultContainingObject,
            anonymousSymbol,
            /*objectFlags*/
            0,
            /*readonly*/
            false
          ) : defaultContainingObject;
        } else {
          synthType.syntheticType = type;
        }
      }
      return synthType.syntheticType;
    }
    return type;
  }
  function isCommonJsRequire(node) {
    if (!isRequireCall(
      node,
      /*requireStringLiteralLikeArgument*/
      true
    )) {
      return false;
    }
    if (!isIdentifier(node.expression)) return Debug.fail();
    const resolvedRequire = resolveName(
      node.expression,
      node.expression.escapedText,
      111551 /* Value */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
    if (resolvedRequire === requireSymbol) {
      return true;
    }
    if (resolvedRequire.flags & 2097152 /* Alias */) {
      return false;
    }
    const targetDeclarationKind = resolvedRequire.flags & 16 /* Function */ ? 262 /* FunctionDeclaration */ : resolvedRequire.flags & 3 /* Variable */ ? 260 /* VariableDeclaration */ : 0 /* Unknown */;
    if (targetDeclarationKind !== 0 /* Unknown */) {
      const decl = getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
      return !!decl && !!(decl.flags & 33554432 /* Ambient */);
    }
    return false;
  }
  function checkTaggedTemplateExpression(node) {
    if (!checkGrammarTaggedTemplateChain(node)) checkGrammarTypeArguments(node, node.typeArguments);
    if (languageVersion < LanguageFeatureMinimumTarget.TaggedTemplates) {
      checkExternalEmitHelpers(node, 262144 /* MakeTemplateObject */);
    }
    const signature = getResolvedSignature(node);
    checkDeprecatedSignature(signature, node);
    return getReturnTypeOfSignature(signature);
  }
  function checkAssertion(node, checkMode) {
    if (node.kind === 216 /* TypeAssertionExpression */) {
      const file = getSourceFileOfNode(node);
      if (file && fileExtensionIsOneOf(file.fileName, [".cts" /* Cts */, ".mts" /* Mts */])) {
        grammarErrorOnNode(node, Diagnostics.This_syntax_is_reserved_in_files_with_the_mts_or_cts_extension_Use_an_as_expression_instead);
      }
    }
    return checkAssertionWorker(node, checkMode);
  }
  function isValidConstAssertionArgument(node) {
    switch (node.kind) {
      case 11 /* StringLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 209 /* ArrayLiteralExpression */:
      case 210 /* ObjectLiteralExpression */:
      case 228 /* TemplateExpression */:
        return true;
      case 217 /* ParenthesizedExpression */:
        return isValidConstAssertionArgument(node.expression);
      case 224 /* PrefixUnaryExpression */:
        const op = node.operator;
        const arg = node.operand;
        return op === 41 /* MinusToken */ && (arg.kind === 9 /* NumericLiteral */ || arg.kind === 10 /* BigIntLiteral */) || op === 40 /* PlusToken */ && arg.kind === 9 /* NumericLiteral */;
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        const expr = skipParentheses(node.expression);
        const symbol = isEntityNameExpression(expr) ? resolveEntityName(
          expr,
          111551 /* Value */,
          /*ignoreErrors*/
          true
        ) : void 0;
        return !!(symbol && symbol.flags & 384 /* Enum */);
    }
    return false;
  }
  function checkAssertionWorker(node, checkMode) {
    const { type, expression } = getAssertionTypeAndExpression(node);
    const exprType = checkExpression(expression, checkMode);
    if (isConstTypeReference(type)) {
      if (!isValidConstAssertionArgument(expression)) {
        error(expression, Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
      }
      return getRegularTypeOfLiteralType(exprType);
    }
    const links = getNodeLinks(node);
    links.assertionExpressionType = exprType;
    checkSourceElement(type);
    checkNodeDeferred(node);
    return getTypeFromTypeNode(type);
  }
  function getAssertionTypeAndExpression(node) {
    let type;
    let expression;
    switch (node.kind) {
      case 234 /* AsExpression */:
      case 216 /* TypeAssertionExpression */:
        type = node.type;
        expression = node.expression;
        break;
      case 217 /* ParenthesizedExpression */:
        type = getJSDocTypeAssertionType(node);
        expression = node.expression;
        break;
    }
    return { type, expression };
  }
  function checkAssertionDeferred(node) {
    const { type } = getAssertionTypeAndExpression(node);
    const errNode = isParenthesizedExpression(node) ? type : node;
    const links = getNodeLinks(node);
    Debug.assertIsDefined(links.assertionExpressionType);
    const exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(links.assertionExpressionType));
    const targetType = getTypeFromTypeNode(type);
    if (!isErrorType(targetType)) {
      addLazyDiagnostic(() => {
        const widenedType = getWidenedType(exprType);
        if (!isTypeComparableTo(targetType, widenedType)) {
          checkTypeComparableTo(exprType, targetType, errNode, Diagnostics.Conversion_of_type_0_to_type_1_may_be_a_mistake_because_neither_type_sufficiently_overlaps_with_the_other_If_this_was_intentional_convert_the_expression_to_unknown_first);
        }
      });
    }
  }
  function checkNonNullChain(node) {
    const leftType = checkExpression(node.expression);
    const nonOptionalType = getOptionalExpressionType(leftType, node.expression);
    return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
  }
  function checkNonNullAssertion(node) {
    return node.flags & 64 /* OptionalChain */ ? checkNonNullChain(node) : getNonNullableType(checkExpression(node.expression));
  }
  function checkExpressionWithTypeArguments(node) {
    checkGrammarExpressionWithTypeArguments(node);
    forEach(node.typeArguments, checkSourceElement);
    if (node.kind === 233 /* ExpressionWithTypeArguments */) {
      const parent = walkUpParenthesizedExpressions(node.parent);
      if (parent.kind === 226 /* BinaryExpression */ && parent.operatorToken.kind === 104 /* InstanceOfKeyword */ && isNodeDescendantOf(node, parent.right)) {
        error(node, Diagnostics.The_right_hand_side_of_an_instanceof_expression_must_not_be_an_instantiation_expression);
      }
    }
    const exprType = node.kind === 233 /* ExpressionWithTypeArguments */ ? checkExpression(node.expression) : isThisIdentifier(node.exprName) ? checkThisExpression(node.exprName) : checkExpression(node.exprName);
    return getInstantiationExpressionType(exprType, node);
  }
  function getInstantiationExpressionType(exprType, node) {
    const typeArguments = node.typeArguments;
    if (exprType === silentNeverType || isErrorType(exprType) || !some(typeArguments)) {
      return exprType;
    }
    const links = getNodeLinks(node);
    if (!links.instantiationExpressionTypes) {
      links.instantiationExpressionTypes = /* @__PURE__ */ new Map();
    }
    if (links.instantiationExpressionTypes.has(exprType.id)) {
      return links.instantiationExpressionTypes.get(exprType.id);
    }
    let hasSomeApplicableSignature = false;
    let nonApplicableType;
    const result = getInstantiatedType(exprType);
    links.instantiationExpressionTypes.set(exprType.id, result);
    const errorType2 = hasSomeApplicableSignature ? nonApplicableType : exprType;
    if (errorType2) {
      diagnostics.add(createDiagnosticForNodeArray(getSourceFileOfNode(node), typeArguments, Diagnostics.Type_0_has_no_signatures_for_which_the_type_argument_list_is_applicable, typeToString(errorType2)));
    }
    return result;
    function getInstantiatedType(type) {
      let hasSignatures = false;
      let hasApplicableSignature = false;
      const result2 = getInstantiatedTypePart(type);
      hasSomeApplicableSignature || (hasSomeApplicableSignature = hasApplicableSignature);
      if (hasSignatures && !hasApplicableSignature) {
        nonApplicableType ?? (nonApplicableType = type);
      }
      return result2;
      function getInstantiatedTypePart(type2) {
        if (type2.flags & 524288 /* Object */) {
          const resolved = resolveStructuredTypeMembers(type2);
          const callSignatures = getInstantiatedSignatures(resolved.callSignatures);
          const constructSignatures = getInstantiatedSignatures(resolved.constructSignatures);
          hasSignatures || (hasSignatures = resolved.callSignatures.length !== 0 || resolved.constructSignatures.length !== 0);
          hasApplicableSignature || (hasApplicableSignature = callSignatures.length !== 0 || constructSignatures.length !== 0);
          if (callSignatures !== resolved.callSignatures || constructSignatures !== resolved.constructSignatures) {
            const result3 = createAnonymousType(createSymbol(0 /* None */, "__instantiationExpression" /* InstantiationExpression */), resolved.members, callSignatures, constructSignatures, resolved.indexInfos);
            result3.objectFlags |= 8388608 /* InstantiationExpressionType */;
            result3.node = node;
            return result3;
          }
        } else if (type2.flags & 58982400 /* InstantiableNonPrimitive */) {
          const constraint = getBaseConstraintOfType(type2);
          if (constraint) {
            const instantiated = getInstantiatedTypePart(constraint);
            if (instantiated !== constraint) {
              return instantiated;
            }
          }
        } else if (type2.flags & 1048576 /* Union */) {
          return mapType(type2, getInstantiatedType);
        } else if (type2.flags & 2097152 /* Intersection */) {
          return getIntersectionType(sameMap(type2.types, getInstantiatedTypePart));
        }
        return type2;
      }
    }
    function getInstantiatedSignatures(signatures) {
      const applicableSignatures = filter(signatures, (sig) => !!sig.typeParameters && hasCorrectTypeArgumentArity(sig, typeArguments));
      return sameMap(applicableSignatures, (sig) => {
        const typeArgumentTypes = checkTypeArguments(
          sig,
          typeArguments,
          /*reportErrors*/
          true
        );
        return typeArgumentTypes ? getSignatureInstantiation(sig, typeArgumentTypes, isInJSFile(sig.declaration)) : sig;
      });
    }
  }
  function checkSatisfiesExpression(node) {
    checkSourceElement(node.type);
    return checkSatisfiesExpressionWorker(node.expression, node.type);
  }
  function checkSatisfiesExpressionWorker(expression, target, checkMode) {
    const exprType = checkExpression(expression, checkMode);
    const targetType = getTypeFromTypeNode(target);
    if (isErrorType(targetType)) {
      return targetType;
    }
    const errorNode = findAncestor(target.parent, (n) => n.kind === 238 /* SatisfiesExpression */ || n.kind === 350 /* JSDocSatisfiesTag */);
    checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, errorNode, expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1);
    return exprType;
  }
  function checkMetaProperty(node) {
    checkGrammarMetaProperty(node);
    if (node.keywordToken === 105 /* NewKeyword */) {
      return checkNewTargetMetaProperty(node);
    }
    if (node.keywordToken === 102 /* ImportKeyword */) {
      return checkImportMetaProperty(node);
    }
    return Debug.assertNever(node.keywordToken);
  }
  function checkMetaPropertyKeyword(node) {
    switch (node.keywordToken) {
      case 102 /* ImportKeyword */:
        return getGlobalImportMetaExpressionType();
      case 105 /* NewKeyword */:
        const type = checkNewTargetMetaProperty(node);
        return isErrorType(type) ? errorType : createNewTargetExpressionType(type);
      default:
        Debug.assertNever(node.keywordToken);
    }
  }
  function checkNewTargetMetaProperty(node) {
    const container = getNewTargetContainer(node);
    if (!container) {
      error(node, Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
      return errorType;
    } else if (container.kind === 176 /* Constructor */) {
      const symbol = getSymbolOfDeclaration(container.parent);
      return getTypeOfSymbol(symbol);
    } else {
      const symbol = getSymbolOfDeclaration(container);
      return getTypeOfSymbol(symbol);
    }
  }
  function checkImportMetaProperty(node) {
    if (moduleKind === 100 /* Node16 */ || moduleKind === 199 /* NodeNext */) {
      if (getSourceFileOfNode(node).impliedNodeFormat !== 99 /* ESNext */) {
        error(node, Diagnostics.The_import_meta_meta_property_is_not_allowed_in_files_which_will_build_into_CommonJS_output);
      }
    } else if (moduleKind < 6 /* ES2020 */ && moduleKind !== 4 /* System */) {
      error(node, Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_es2022_esnext_system_node16_or_nodenext);
    }
    const file = getSourceFileOfNode(node);
    Debug.assert(!!(file.flags & 8388608 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
    return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
  }
  function getTypeOfParameter(symbol) {
    const declaration = symbol.valueDeclaration;
    return addOptionality(
      getTypeOfSymbol(symbol),
      /*isProperty*/
      false,
      /*isOptional*/
      !!declaration && (hasInitializer(declaration) || isOptionalDeclaration(declaration))
    );
  }
  function getTupleElementLabelFromBindingElement(node, index, elementFlags) {
    switch (node.name.kind) {
      case 80 /* Identifier */: {
        const name = node.name.escapedText;
        if (node.dotDotDotToken) {
          return elementFlags & 12 /* Variable */ ? name : `${name}_${index}`;
        } else {
          return elementFlags & 3 /* Fixed */ ? name : `${name}_n`;
        }
      }
      case 207 /* ArrayBindingPattern */: {
        if (node.dotDotDotToken) {
          const elements = node.name.elements;
          const lastElement = tryCast(lastOrUndefined(elements), isBindingElement);
          const elementCount = elements.length - ((lastElement == null ? void 0 : lastElement.dotDotDotToken) ? 1 : 0);
          if (index < elementCount) {
            const element = elements[index];
            if (isBindingElement(element)) {
              return getTupleElementLabelFromBindingElement(element, index, elementFlags);
            }
          } else if (lastElement == null ? void 0 : lastElement.dotDotDotToken) {
            return getTupleElementLabelFromBindingElement(lastElement, index - elementCount, elementFlags);
          }
        }
        break;
      }
    }
    return `arg_${index}`;
  }
  function getTupleElementLabel(d, index = 0, elementFlags = 3 /* Fixed */, restSymbol) {
    if (!d) {
      const restParameter = tryCast(restSymbol == null ? void 0 : restSymbol.valueDeclaration, isParameter);
      return restParameter ? getTupleElementLabelFromBindingElement(restParameter, index, elementFlags) : `${(restSymbol == null ? void 0 : restSymbol.escapedName) ?? "arg"}_${index}`;
    }
    Debug.assert(isIdentifier(d.name));
    return d.name.escapedText;
  }
  function getParameterNameAtPosition(signature, pos, overrideRestType) {
    var _a;
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      return signature.parameters[pos].escapedName;
    }
    const restParameter = signature.parameters[paramCount] || unknownSymbol;
    const restType = overrideRestType || getTypeOfSymbol(restParameter);
    if (isTupleType(restType)) {
      const tupleType = restType.target;
      const index = pos - paramCount;
      const associatedName = (_a = tupleType.labeledElementDeclarations) == null ? void 0 : _a[index];
      const elementFlags = tupleType.elementFlags[index];
      return getTupleElementLabel(associatedName, index, elementFlags, restParameter);
    }
    return restParameter.escapedName;
  }
  function getParameterIdentifierInfoAtPosition(signature, pos) {
    var _a;
    if (((_a = signature.declaration) == null ? void 0 : _a.kind) === 317 /* JSDocFunctionType */) {
      return void 0;
    }
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      const param = signature.parameters[pos];
      const paramIdent = getParameterDeclarationIdentifier(param);
      return paramIdent ? {
        parameter: paramIdent,
        parameterName: param.escapedName,
        isRestParameter: false
      } : void 0;
    }
    const restParameter = signature.parameters[paramCount] || unknownSymbol;
    const restIdent = getParameterDeclarationIdentifier(restParameter);
    if (!restIdent) {
      return void 0;
    }
    const restType = getTypeOfSymbol(restParameter);
    if (isTupleType(restType)) {
      const associatedNames = restType.target.labeledElementDeclarations;
      const index = pos - paramCount;
      const associatedName = associatedNames == null ? void 0 : associatedNames[index];
      const isRestTupleElement = !!(associatedName == null ? void 0 : associatedName.dotDotDotToken);
      if (associatedName) {
        Debug.assert(isIdentifier(associatedName.name));
        return { parameter: associatedName.name, parameterName: associatedName.name.escapedText, isRestParameter: isRestTupleElement };
      }
      return void 0;
    }
    if (pos === paramCount) {
      return { parameter: restIdent, parameterName: restParameter.escapedName, isRestParameter: true };
    }
    return void 0;
  }
  function getParameterDeclarationIdentifier(symbol) {
    return symbol.valueDeclaration && isParameter(symbol.valueDeclaration) && isIdentifier(symbol.valueDeclaration.name) && symbol.valueDeclaration.name;
  }
  function isValidDeclarationForTupleLabel(d) {
    return d.kind === 202 /* NamedTupleMember */ || isParameter(d) && d.name && isIdentifier(d.name);
  }
  function getNameableDeclarationAtPosition(signature, pos) {
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      const decl = signature.parameters[pos].valueDeclaration;
      return decl && isValidDeclarationForTupleLabel(decl) ? decl : void 0;
    }
    const restParameter = signature.parameters[paramCount] || unknownSymbol;
    const restType = getTypeOfSymbol(restParameter);
    if (isTupleType(restType)) {
      const associatedNames = restType.target.labeledElementDeclarations;
      const index = pos - paramCount;
      return associatedNames && associatedNames[index];
    }
    return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : void 0;
  }
  function getTypeAtPosition(signature, pos) {
    return tryGetTypeAtPosition(signature, pos) || anyType;
  }
  function tryGetTypeAtPosition(signature, pos) {
    const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    if (pos < paramCount) {
      return getTypeOfParameter(signature.parameters[pos]);
    }
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[paramCount]);
      const index = pos - paramCount;
      if (!isTupleType(restType) || restType.target.combinedFlags & 12 /* Variable */ || index < restType.target.fixedLength) {
        return getIndexedAccessType(restType, getNumberLiteralType(index));
      }
    }
    return void 0;
  }
  function getRestTypeAtPosition(source, pos, readonly) {
    const parameterCount = getParameterCount(source);
    const minArgumentCount = getMinArgumentCount(source);
    const restType = getEffectiveRestType(source);
    if (restType && pos >= parameterCount - 1) {
      return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType));
    }
    const types = [];
    const flags = [];
    const names = [];
    for (let i = pos; i < parameterCount; i++) {
      if (!restType || i < parameterCount - 1) {
        types.push(getTypeAtPosition(source, i));
        flags.push(i < minArgumentCount ? 1 /* Required */ : 2 /* Optional */);
      } else {
        types.push(restType);
        flags.push(8 /* Variadic */);
      }
      names.push(getNameableDeclarationAtPosition(source, i));
    }
    return createTupleType(types, flags, readonly, names);
  }
  function getRestOrAnyTypeAtPosition(source, pos) {
    const restType = getRestTypeAtPosition(source, pos);
    const elementType = restType && getElementTypeOfArrayType(restType);
    return elementType && isTypeAny(elementType) ? anyType : restType;
  }
  function getParameterCount(signature) {
    const length2 = signature.parameters.length;
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[length2 - 1]);
      if (isTupleType(restType)) {
        return length2 + restType.target.fixedLength - (restType.target.combinedFlags & 12 /* Variable */ ? 0 : 1);
      }
    }
    return length2;
  }
  function getMinArgumentCount(signature, flags) {
    const strongArityForUntypedJS = flags & 1 /* StrongArityForUntypedJS */;
    const voidIsNonOptional = flags & 2 /* VoidIsNonOptional */;
    if (voidIsNonOptional || signature.resolvedMinArgumentCount === void 0) {
      let minArgumentCount;
      if (signatureHasRestParameter(signature)) {
        const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
        if (isTupleType(restType)) {
          const firstOptionalIndex = findIndex(restType.target.elementFlags, (f) => !(f & 1 /* Required */));
          const requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex;
          if (requiredCount > 0) {
            minArgumentCount = signature.parameters.length - 1 + requiredCount;
          }
        }
      }
      if (minArgumentCount === void 0) {
        if (!strongArityForUntypedJS && signature.flags & 32 /* IsUntypedSignatureInJSFile */) {
          return 0;
        }
        minArgumentCount = signature.minArgumentCount;
      }
      if (voidIsNonOptional) {
        return minArgumentCount;
      }
      for (let i = minArgumentCount - 1; i >= 0; i--) {
        const type = getTypeAtPosition(signature, i);
        if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
          break;
        }
        minArgumentCount = i;
      }
      signature.resolvedMinArgumentCount = minArgumentCount;
    }
    return signature.resolvedMinArgumentCount;
  }
  function hasEffectiveRestParameter(signature) {
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
      return !isTupleType(restType) || !!(restType.target.combinedFlags & 12 /* Variable */);
    }
    return false;
  }
  function getEffectiveRestType(signature) {
    if (signatureHasRestParameter(signature)) {
      const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
      if (!isTupleType(restType)) {
        return isTypeAny(restType) ? anyArrayType : restType;
      }
      if (restType.target.combinedFlags & 12 /* Variable */) {
        return sliceTupleType(restType, restType.target.fixedLength);
      }
    }
    return void 0;
  }
  function getNonArrayRestType(signature) {
    const restType = getEffectiveRestType(signature);
    return restType && !isArrayType(restType) && !isTypeAny(restType) ? restType : void 0;
  }
  function getTypeOfFirstParameterOfSignature(signature) {
    return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
  }
  function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
    return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
  }
  function inferFromAnnotatedParameters(signature, context, inferenceContext) {
    const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    for (let i = 0; i < len; i++) {
      const declaration = signature.parameters[i].valueDeclaration;
      const typeNode = getEffectiveTypeAnnotationNode(declaration);
      if (typeNode) {
        const source = addOptionality(
          getTypeFromTypeNode(typeNode),
          /*isProperty*/
          false,
          isOptionalDeclaration(declaration)
        );
        const target = getTypeAtPosition(context, i);
        inferTypes(inferenceContext.inferences, source, target);
      }
    }
  }
  function assignContextualParameterTypes(signature, context) {
    if (context.typeParameters) {
      if (!signature.typeParameters) {
        signature.typeParameters = context.typeParameters;
      } else {
        return;
      }
    }
    if (context.thisParameter) {
      const parameter = signature.thisParameter;
      if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
        if (!parameter) {
          signature.thisParameter = createSymbolWithType(
            context.thisParameter,
            /*type*/
            void 0
          );
        }
        assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
      }
    }
    const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
    for (let i = 0; i < len; i++) {
      const parameter = signature.parameters[i];
      const declaration = parameter.valueDeclaration;
      if (!getEffectiveTypeAnnotationNode(declaration)) {
        let type = tryGetTypeAtPosition(context, i);
        if (type && declaration.initializer) {
          let initializerType = checkDeclarationInitializer(declaration, 0 /* Normal */);
          if (!isTypeAssignableTo(initializerType, type) && isTypeAssignableTo(type, initializerType = widenTypeInferredFromInitializer(declaration, initializerType))) {
            type = initializerType;
          }
        }
        assignParameterType(parameter, type);
      }
    }
    if (signatureHasRestParameter(signature)) {
      const parameter = last(signature.parameters);
      if (parameter.valueDeclaration ? !getEffectiveTypeAnnotationNode(parameter.valueDeclaration) : !!(getCheckFlags(parameter) & 65536 /* DeferredType */)) {
        const contextualParameterType = getRestTypeAtPosition(context, len);
        assignParameterType(parameter, contextualParameterType);
      }
    }
  }
  function assignNonContextualParameterTypes(signature) {
    if (signature.thisParameter) {
      assignParameterType(signature.thisParameter);
    }
    for (const parameter of signature.parameters) {
      assignParameterType(parameter);
    }
  }
  function assignParameterType(parameter, contextualType) {
    const links = getSymbolLinks(parameter);
    if (!links.type) {
      const declaration = parameter.valueDeclaration;
      links.type = addOptionality(
        contextualType || (declaration ? getWidenedTypeForVariableLikeDeclaration(
          declaration,
          /*reportErrors*/
          true
        ) : getTypeOfSymbol(parameter)),
        /*isProperty*/
        false,
        /*isOptional*/
        !!declaration && !declaration.initializer && isOptionalDeclaration(declaration)
      );
      if (declaration && declaration.name.kind !== 80 /* Identifier */) {
        if (links.type === unknownType) {
          links.type = getTypeFromBindingPattern(declaration.name);
        }
        assignBindingElementTypes(declaration.name, links.type);
      }
    } else if (contextualType) {
      Debug.assertEqual(links.type, contextualType, "Parameter symbol already has a cached type which differs from newly assigned type");
    }
  }
  function assignBindingElementTypes(pattern, parentType) {
    for (const element of pattern.elements) {
      if (!isOmittedExpression(element)) {
        const type = getBindingElementTypeFromParentType(
          element,
          parentType,
          /*noTupleBoundsCheck*/
          false
        );
        if (element.name.kind === 80 /* Identifier */) {
          getSymbolLinks(getSymbolOfDeclaration(element)).type = type;
        } else {
          assignBindingElementTypes(element.name, type);
        }
      }
    }
  }
  function createClassDecoratorContextType(classType) {
    return tryCreateTypeReference(getGlobalClassDecoratorContextType(
      /*reportErrors*/
      true
    ), [classType]);
  }
  function createClassMethodDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassMethodDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassGetterDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassGetterDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassSetterDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassSetterDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassAccessorDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassAccessorDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassFieldDecoratorContextType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassFieldDecoratorContextType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic2) {
    const key = `${isPrivate ? "p" : "P"}${isStatic2 ? "s" : "S"}${nameType.id}`;
    let overrideType = decoratorContextOverrideTypeCache.get(key);
    if (!overrideType) {
      const members = createSymbolTable();
      members.set("name", createProperty("name", nameType));
      members.set("private", createProperty("private", isPrivate ? trueType : falseType));
      members.set("static", createProperty("static", isStatic2 ? trueType : falseType));
      overrideType = createAnonymousType(
        /*symbol*/
        void 0,
        members,
        emptyArray,
        emptyArray,
        emptyArray
      );
      decoratorContextOverrideTypeCache.set(key, overrideType);
    }
    return overrideType;
  }
  function createClassMemberDecoratorContextTypeForNode(node, thisType, valueType) {
    const isStatic2 = hasStaticModifier(node);
    const isPrivate = isPrivateIdentifier(node.name);
    const nameType = isPrivate ? getStringLiteralType(idText(node.name)) : getLiteralTypeFromPropertyName(node.name);
    const contextType = isMethodDeclaration(node) ? createClassMethodDecoratorContextType(thisType, valueType) : isGetAccessorDeclaration(node) ? createClassGetterDecoratorContextType(thisType, valueType) : isSetAccessorDeclaration(node) ? createClassSetterDecoratorContextType(thisType, valueType) : isAutoAccessorPropertyDeclaration(node) ? createClassAccessorDecoratorContextType(thisType, valueType) : isPropertyDeclaration(node) ? createClassFieldDecoratorContextType(thisType, valueType) : Debug.failBadSyntaxKind(node);
    const overrideType = getClassMemberDecoratorContextOverrideType(nameType, isPrivate, isStatic2);
    return getIntersectionType([contextType, overrideType]);
  }
  function createClassAccessorDecoratorTargetType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassAccessorDecoratorTargetType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassAccessorDecoratorResultType(thisType, valueType) {
    return tryCreateTypeReference(getGlobalClassAccessorDecoratorResultType(
      /*reportErrors*/
      true
    ), [thisType, valueType]);
  }
  function createClassFieldDecoratorInitializerMutatorType(thisType, valueType) {
    const thisParam = createParameter("this", thisType);
    const valueParam = createParameter("value", valueType);
    return createFunctionType(
      /*typeParameters*/
      void 0,
      thisParam,
      [valueParam],
      valueType,
      /*typePredicate*/
      void 0,
      1
    );
  }
  function createESDecoratorCallSignature(targetType, contextType, nonOptionalReturnType) {
    const targetParam = createParameter("target", targetType);
    const contextParam = createParameter("context", contextType);
    const returnType = getUnionType([nonOptionalReturnType, voidType]);
    return createCallSignature(
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [targetParam, contextParam],
      returnType
    );
  }
  function getESDecoratorCallSignature(decorator) {
    const { parent } = decorator;
    const links = getNodeLinks(parent);
    if (!links.decoratorSignature) {
      links.decoratorSignature = anySignature;
      switch (parent.kind) {
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */: {
          const node = parent;
          const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node));
          const contextType = createClassDecoratorContextType(targetType);
          links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, targetType);
          break;
        }
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */: {
          const node = parent;
          if (!isClassLike(node.parent)) break;
          const valueType = isMethodDeclaration(node) ? getOrCreateTypeFromSignature(getSignatureFromDeclaration(node)) : getTypeOfNode(node);
          const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent));
          const targetType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType;
          const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType);
          const returnType = isGetAccessorDeclaration(node) ? createGetterFunctionType(valueType) : isSetAccessorDeclaration(node) ? createSetterFunctionType(valueType) : valueType;
          links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType);
          break;
        }
        case 172 /* PropertyDeclaration */: {
          const node = parent;
          if (!isClassLike(node.parent)) break;
          const valueType = getTypeOfNode(node);
          const thisType = hasStaticModifier(node) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent)) : getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(node.parent));
          const targetType = hasAccessorModifier(node) ? createClassAccessorDecoratorTargetType(thisType, valueType) : undefinedType;
          const contextType = createClassMemberDecoratorContextTypeForNode(node, thisType, valueType);
          const returnType = hasAccessorModifier(node) ? createClassAccessorDecoratorResultType(thisType, valueType) : createClassFieldDecoratorInitializerMutatorType(thisType, valueType);
          links.decoratorSignature = createESDecoratorCallSignature(targetType, contextType, returnType);
          break;
        }
      }
    }
    return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature;
  }
  function getLegacyDecoratorCallSignature(decorator) {
    const { parent } = decorator;
    const links = getNodeLinks(parent);
    if (!links.decoratorSignature) {
      links.decoratorSignature = anySignature;
      switch (parent.kind) {
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */: {
          const node = parent;
          const targetType = getTypeOfSymbol(getSymbolOfDeclaration(node));
          const targetParam = createParameter("target", targetType);
          links.decoratorSignature = createCallSignature(
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            [targetParam],
            getUnionType([targetType, voidType])
          );
          break;
        }
        case 169 /* Parameter */: {
          const node = parent;
          if (!isConstructorDeclaration(node.parent) && !(isMethodDeclaration(node.parent) || isSetAccessorDeclaration(node.parent) && isClassLike(node.parent.parent))) {
            break;
          }
          if (getThisParameter(node.parent) === node) {
            break;
          }
          const index = getThisParameter(node.parent) ? node.parent.parameters.indexOf(node) - 1 : node.parent.parameters.indexOf(node);
          Debug.assert(index >= 0);
          const targetType = isConstructorDeclaration(node.parent) ? getTypeOfSymbol(getSymbolOfDeclaration(node.parent.parent)) : getParentTypeOfClassElement(node.parent);
          const keyType = isConstructorDeclaration(node.parent) ? undefinedType : getClassElementPropertyKeyType(node.parent);
          const indexType = getNumberLiteralType(index);
          const targetParam = createParameter("target", targetType);
          const keyParam = createParameter("propertyKey", keyType);
          const indexParam = createParameter("parameterIndex", indexType);
          links.decoratorSignature = createCallSignature(
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            [targetParam, keyParam, indexParam],
            voidType
          );
          break;
        }
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
        case 172 /* PropertyDeclaration */: {
          const node = parent;
          if (!isClassLike(node.parent)) break;
          const targetType = getParentTypeOfClassElement(node);
          const targetParam = createParameter("target", targetType);
          const keyType = getClassElementPropertyKeyType(node);
          const keyParam = createParameter("propertyKey", keyType);
          const returnType = isPropertyDeclaration(node) ? voidType : createTypedPropertyDescriptorType(getTypeOfNode(node));
          const hasPropDesc = !isPropertyDeclaration(parent) || hasAccessorModifier(parent);
          if (hasPropDesc) {
            const descriptorType = createTypedPropertyDescriptorType(getTypeOfNode(node));
            const descriptorParam = createParameter("descriptor", descriptorType);
            links.decoratorSignature = createCallSignature(
              /*typeParameters*/
              void 0,
              /*thisParameter*/
              void 0,
              [targetParam, keyParam, descriptorParam],
              getUnionType([returnType, voidType])
            );
          } else {
            links.decoratorSignature = createCallSignature(
              /*typeParameters*/
              void 0,
              /*thisParameter*/
              void 0,
              [targetParam, keyParam],
              getUnionType([returnType, voidType])
            );
          }
          break;
        }
      }
    }
    return links.decoratorSignature === anySignature ? void 0 : links.decoratorSignature;
  }
  function getDecoratorCallSignature(decorator) {
    return legacyDecorators ? getLegacyDecoratorCallSignature(decorator) : getESDecoratorCallSignature(decorator);
  }
  function createPromiseType(promisedType) {
    const globalPromiseType = getGlobalPromiseType(
      /*reportErrors*/
      true
    );
    if (globalPromiseType !== emptyGenericType) {
      promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType;
      return createTypeReference(globalPromiseType, [promisedType]);
    }
    return unknownType;
  }
  function createPromiseLikeType(promisedType) {
    const globalPromiseLikeType = getGlobalPromiseLikeType(
      /*reportErrors*/
      true
    );
    if (globalPromiseLikeType !== emptyGenericType) {
      promisedType = getAwaitedTypeNoAlias(unwrapAwaitedType(promisedType)) || unknownType;
      return createTypeReference(globalPromiseLikeType, [promisedType]);
    }
    return unknownType;
  }
  function createPromiseReturnType(func, promisedType) {
    const promiseType = createPromiseType(promisedType);
    if (promiseType === unknownType) {
      error(
        func,
        isImportCall(func) ? Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_must_return_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option
      );
      return errorType;
    } else if (!getGlobalPromiseConstructorSymbol(
      /*reportErrors*/
      true
    )) {
      error(
        func,
        isImportCall(func) ? Diagnostics.A_dynamic_import_call_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option : Diagnostics.An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option
      );
    }
    return promiseType;
  }
  function createNewTargetExpressionType(targetType) {
    const symbol = createSymbol(0 /* None */, "NewTargetExpression");
    const targetPropertySymbol = createSymbol(4 /* Property */, "target", 8 /* Readonly */);
    targetPropertySymbol.parent = symbol;
    targetPropertySymbol.links.type = targetType;
    const members = createSymbolTable([targetPropertySymbol]);
    symbol.members = members;
    return createAnonymousType(symbol, members, emptyArray, emptyArray, emptyArray);
  }
  function getReturnTypeFromBody(func, checkMode) {
    if (!func.body) {
      return errorType;
    }
    const functionFlags = getFunctionFlags(func);
    const isAsync = (functionFlags & 2 /* Async */) !== 0;
    const isGenerator = (functionFlags & 1 /* Generator */) !== 0;
    let returnType;
    let yieldType;
    let nextType;
    let fallbackReturnType = voidType;
    if (func.body.kind !== 241 /* Block */) {
      returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
      if (isAsync) {
        returnType = unwrapAwaitedType(checkAwaitedType(
          returnType,
          /*withAlias*/
          false,
          /*errorNode*/
          func,
          Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
        ));
      }
    } else if (isGenerator) {
      const returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
      if (!returnTypes) {
        fallbackReturnType = neverType;
      } else if (returnTypes.length > 0) {
        returnType = getUnionType(returnTypes, 2 /* Subtype */);
      }
      const { yieldTypes, nextTypes } = checkAndAggregateYieldOperandTypes(func, checkMode);
      yieldType = some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : void 0;
      nextType = some(nextTypes) ? getIntersectionType(nextTypes) : void 0;
    } else {
      const types = checkAndAggregateReturnExpressionTypes(func, checkMode);
      if (!types) {
        return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, neverType) : neverType;
      }
      if (types.length === 0) {
        const contextualReturnType = getContextualReturnType(
          func,
          /*contextFlags*/
          void 0
        );
        const returnType2 = contextualReturnType && (unwrapReturnType(contextualReturnType, functionFlags) || voidType).flags & 32768 /* Undefined */ ? undefinedType : voidType;
        return functionFlags & 2 /* Async */ ? createPromiseReturnType(func, returnType2) : (
          // Async function
          returnType2
        );
      }
      returnType = getUnionType(types, 2 /* Subtype */);
    }
    if (returnType || yieldType || nextType) {
      if (yieldType) reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
      if (returnType) reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
      if (nextType) reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
      if (returnType && isUnitType(returnType) || yieldType && isUnitType(yieldType) || nextType && isUnitType(nextType)) {
        const contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
        const contextualType = !contextualSignature ? void 0 : contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? void 0 : returnType : instantiateContextualType(
          getReturnTypeOfSignature(contextualSignature),
          func,
          /*contextFlags*/
          void 0
        );
        if (isGenerator) {
          yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
          returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
          nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
        } else {
          returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
        }
      }
      if (yieldType) yieldType = getWidenedType(yieldType);
      if (returnType) returnType = getWidenedType(returnType);
      if (nextType) nextType = getWidenedType(nextType);
    }
    if (isGenerator) {
      return createGeneratorType(
        yieldType || neverType,
        returnType || fallbackReturnType,
        nextType || getContextualIterationType(2 /* Next */, func) || unknownType,
        isAsync
      );
    } else {
      return isAsync ? createPromiseType(returnType || fallbackReturnType) : returnType || fallbackReturnType;
    }
  }
  function createGeneratorType(yieldType, returnType, nextType, isAsyncGenerator) {
    const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
    const globalGeneratorType = resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    );
    yieldType = resolver.resolveIterationType(
      yieldType,
      /*errorNode*/
      void 0
    ) || unknownType;
    returnType = resolver.resolveIterationType(
      returnType,
      /*errorNode*/
      void 0
    ) || unknownType;
    if (globalGeneratorType === emptyGenericType) {
      const globalIterableIteratorType = resolver.getGlobalIterableIteratorType(
        /*reportErrors*/
        false
      );
      if (globalIterableIteratorType !== emptyGenericType) {
        return createTypeFromGenericGlobalType(globalIterableIteratorType, [yieldType, returnType, nextType]);
      }
      resolver.getGlobalIterableIteratorType(
        /*reportErrors*/
        true
      );
      return emptyObjectType;
    }
    return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
  }
  function checkAndAggregateYieldOperandTypes(func, checkMode) {
    const yieldTypes = [];
    const nextTypes = [];
    const isAsync = (getFunctionFlags(func) & 2 /* Async */) !== 0;
    forEachYieldExpression(func.body, (yieldExpression) => {
      const yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
      pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
      let nextType;
      if (yieldExpression.asteriskToken) {
        const iterationTypes = getIterationTypesOfIterable(
          yieldExpressionType,
          isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */,
          yieldExpression.expression
        );
        nextType = iterationTypes && iterationTypes.nextType;
      } else {
        nextType = getContextualType(
          yieldExpression,
          /*contextFlags*/
          void 0
        );
      }
      if (nextType) pushIfUnique(nextTypes, nextType);
    });
    return { yieldTypes, nextTypes };
  }
  function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
    const errorNode = node.expression || node;
    const yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
    return !isAsync ? yieldedType : getAwaitedType(
      yieldedType,
      errorNode,
      node.asteriskToken ? Diagnostics.Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member : Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
    );
  }
  function getNotEqualFactsFromTypeofSwitch(start, end, witnesses) {
    let facts = 0 /* None */;
    for (let i = 0; i < witnesses.length; i++) {
      const witness = i < start || i >= end ? witnesses[i] : void 0;
      facts |= witness !== void 0 ? typeofNEFacts.get(witness) || 32768 /* TypeofNEHostObject */ : 0;
    }
    return facts;
  }
  function isExhaustiveSwitchStatement(node) {
    const links = getNodeLinks(node);
    if (links.isExhaustive === void 0) {
      links.isExhaustive = 0;
      const exhaustive = computeExhaustiveSwitchStatement(node);
      if (links.isExhaustive === 0) {
        links.isExhaustive = exhaustive;
      }
    } else if (links.isExhaustive === 0) {
      links.isExhaustive = false;
    }
    return links.isExhaustive;
  }
  function computeExhaustiveSwitchStatement(node) {
    if (node.expression.kind === 221 /* TypeOfExpression */) {
      const witnesses = getSwitchClauseTypeOfWitnesses(node);
      if (!witnesses) {
        return false;
      }
      const operandConstraint = getBaseConstraintOrType(checkExpressionCached(node.expression.expression));
      const notEqualFacts = getNotEqualFactsFromTypeofSwitch(0, 0, witnesses);
      if (operandConstraint.flags & 3 /* AnyOrUnknown */) {
        return (556800 /* AllTypeofNE */ & notEqualFacts) === 556800 /* AllTypeofNE */;
      }
      return !someType(operandConstraint, (t) => getTypeFacts(t, notEqualFacts) === notEqualFacts);
    }
    const type = checkExpressionCached(node.expression);
    if (!isLiteralType(type)) {
      return false;
    }
    const switchTypes = getSwitchClauseTypes(node);
    if (!switchTypes.length || some(switchTypes, isNeitherUnitTypeNorNever)) {
      return false;
    }
    return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
  }
  function functionHasImplicitReturn(func) {
    return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
  }
  function checkAndAggregateReturnExpressionTypes(func, checkMode) {
    const functionFlags = getFunctionFlags(func);
    const aggregatedTypes = [];
    let hasReturnWithNoExpression = functionHasImplicitReturn(func);
    let hasReturnOfTypeNever = false;
    forEachReturnStatement(func.body, (returnStatement) => {
      let expr = returnStatement.expression;
      if (expr) {
        expr = skipParentheses(
          expr,
          /*excludeJSDocTypeAssertions*/
          true
        );
        if (functionFlags & 2 /* Async */ && expr.kind === 223 /* AwaitExpression */) {
          expr = skipParentheses(
            expr.expression,
            /*excludeJSDocTypeAssertions*/
            true
          );
        }
        if (expr.kind === 213 /* CallExpression */ && expr.expression.kind === 80 /* Identifier */ && checkExpressionCached(expr.expression).symbol === getMergedSymbol(func.symbol) && (!isFunctionExpressionOrArrowFunction(func.symbol.valueDeclaration) || isConstantReference(expr.expression))) {
          hasReturnOfTypeNever = true;
          return;
        }
        let type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
        if (functionFlags & 2 /* Async */) {
          type = unwrapAwaitedType(checkAwaitedType(
            type,
            /*withAlias*/
            false,
            func,
            Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
          ));
        }
        if (type.flags & 131072 /* Never */) {
          hasReturnOfTypeNever = true;
        }
        pushIfUnique(aggregatedTypes, type);
      } else {
        hasReturnWithNoExpression = true;
      }
    });
    if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
      return void 0;
    }
    if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression && !(isJSConstructor(func) && aggregatedTypes.some((t) => t.symbol === func.symbol))) {
      pushIfUnique(aggregatedTypes, undefinedType);
    }
    return aggregatedTypes;
  }
  function mayReturnNever(func) {
    switch (func.kind) {
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        return true;
      case 174 /* MethodDeclaration */:
        return func.parent.kind === 210 /* ObjectLiteralExpression */;
      default:
        return false;
    }
  }
  function getTypePredicateFromBody(func) {
    switch (func.kind) {
      case 176 /* Constructor */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return void 0;
    }
    const functionFlags = getFunctionFlags(func);
    if (functionFlags !== 0 /* Normal */) return void 0;
    let singleReturn;
    if (func.body && func.body.kind !== 241 /* Block */) {
      singleReturn = func.body;
    } else {
      const bailedEarly = forEachReturnStatement(func.body, (returnStatement) => {
        if (singleReturn || !returnStatement.expression) return true;
        singleReturn = returnStatement.expression;
      });
      if (bailedEarly || !singleReturn || functionHasImplicitReturn(func)) return void 0;
    }
    return checkIfExpressionRefinesAnyParameter(func, singleReturn);
  }
  function checkIfExpressionRefinesAnyParameter(func, expr) {
    expr = skipParentheses(
      expr,
      /*excludeJSDocTypeAssertions*/
      true
    );
    const returnType = checkExpressionCached(expr);
    if (!(returnType.flags & 16 /* Boolean */)) return void 0;
    return forEach(func.parameters, (param, i) => {
      const initType = getTypeOfSymbol(param.symbol);
      if (!initType || initType.flags & 16 /* Boolean */ || !isIdentifier(param.name) || isSymbolAssigned(param.symbol) || isRestParameter(param)) {
        return;
      }
      const trueType2 = checkIfExpressionRefinesParameter(func, expr, param, initType);
      if (trueType2) {
        return createTypePredicate(1 /* Identifier */, unescapeLeadingUnderscores(param.name.escapedText), i, trueType2);
      }
    });
  }
  function checkIfExpressionRefinesParameter(func, expr, param, initType) {
    const antecedent = canHaveFlowNode(expr) && expr.flowNode || expr.parent.kind === 253 /* ReturnStatement */ && expr.parent.flowNode || createFlowNode(
      2 /* Start */,
      /*node*/
      void 0,
      /*antecedent*/
      void 0
    );
    const trueCondition = createFlowNode(32 /* TrueCondition */, expr, antecedent);
    const trueType2 = getFlowTypeOfReference(param.name, initType, initType, func, trueCondition);
    if (trueType2 === initType) return void 0;
    const falseCondition = createFlowNode(64 /* FalseCondition */, expr, antecedent);
    const falseSubtype = getFlowTypeOfReference(param.name, initType, trueType2, func, falseCondition);
    return falseSubtype.flags & 131072 /* Never */ ? trueType2 : void 0;
  }
  function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
    addLazyDiagnostic(checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics);
    return;
    function checkAllCodePathsInNonVoidFunctionReturnOrThrowDiagnostics() {
      const functionFlags = getFunctionFlags(func);
      const type = returnType && unwrapReturnType(returnType, functionFlags);
      if (type && (maybeTypeOfKind(type, 16384 /* Void */) || type.flags & (1 /* Any */ | 32768 /* Undefined */))) {
        return;
      }
      if (func.kind === 173 /* MethodSignature */ || nodeIsMissing(func.body) || func.body.kind !== 241 /* Block */ || !functionHasImplicitReturn(func)) {
        return;
      }
      const hasExplicitReturn = func.flags & 1024 /* HasExplicitReturn */;
      const errorNode = getEffectiveReturnTypeNode(func) || func;
      if (type && type.flags & 131072 /* Never */) {
        error(errorNode, Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
      } else if (type && !hasExplicitReturn) {
        error(errorNode, Diagnostics.A_function_whose_declared_type_is_neither_undefined_void_nor_any_must_return_a_value);
      } else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
        error(errorNode, Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
      } else if (compilerOptions.noImplicitReturns) {
        if (!type) {
          if (!hasExplicitReturn) {
            return;
          }
          const inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
          if (isUnwrappedReturnTypeUndefinedVoidOrAny(func, inferredReturnType)) {
            return;
          }
        }
        error(errorNode, Diagnostics.Not_all_code_paths_return_a_value);
      }
    }
  }
  function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
    Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node));
    checkNodeDeferred(node);
    if (isFunctionExpression(node)) {
      checkCollisionsForDeclarationName(node, node.name);
    }
    if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
      if (!getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
        const contextualSignature = getContextualSignature(node);
        if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
          const links = getNodeLinks(node);
          if (links.contextFreeType) {
            return links.contextFreeType;
          }
          const returnType = getReturnTypeFromBody(node, checkMode);
          const returnOnlySignature = createSignature(
            /*declaration*/
            void 0,
            /*typeParameters*/
            void 0,
            /*thisParameter*/
            void 0,
            emptyArray,
            returnType,
            /*resolvedTypePredicate*/
            void 0,
            0,
            64 /* IsNonInferrable */
          );
          const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], emptyArray, emptyArray);
          returnOnlyType.objectFlags |= 262144 /* NonInferrableType */;
          return links.contextFreeType = returnOnlyType;
        }
      }
      return anyFunctionType;
    }
    const hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
    if (!hasGrammarError && node.kind === 218 /* FunctionExpression */) {
      checkGrammarForGenerator(node);
    }
    contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
    return getTypeOfSymbol(getSymbolOfDeclaration(node));
  }
  function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
    const links = getNodeLinks(node);
    if (!(links.flags & 64 /* ContextChecked */)) {
      const contextualSignature = getContextualSignature(node);
      if (!(links.flags & 64 /* ContextChecked */)) {
        links.flags |= 64 /* ContextChecked */;
        const signature = firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfDeclaration(node)), 0 /* Call */));
        if (!signature) {
          return;
        }
        if (isContextSensitive(node)) {
          if (contextualSignature) {
            const inferenceContext = getInferenceContext(node);
            let instantiatedContextualSignature;
            if (checkMode && checkMode & 2 /* Inferential */) {
              inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
              const restType = getEffectiveRestType(contextualSignature);
              if (restType && restType.flags & 262144 /* TypeParameter */) {
                instantiatedContextualSignature = instantiateSignature(contextualSignature, inferenceContext.nonFixingMapper);
              }
            }
            instantiatedContextualSignature || (instantiatedContextualSignature = inferenceContext ? instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature);
            assignContextualParameterTypes(signature, instantiatedContextualSignature);
          } else {
            assignNonContextualParameterTypes(signature);
          }
        } else if (contextualSignature && !node.typeParameters && contextualSignature.parameters.length > node.parameters.length) {
          const inferenceContext = getInferenceContext(node);
          if (checkMode && checkMode & 2 /* Inferential */) {
            inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
          }
        }
        if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
          const returnType = getReturnTypeFromBody(node, checkMode);
          if (!signature.resolvedReturnType) {
            signature.resolvedReturnType = returnType;
          }
        }
        checkSignatureDeclaration(node);
      }
    }
  }
  function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
    Debug.assert(node.kind !== 174 /* MethodDeclaration */ || isObjectLiteralMethod(node));
    const functionFlags = getFunctionFlags(node);
    const returnType = getReturnTypeFromAnnotation(node);
    checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
    if (node.body) {
      if (!getEffectiveReturnTypeNode(node)) {
        getReturnTypeOfSignature(getSignatureFromDeclaration(node));
      }
      if (node.body.kind === 241 /* Block */) {
        checkSourceElement(node.body);
      } else {
        const exprType = checkExpression(node.body);
        const returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
        if (returnOrPromisedType) {
          const effectiveCheckNode = getEffectiveCheckNode(node.body);
          if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) {
            const awaitedType = checkAwaitedType(
              exprType,
              /*withAlias*/
              false,
              effectiveCheckNode,
              Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
            );
            checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, effectiveCheckNode, effectiveCheckNode);
          } else {
            checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, effectiveCheckNode, effectiveCheckNode);
          }
        }
      }
    }
  }
  function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid = false) {
    if (!isTypeAssignableTo(type, numberOrBigIntType)) {
      const awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
      errorAndMaybeSuggestAwait(
        operand,
        !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType),
        diagnostic
      );
      return false;
    }
    return true;
  }
  function isReadonlyAssignmentDeclaration(d) {
    if (!isCallExpression(d)) {
      return false;
    }
    if (!isBindableObjectDefinePropertyCall(d)) {
      return false;
    }
    const objectLitType = checkExpressionCached(d.arguments[2]);
    const valueType = getTypeOfPropertyOfType(objectLitType, "value");
    if (valueType) {
      const writableProp = getPropertyOfType(objectLitType, "writable");
      const writableType = writableProp && getTypeOfSymbol(writableProp);
      if (!writableType || writableType === falseType || writableType === regularFalseType) {
        return true;
      }
      if (writableProp && writableProp.valueDeclaration && isPropertyAssignment(writableProp.valueDeclaration)) {
        const initializer = writableProp.valueDeclaration.initializer;
        const rawOriginalType = checkExpression(initializer);
        if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
          return true;
        }
      }
      return false;
    }
    const setProp = getPropertyOfType(objectLitType, "set");
    return !setProp;
  }
  function isReadonlySymbol(symbol) {
    return !!(getCheckFlags(symbol) & 8 /* Readonly */ || symbol.flags & 4 /* Property */ && getDeclarationModifierFlagsFromSymbol(symbol) & 8 /* Readonly */ || symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 6 /* Constant */ || symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) || symbol.flags & 8 /* EnumMember */ || some(symbol.declarations, isReadonlyAssignmentDeclaration));
  }
  function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
    var _a, _b;
    if (assignmentKind === 0 /* None */) {
      return false;
    }
    if (isReadonlySymbol(symbol)) {
      if (symbol.flags & 4 /* Property */ && isAccessExpression(expr) && expr.expression.kind === 110 /* ThisKeyword */) {
        const ctor = getContainingFunction(expr);
        if (!(ctor && (ctor.kind === 176 /* Constructor */ || isJSConstructor(ctor)))) {
          return true;
        }
        if (symbol.valueDeclaration) {
          const isAssignmentDeclaration2 = isBinaryExpression(symbol.valueDeclaration);
          const isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
          const isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
          const isLocalThisPropertyAssignment = isAssignmentDeclaration2 && ((_a = symbol.parent) == null ? void 0 : _a.valueDeclaration) === ctor.parent;
          const isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration2 && ((_b = symbol.parent) == null ? void 0 : _b.valueDeclaration) === ctor;
          const isWriteableSymbol = isLocalPropertyDeclaration || isLocalParameterProperty || isLocalThisPropertyAssignment || isLocalThisPropertyAssignmentConstructorFunction;
          return !isWriteableSymbol;
        }
      }
      return true;
    }
    if (isAccessExpression(expr)) {
      const node = skipParentheses(expr.expression);
      if (node.kind === 80 /* Identifier */) {
        const symbol2 = getNodeLinks(node).resolvedSymbol;
        if (symbol2.flags & 2097152 /* Alias */) {
          const declaration = getDeclarationOfAliasSymbol(symbol2);
          return !!declaration && declaration.kind === 274 /* NamespaceImport */;
        }
      }
    }
    return false;
  }
  function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
    const node = skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
    if (node.kind !== 80 /* Identifier */ && !isAccessExpression(node)) {
      error(expr, invalidReferenceMessage);
      return false;
    }
    if (node.flags & 64 /* OptionalChain */) {
      error(expr, invalidOptionalChainMessage);
      return false;
    }
    return true;
  }
  function checkDeleteExpression(node) {
    checkExpression(node.expression);
    const expr = skipParentheses(node.expression);
    if (!isAccessExpression(expr)) {
      error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
      return booleanType;
    }
    if (isPropertyAccessExpression(expr) && isPrivateIdentifier(expr.name)) {
      error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
    }
    const links = getNodeLinks(expr);
    const symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
    if (symbol) {
      if (isReadonlySymbol(symbol)) {
        error(expr, Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
      } else {
        checkDeleteExpressionMustBeOptional(expr, symbol);
      }
    }
    return booleanType;
  }
  function checkDeleteExpressionMustBeOptional(expr, symbol) {
    const type = getTypeOfSymbol(symbol);
    if (strictNullChecks && !(type.flags & (3 /* AnyOrUnknown */ | 131072 /* Never */)) && !(exactOptionalPropertyTypes ? symbol.flags & 16777216 /* Optional */ : hasTypeFacts(type, 16777216 /* IsUndefined */))) {
      error(expr, Diagnostics.The_operand_of_a_delete_operator_must_be_optional);
    }
  }
  function checkTypeOfExpression(node) {
    checkExpression(node.expression);
    return typeofType;
  }
  function checkVoidExpression(node) {
    checkNodeDeferred(node);
    return undefinedWideningType;
  }
  function checkAwaitGrammar(node) {
    let hasError = false;
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (container && isClassStaticBlockDeclaration(container)) {
      const message = isAwaitExpression(node) ? Diagnostics.await_expression_cannot_be_used_inside_a_class_static_block : Diagnostics.await_using_statements_cannot_be_used_inside_a_class_static_block;
      error(node, message);
      hasError = true;
    } else if (!(node.flags & 65536 /* AwaitContext */)) {
      if (isInTopLevelContext(node)) {
        const sourceFile = getSourceFileOfNode(node);
        if (!hasParseDiagnostics(sourceFile)) {
          let span;
          if (!isEffectiveExternalModule(sourceFile, compilerOptions)) {
            span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos));
            const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module : Diagnostics.await_using_statements_are_only_allowed_at_the_top_level_of_a_file_when_that_file_is_a_module_but_this_file_has_no_imports_or_exports_Consider_adding_an_empty_export_to_make_this_file_a_module;
            const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message);
            diagnostics.add(diagnostic);
            hasError = true;
          }
          switch (moduleKind) {
            case 100 /* Node16 */:
            case 199 /* NodeNext */:
              if (sourceFile.impliedNodeFormat === 1 /* CommonJS */) {
                span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos));
                diagnostics.add(
                  createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.The_current_file_is_a_CommonJS_module_and_cannot_use_await_at_the_top_level)
                );
                hasError = true;
                break;
              }
            // fallthrough
            case 7 /* ES2022 */:
            case 99 /* ESNext */:
            case 200 /* Preserve */:
            case 4 /* System */:
              if (languageVersion >= 4 /* ES2017 */) {
                break;
              }
            // fallthrough
            default:
              span ?? (span = getSpanOfTokenAtPosition(sourceFile, node.pos));
              const message = isAwaitExpression(node) ? Diagnostics.Top_level_await_expressions_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher : Diagnostics.Top_level_await_using_statements_are_only_allowed_when_the_module_option_is_set_to_es2022_esnext_system_node16_nodenext_or_preserve_and_the_target_option_is_set_to_es2017_or_higher;
              diagnostics.add(createFileDiagnostic(sourceFile, span.start, span.length, message));
              hasError = true;
              break;
          }
        }
      } else {
        const sourceFile = getSourceFileOfNode(node);
        if (!hasParseDiagnostics(sourceFile)) {
          const span = getSpanOfTokenAtPosition(sourceFile, node.pos);
          const message = isAwaitExpression(node) ? Diagnostics.await_expressions_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules : Diagnostics.await_using_statements_are_only_allowed_within_async_functions_and_at_the_top_levels_of_modules;
          const diagnostic = createFileDiagnostic(sourceFile, span.start, span.length, message);
          if (container && container.kind !== 176 /* Constructor */ && (getFunctionFlags(container) & 2 /* Async */) === 0) {
            const relatedInfo = createDiagnosticForNode(container, Diagnostics.Did_you_mean_to_mark_this_function_as_async);
            addRelatedInfo(diagnostic, relatedInfo);
          }
          diagnostics.add(diagnostic);
          hasError = true;
        }
      }
    }
    if (isAwaitExpression(node) && isInParameterInitializerBeforeContainingFunction(node)) {
      error(node, Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
      hasError = true;
    }
    return hasError;
  }
  function checkAwaitExpression(node) {
    addLazyDiagnostic(() => checkAwaitGrammar(node));
    const operandType = checkExpression(node.expression);
    const awaitedType = checkAwaitedType(
      operandType,
      /*withAlias*/
      true,
      node,
      Diagnostics.Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
    );
    if (awaitedType === operandType && !isErrorType(awaitedType) && !(operandType.flags & 3 /* AnyOrUnknown */)) {
      addErrorOrSuggestion(
        /*isError*/
        false,
        createDiagnosticForNode(node, Diagnostics.await_has_no_effect_on_the_type_of_this_expression)
      );
    }
    return awaitedType;
  }
  function checkPrefixUnaryExpression(node) {
    const operandType = checkExpression(node.operand);
    if (operandType === silentNeverType) {
      return silentNeverType;
    }
    switch (node.operand.kind) {
      case 9 /* NumericLiteral */:
        switch (node.operator) {
          case 41 /* MinusToken */:
            return getFreshTypeOfLiteralType(getNumberLiteralType(-node.operand.text));
          case 40 /* PlusToken */:
            return getFreshTypeOfLiteralType(getNumberLiteralType(+node.operand.text));
        }
        break;
      case 10 /* BigIntLiteral */:
        if (node.operator === 41 /* MinusToken */) {
          return getFreshTypeOfLiteralType(getBigIntLiteralType({
            negative: true,
            base10Value: parsePseudoBigInt(node.operand.text)
          }));
        }
    }
    switch (node.operator) {
      case 40 /* PlusToken */:
      case 41 /* MinusToken */:
      case 55 /* TildeToken */:
        checkNonNullType(operandType, node.operand);
        if (maybeTypeOfKindConsideringBaseConstraint(operandType, 12288 /* ESSymbolLike */)) {
          error(node.operand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(node.operator));
        }
        if (node.operator === 40 /* PlusToken */) {
          if (maybeTypeOfKindConsideringBaseConstraint(operandType, 2112 /* BigIntLike */)) {
            error(node.operand, Diagnostics.Operator_0_cannot_be_applied_to_type_1, tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
          }
          return numberType;
        }
        return getUnaryResultType(operandType);
      case 54 /* ExclamationToken */:
        checkTruthinessOfType(operandType, node.operand);
        const facts = getTypeFacts(operandType, 4194304 /* Truthy */ | 8388608 /* Falsy */);
        return facts === 4194304 /* Truthy */ ? falseType : facts === 8388608 /* Falsy */ ? trueType : booleanType;
      case 46 /* PlusPlusToken */:
      case 47 /* MinusMinusToken */:
        const ok = checkArithmeticOperandType(node.operand, checkNonNullType(operandType, node.operand), Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type);
        if (ok) {
          checkReferenceExpression(
            node.operand,
            Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access,
            Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access
          );
        }
        return getUnaryResultType(operandType);
    }
    return errorType;
  }
  function checkPostfixUnaryExpression(node) {
    const operandType = checkExpression(node.operand);
    if (operandType === silentNeverType) {
      return silentNeverType;
    }
    const ok = checkArithmeticOperandType(
      node.operand,
      checkNonNullType(operandType, node.operand),
      Diagnostics.An_arithmetic_operand_must_be_of_type_any_number_bigint_or_an_enum_type
    );
    if (ok) {
      checkReferenceExpression(
        node.operand,
        Diagnostics.The_operand_of_an_increment_or_decrement_operator_must_be_a_variable_or_a_property_access,
        Diagnostics.The_operand_of_an_increment_or_decrement_operator_may_not_be_an_optional_property_access
      );
    }
    return getUnaryResultType(operandType);
  }
  function getUnaryResultType(operandType) {
    if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
      return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */) ? numberOrBigIntType : bigintType;
    }
    return numberType;
  }
  function maybeTypeOfKindConsideringBaseConstraint(type, kind) {
    if (maybeTypeOfKind(type, kind)) {
      return true;
    }
    const baseConstraint = getBaseConstraintOrType(type);
    return !!baseConstraint && maybeTypeOfKind(baseConstraint, kind);
  }
  function maybeTypeOfKind(type, kind) {
    if (type.flags & kind) {
      return true;
    }
    if (type.flags & 3145728 /* UnionOrIntersection */) {
      const types = type.types;
      for (const t of types) {
        if (maybeTypeOfKind(t, kind)) {
          return true;
        }
      }
    }
    return false;
  }
  function isTypeAssignableToKind(source, kind, strict) {
    if (source.flags & kind) {
      return true;
    }
    if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
      return false;
    }
    return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) || !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) || !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) || !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) || !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) || !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) || !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) || !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) || !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) || !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
  }
  function allTypesAssignableToKind(source, kind, strict) {
    return source.flags & 1048576 /* Union */ ? every(source.types, (subType) => allTypesAssignableToKind(subType, kind, strict)) : isTypeAssignableToKind(source, kind, strict);
  }
  function isConstEnumObjectType(type) {
    return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
  }
  function isConstEnumSymbol(symbol) {
    return (symbol.flags & 128 /* ConstEnum */) !== 0;
  }
  function getSymbolHasInstanceMethodOfObjectType(type) {
    const hasInstancePropertyName = getPropertyNameForKnownSymbolName("hasInstance");
    if (allTypesAssignableToKind(type, 67108864 /* NonPrimitive */)) {
      const hasInstanceProperty = getPropertyOfType(type, hasInstancePropertyName);
      if (hasInstanceProperty) {
        const hasInstancePropertyType = getTypeOfSymbol(hasInstanceProperty);
        if (hasInstancePropertyType && getSignaturesOfType(hasInstancePropertyType, 0 /* Call */).length !== 0) {
          return hasInstancePropertyType;
        }
      }
    }
  }
  function checkInstanceOfExpression(left, right, leftType, rightType, checkMode) {
    if (leftType === silentNeverType || rightType === silentNeverType) {
      return silentNeverType;
    }
    if (!isTypeAny(leftType) && allTypesAssignableToKind(leftType, 402784252 /* Primitive */)) {
      error(left, Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
    }
    Debug.assert(isInstanceOfExpression(left.parent));
    const signature = getResolvedSignature(
      left.parent,
      /*candidatesOutArray*/
      void 0,
      checkMode
    );
    if (signature === resolvingSignature) {
      return silentNeverType;
    }
    const returnType = getReturnTypeOfSignature(signature);
    checkTypeAssignableTo(returnType, booleanType, right, Diagnostics.An_object_s_Symbol_hasInstance_method_must_return_a_boolean_value_for_it_to_be_used_on_the_right_hand_side_of_an_instanceof_expression);
    return booleanType;
  }
  function hasEmptyObjectIntersection(type) {
    return someType(type, (t) => t === unknownEmptyObjectType || !!(t.flags & 2097152 /* Intersection */) && isEmptyAnonymousObjectType(getBaseConstraintOrType(t)));
  }
  function checkInExpression(left, right, leftType, rightType) {
    if (leftType === silentNeverType || rightType === silentNeverType) {
      return silentNeverType;
    }
    if (isPrivateIdentifier(left)) {
      if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) {
        checkExternalEmitHelpers(left, 2097152 /* ClassPrivateFieldIn */);
      }
      if (!getNodeLinks(left).resolvedSymbol && getContainingClass(left)) {
        const isUncheckedJS = isUncheckedJSSuggestion(
          left,
          rightType.symbol,
          /*excludeClasses*/
          true
        );
        reportNonexistentProperty(left, rightType, isUncheckedJS);
      }
    } else {
      checkTypeAssignableTo(checkNonNullType(leftType, left), stringNumberSymbolType, left);
    }
    if (checkTypeAssignableTo(checkNonNullType(rightType, right), nonPrimitiveType, right)) {
      if (hasEmptyObjectIntersection(rightType)) {
        error(right, Diagnostics.Type_0_may_represent_a_primitive_value_which_is_not_permitted_as_the_right_operand_of_the_in_operator, typeToString(rightType));
      }
    }
    return booleanType;
  }
  function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
    const properties = node.properties;
    if (strictNullChecks && properties.length === 0) {
      return checkNonNullType(sourceType, node);
    }
    for (let i = 0; i < properties.length; i++) {
      checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
    }
    return sourceType;
  }
  function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis = false) {
    const properties = node.properties;
    const property = properties[propertyIndex];
    if (property.kind === 303 /* PropertyAssignment */ || property.kind === 304 /* ShorthandPropertyAssignment */) {
      const name = property.name;
      const exprType = getLiteralTypeFromPropertyName(name);
      if (isTypeUsableAsPropertyName(exprType)) {
        const text = getPropertyNameFromType(exprType);
        const prop = getPropertyOfType(objectLiteralType, text);
        if (prop) {
          markPropertyAsReferenced(prop, property, rightIsThis);
          checkPropertyAccessibility(
            property,
            /*isSuper*/
            false,
            /*writing*/
            true,
            objectLiteralType,
            prop
          );
        }
      }
      const elementType = getIndexedAccessType(objectLiteralType, exprType, 32 /* ExpressionPosition */ | (hasDefaultValue(property) ? 16 /* AllowMissing */ : 0), name);
      const type = getFlowTypeOfDestructuring(property, elementType);
      return checkDestructuringAssignment(property.kind === 304 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
    } else if (property.kind === 305 /* SpreadAssignment */) {
      if (propertyIndex < properties.length - 1) {
        error(property, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      } else {
        if (languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) {
          checkExternalEmitHelpers(property, 4 /* Rest */);
        }
        const nonRestNames = [];
        if (allProperties) {
          for (const otherProperty of allProperties) {
            if (!isSpreadAssignment(otherProperty)) {
              nonRestNames.push(otherProperty.name);
            }
          }
        }
        const type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
        checkGrammarForDisallowedTrailingComma(allProperties, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
        return checkDestructuringAssignment(property.expression, type);
      }
    } else {
      error(property, Diagnostics.Property_assignment_expected);
    }
  }
  function checkArrayLiteralAssignment(node, sourceType, checkMode) {
    const elements = node.elements;
    if (languageVersion < LanguageFeatureMinimumTarget.DestructuringAssignment && compilerOptions.downlevelIteration) {
      checkExternalEmitHelpers(node, 512 /* Read */);
    }
    const possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType;
    let inBoundsType = compilerOptions.noUncheckedIndexedAccess ? void 0 : possiblyOutOfBoundsType;
    for (let i = 0; i < elements.length; i++) {
      let type = possiblyOutOfBoundsType;
      if (node.elements[i].kind === 230 /* SpreadElement */) {
        type = inBoundsType = inBoundsType ?? (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType);
      }
      checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode);
    }
    return sourceType;
  }
  function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
    const elements = node.elements;
    const element = elements[elementIndex];
    if (element.kind !== 232 /* OmittedExpression */) {
      if (element.kind !== 230 /* SpreadElement */) {
        const indexType = getNumberLiteralType(elementIndex);
        if (isArrayLikeType(sourceType)) {
          const accessFlags = 32 /* ExpressionPosition */ | (hasDefaultValue(element) ? 16 /* AllowMissing */ : 0);
          const elementType2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, accessFlags, createSyntheticExpression(element, indexType)) || errorType;
          const assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType2, 524288 /* NEUndefined */) : elementType2;
          const type = getFlowTypeOfDestructuring(element, assignedType);
          return checkDestructuringAssignment(element, type, checkMode);
        }
        return checkDestructuringAssignment(element, elementType, checkMode);
      }
      if (elementIndex < elements.length - 1) {
        error(element, Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
      } else {
        const restExpression = element.expression;
        if (restExpression.kind === 226 /* BinaryExpression */ && restExpression.operatorToken.kind === 64 /* EqualsToken */) {
          error(restExpression.operatorToken, Diagnostics.A_rest_element_cannot_have_an_initializer);
        } else {
          checkGrammarForDisallowedTrailingComma(node.elements, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
          const type = everyType(sourceType, isTupleType) ? mapType(sourceType, (t) => sliceTupleType(t, elementIndex)) : createArrayType(elementType);
          return checkDestructuringAssignment(restExpression, type, checkMode);
        }
      }
    }
    return void 0;
  }
  function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
    let target;
    if (exprOrAssignment.kind === 304 /* ShorthandPropertyAssignment */) {
      const prop = exprOrAssignment;
      if (prop.objectAssignmentInitializer) {
        if (strictNullChecks && !hasTypeFacts(checkExpression(prop.objectAssignmentInitializer), 16777216 /* IsUndefined */)) {
          sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
        }
        checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
      }
      target = exprOrAssignment.name;
    } else {
      target = exprOrAssignment;
    }
    if (target.kind === 226 /* BinaryExpression */ && target.operatorToken.kind === 64 /* EqualsToken */) {
      checkBinaryExpression(target, checkMode);
      target = target.left;
      if (strictNullChecks) {
        sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
      }
    }
    if (target.kind === 210 /* ObjectLiteralExpression */) {
      return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
    }
    if (target.kind === 209 /* ArrayLiteralExpression */) {
      return checkArrayLiteralAssignment(target, sourceType, checkMode);
    }
    return checkReferenceAssignment(target, sourceType, checkMode);
  }
  function checkReferenceAssignment(target, sourceType, checkMode) {
    const targetType = checkExpression(target, checkMode);
    const error2 = target.parent.kind === 305 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
    const optionalError = target.parent.kind === 305 /* SpreadAssignment */ ? Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access : Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
    if (checkReferenceExpression(target, error2, optionalError)) {
      checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
    }
    if (isPrivateIdentifierPropertyAccessExpression(target)) {
      checkExternalEmitHelpers(target.parent, 1048576 /* ClassPrivateFieldSet */);
    }
    return sourceType;
  }
  function isSideEffectFree(node) {
    node = skipParentheses(node);
    switch (node.kind) {
      case 80 /* Identifier */:
      case 11 /* StringLiteral */:
      case 14 /* RegularExpressionLiteral */:
      case 215 /* TaggedTemplateExpression */:
      case 228 /* TemplateExpression */:
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 9 /* NumericLiteral */:
      case 10 /* BigIntLiteral */:
      case 112 /* TrueKeyword */:
      case 97 /* FalseKeyword */:
      case 106 /* NullKeyword */:
      case 157 /* UndefinedKeyword */:
      case 218 /* FunctionExpression */:
      case 231 /* ClassExpression */:
      case 219 /* ArrowFunction */:
      case 209 /* ArrayLiteralExpression */:
      case 210 /* ObjectLiteralExpression */:
      case 221 /* TypeOfExpression */:
      case 235 /* NonNullExpression */:
      case 285 /* JsxSelfClosingElement */:
      case 284 /* JsxElement */:
        return true;
      case 227 /* ConditionalExpression */:
        return isSideEffectFree(node.whenTrue) && isSideEffectFree(node.whenFalse);
      case 226 /* BinaryExpression */:
        if (isAssignmentOperator(node.operatorToken.kind)) {
          return false;
        }
        return isSideEffectFree(node.left) && isSideEffectFree(node.right);
      case 224 /* PrefixUnaryExpression */:
      case 225 /* PostfixUnaryExpression */:
        switch (node.operator) {
          case 54 /* ExclamationToken */:
          case 40 /* PlusToken */:
          case 41 /* MinusToken */:
          case 55 /* TildeToken */:
            return true;
        }
        return false;
      // Some forms listed here for clarity
      case 222 /* VoidExpression */:
      // Explicit opt-out
      case 216 /* TypeAssertionExpression */:
      // Not SEF, but can produce useful type warnings
      case 234 /* AsExpression */:
      // Not SEF, but can produce useful type warnings
      default:
        return false;
    }
  }
  function isTypeEqualityComparableTo(source, target) {
    return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
  }
  function createCheckBinaryExpression() {
    const trampoline = createBinaryExpressionTrampoline(onEnter, onLeft, onOperator, onRight, onExit, foldState);
    return (node, checkMode) => {
      const result = trampoline(node, checkMode);
      Debug.assertIsDefined(result);
      return result;
    };
    function onEnter(node, state, checkMode) {
      if (state) {
        state.stackIndex++;
        state.skip = false;
        setLeftType(
          state,
          /*type*/
          void 0
        );
        setLastResult(
          state,
          /*type*/
          void 0
        );
      } else {
        state = {
          checkMode,
          skip: false,
          stackIndex: 0,
          typeStack: [void 0, void 0]
        };
      }
      if (isInJSFile(node) && getAssignedExpandoInitializer(node)) {
        state.skip = true;
        setLastResult(state, checkExpression(node.right, checkMode));
        return state;
      }
      checkNullishCoalesceOperands(node);
      const operator = node.operatorToken.kind;
      if (operator === 64 /* EqualsToken */ && (node.left.kind === 210 /* ObjectLiteralExpression */ || node.left.kind === 209 /* ArrayLiteralExpression */)) {
        state.skip = true;
        setLastResult(state, checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 110 /* ThisKeyword */));
        return state;
      }
      return state;
    }
    function onLeft(left, state, _node) {
      if (!state.skip) {
        return maybeCheckExpression(state, left);
      }
    }
    function onOperator(operatorToken, state, node) {
      if (!state.skip) {
        const leftType = getLastResult(state);
        Debug.assertIsDefined(leftType);
        setLeftType(state, leftType);
        setLastResult(
          state,
          /*type*/
          void 0
        );
        const operator = operatorToken.kind;
        if (isLogicalOrCoalescingBinaryOperator(operator)) {
          let parent = node.parent;
          while (parent.kind === 217 /* ParenthesizedExpression */ || isLogicalOrCoalescingBinaryExpression(parent)) {
            parent = parent.parent;
          }
          if (operator === 56 /* AmpersandAmpersandToken */ || isIfStatement(parent)) {
            checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.left, leftType, isIfStatement(parent) ? parent.thenStatement : void 0);
          }
          if (isBinaryLogicalOperator(operator)) {
            checkTruthinessOfType(leftType, node.left);
          }
        }
      }
    }
    function onRight(right, state, _node) {
      if (!state.skip) {
        return maybeCheckExpression(state, right);
      }
    }
    function onExit(node, state) {
      let result;
      if (state.skip) {
        result = getLastResult(state);
      } else {
        const leftType = getLeftType(state);
        Debug.assertIsDefined(leftType);
        const rightType = getLastResult(state);
        Debug.assertIsDefined(rightType);
        result = checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, state.checkMode, node);
      }
      state.skip = false;
      setLeftType(
        state,
        /*type*/
        void 0
      );
      setLastResult(
        state,
        /*type*/
        void 0
      );
      state.stackIndex--;
      return result;
    }
    function foldState(state, result, _side) {
      setLastResult(state, result);
      return state;
    }
    function maybeCheckExpression(state, node) {
      if (isBinaryExpression(node)) {
        return node;
      }
      setLastResult(state, checkExpression(node, state.checkMode));
    }
    function getLeftType(state) {
      return state.typeStack[state.stackIndex];
    }
    function setLeftType(state, type) {
      state.typeStack[state.stackIndex] = type;
    }
    function getLastResult(state) {
      return state.typeStack[state.stackIndex + 1];
    }
    function setLastResult(state, type) {
      state.typeStack[state.stackIndex + 1] = type;
    }
  }
  function checkNullishCoalesceOperands(node) {
    const { left, operatorToken, right } = node;
    if (operatorToken.kind === 61 /* QuestionQuestionToken */) {
      if (isBinaryExpression(left) && (left.operatorToken.kind === 57 /* BarBarToken */ || left.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) {
        grammarErrorOnNode(left, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(left.operatorToken.kind), tokenToString(operatorToken.kind));
      }
      if (isBinaryExpression(right) && (right.operatorToken.kind === 57 /* BarBarToken */ || right.operatorToken.kind === 56 /* AmpersandAmpersandToken */)) {
        grammarErrorOnNode(right, Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, tokenToString(right.operatorToken.kind), tokenToString(operatorToken.kind));
      }
      const leftTarget = skipOuterExpressions(left, 31 /* All */);
      const nullishSemantics = getSyntacticNullishnessSemantics(leftTarget);
      if (nullishSemantics !== 3 /* Sometimes */) {
        if (node.parent.kind === 226 /* BinaryExpression */) {
          error(leftTarget, Diagnostics.This_binary_expression_is_never_nullish_Are_you_missing_parentheses);
        } else {
          if (nullishSemantics === 1 /* Always */) {
            error(leftTarget, Diagnostics.This_expression_is_always_nullish);
          } else {
            error(leftTarget, Diagnostics.Right_operand_of_is_unreachable_because_the_left_operand_is_never_nullish);
          }
        }
      }
    }
  }
  function getSyntacticNullishnessSemantics(node) {
    node = skipOuterExpressions(node);
    switch (node.kind) {
      case 223 /* AwaitExpression */:
      case 213 /* CallExpression */:
      case 215 /* TaggedTemplateExpression */:
      case 212 /* ElementAccessExpression */:
      case 236 /* MetaProperty */:
      case 214 /* NewExpression */:
      case 211 /* PropertyAccessExpression */:
      case 229 /* YieldExpression */:
      case 110 /* ThisKeyword */:
        return 3 /* Sometimes */;
      case 226 /* BinaryExpression */:
        switch (node.operatorToken.kind) {
          case 64 /* EqualsToken */:
          case 61 /* QuestionQuestionToken */:
          case 78 /* QuestionQuestionEqualsToken */:
          case 57 /* BarBarToken */:
          case 76 /* BarBarEqualsToken */:
          case 56 /* AmpersandAmpersandToken */:
          case 77 /* AmpersandAmpersandEqualsToken */:
            return 3 /* Sometimes */;
          case 28 /* CommaToken */:
            return getSyntacticNullishnessSemantics(node.right);
        }
        return 2 /* Never */;
      case 227 /* ConditionalExpression */:
        return getSyntacticNullishnessSemantics(node.whenTrue) | getSyntacticNullishnessSemantics(node.whenFalse);
      case 106 /* NullKeyword */:
        return 1 /* Always */;
      case 80 /* Identifier */:
        if (getResolvedSymbol(node) === undefinedSymbol) {
          return 1 /* Always */;
        }
        return 3 /* Sometimes */;
    }
    return 2 /* Never */;
  }
  function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
    const operator = operatorToken.kind;
    if (operator === 64 /* EqualsToken */ && (left.kind === 210 /* ObjectLiteralExpression */ || left.kind === 209 /* ArrayLiteralExpression */)) {
      return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 110 /* ThisKeyword */);
    }
    let leftType;
    if (isBinaryLogicalOperator(operator)) {
      leftType = checkTruthinessExpression(left, checkMode);
    } else {
      leftType = checkExpression(left, checkMode);
    }
    const rightType = checkExpression(right, checkMode);
    return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode);
  }
  function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, checkMode, errorNode) {
    const operator = operatorToken.kind;
    switch (operator) {
      case 42 /* AsteriskToken */:
      case 43 /* AsteriskAsteriskToken */:
      case 67 /* AsteriskEqualsToken */:
      case 68 /* AsteriskAsteriskEqualsToken */:
      case 44 /* SlashToken */:
      case 69 /* SlashEqualsToken */:
      case 45 /* PercentToken */:
      case 70 /* PercentEqualsToken */:
      case 41 /* MinusToken */:
      case 66 /* MinusEqualsToken */:
      case 48 /* LessThanLessThanToken */:
      case 71 /* LessThanLessThanEqualsToken */:
      case 49 /* GreaterThanGreaterThanToken */:
      case 72 /* GreaterThanGreaterThanEqualsToken */:
      case 50 /* GreaterThanGreaterThanGreaterThanToken */:
      case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
      case 52 /* BarToken */:
      case 75 /* BarEqualsToken */:
      case 53 /* CaretToken */:
      case 79 /* CaretEqualsToken */:
      case 51 /* AmpersandToken */:
      case 74 /* AmpersandEqualsToken */:
        if (leftType === silentNeverType || rightType === silentNeverType) {
          return silentNeverType;
        }
        leftType = checkNonNullType(leftType, left);
        rightType = checkNonNullType(rightType, right);
        let suggestedOperator;
        if (leftType.flags & 528 /* BooleanLike */ && rightType.flags & 528 /* BooleanLike */ && (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== void 0) {
          error(errorNode || operatorToken, Diagnostics.The_0_operator_is_not_allowed_for_boolean_types_Consider_using_1_instead, tokenToString(operatorToken.kind), tokenToString(suggestedOperator));
          return numberType;
        } else {
          const leftOk = checkArithmeticOperandType(
            left,
            leftType,
            Diagnostics.The_left_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type,
            /*isAwaitValid*/
            true
          );
          const rightOk = checkArithmeticOperandType(
            right,
            rightType,
            Diagnostics.The_right_hand_side_of_an_arithmetic_operation_must_be_of_type_any_number_bigint_or_an_enum_type,
            /*isAwaitValid*/
            true
          );
          let resultType2;
          if (isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */) || // Or, if neither could be bigint, implicit coercion results in a number result
          !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
            resultType2 = numberType;
          } else if (bothAreBigIntLike(leftType, rightType)) {
            switch (operator) {
              case 50 /* GreaterThanGreaterThanGreaterThanToken */:
              case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                reportOperatorError();
                break;
              case 43 /* AsteriskAsteriskToken */:
              case 68 /* AsteriskAsteriskEqualsToken */:
                if (languageVersion < 3 /* ES2016 */) {
                  error(errorNode, Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later);
                }
            }
            resultType2 = bigintType;
          } else {
            reportOperatorError(bothAreBigIntLike);
            resultType2 = errorType;
          }
          if (leftOk && rightOk) {
            checkAssignmentOperator(resultType2);
            switch (operator) {
              case 48 /* LessThanLessThanToken */:
              case 71 /* LessThanLessThanEqualsToken */:
              case 49 /* GreaterThanGreaterThanToken */:
              case 72 /* GreaterThanGreaterThanEqualsToken */:
              case 50 /* GreaterThanGreaterThanGreaterThanToken */:
              case 73 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
                const rhsEval = evaluate(right);
                if (typeof rhsEval.value === "number" && Math.abs(rhsEval.value) >= 32) {
                  errorOrSuggestion(
                    isEnumMember(walkUpParenthesizedExpressions(right.parent.parent)),
                    // elevate from suggestion to error within an enum member
                    errorNode || operatorToken,
                    Diagnostics.This_operation_can_be_simplified_This_shift_is_identical_to_0_1_2,
                    getTextOfNode(left),
                    tokenToString(operator),
                    rhsEval.value % 32
                  );
                }
                break;
              default:
                break;
            }
          }
          return resultType2;
        }
      case 40 /* PlusToken */:
      case 65 /* PlusEqualsToken */:
        if (leftType === silentNeverType || rightType === silentNeverType) {
          return silentNeverType;
        }
        if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */)) {
          leftType = checkNonNullType(leftType, left);
          rightType = checkNonNullType(rightType, right);
        }
        let resultType;
        if (isTypeAssignableToKind(
          leftType,
          296 /* NumberLike */,
          /*strict*/
          true
        ) && isTypeAssignableToKind(
          rightType,
          296 /* NumberLike */,
          /*strict*/
          true
        )) {
          resultType = numberType;
        } else if (isTypeAssignableToKind(
          leftType,
          2112 /* BigIntLike */,
          /*strict*/
          true
        ) && isTypeAssignableToKind(
          rightType,
          2112 /* BigIntLike */,
          /*strict*/
          true
        )) {
          resultType = bigintType;
        } else if (isTypeAssignableToKind(
          leftType,
          402653316 /* StringLike */,
          /*strict*/
          true
        ) || isTypeAssignableToKind(
          rightType,
          402653316 /* StringLike */,
          /*strict*/
          true
        )) {
          resultType = stringType;
        } else if (isTypeAny(leftType) || isTypeAny(rightType)) {
          resultType = isErrorType(leftType) || isErrorType(rightType) ? errorType : anyType;
        }
        if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
          return resultType;
        }
        if (!resultType) {
          const closeEnoughKind = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */;
          reportOperatorError(
            (left2, right2) => isTypeAssignableToKind(left2, closeEnoughKind) && isTypeAssignableToKind(right2, closeEnoughKind)
          );
          return anyType;
        }
        if (operator === 65 /* PlusEqualsToken */) {
          checkAssignmentOperator(resultType);
        }
        return resultType;
      case 30 /* LessThanToken */:
      case 32 /* GreaterThanToken */:
      case 33 /* LessThanEqualsToken */:
      case 34 /* GreaterThanEqualsToken */:
        if (checkForDisallowedESSymbolOperand(operator)) {
          leftType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(leftType, left));
          rightType = getBaseTypeOfLiteralTypeForComparison(checkNonNullType(rightType, right));
          reportOperatorErrorUnless((left2, right2) => {
            if (isTypeAny(left2) || isTypeAny(right2)) {
              return true;
            }
            const leftAssignableToNumber = isTypeAssignableTo(left2, numberOrBigIntType);
            const rightAssignableToNumber = isTypeAssignableTo(right2, numberOrBigIntType);
            return leftAssignableToNumber && rightAssignableToNumber || !leftAssignableToNumber && !rightAssignableToNumber && areTypesComparable(left2, right2);
          });
        }
        return booleanType;
      case 35 /* EqualsEqualsToken */:
      case 36 /* ExclamationEqualsToken */:
      case 37 /* EqualsEqualsEqualsToken */:
      case 38 /* ExclamationEqualsEqualsToken */:
        if (!(checkMode && checkMode & 64 /* TypeOnly */)) {
          if ((isLiteralExpressionOfObject(left) || isLiteralExpressionOfObject(right)) && // only report for === and !== in JS, not == or !=
          (!isInJSFile(left) || (operator === 37 /* EqualsEqualsEqualsToken */ || operator === 38 /* ExclamationEqualsEqualsToken */))) {
            const eqType = operator === 35 /* EqualsEqualsToken */ || operator === 37 /* EqualsEqualsEqualsToken */;
            error(errorNode, Diagnostics.This_condition_will_always_return_0_since_JavaScript_compares_objects_by_reference_not_value, eqType ? "false" : "true");
          }
          checkNaNEquality(errorNode, operator, left, right);
          reportOperatorErrorUnless((left2, right2) => isTypeEqualityComparableTo(left2, right2) || isTypeEqualityComparableTo(right2, left2));
        }
        return booleanType;
      case 104 /* InstanceOfKeyword */:
        return checkInstanceOfExpression(left, right, leftType, rightType, checkMode);
      case 103 /* InKeyword */:
        return checkInExpression(left, right, leftType, rightType);
      case 56 /* AmpersandAmpersandToken */:
      case 77 /* AmpersandAmpersandEqualsToken */: {
        const resultType2 = hasTypeFacts(leftType, 4194304 /* Truthy */) ? getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) : leftType;
        if (operator === 77 /* AmpersandAmpersandEqualsToken */) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case 57 /* BarBarToken */:
      case 76 /* BarBarEqualsToken */: {
        const resultType2 = hasTypeFacts(leftType, 8388608 /* Falsy */) ? getUnionType([getNonNullableType(removeDefinitelyFalsyTypes(leftType)), rightType], 2 /* Subtype */) : leftType;
        if (operator === 76 /* BarBarEqualsToken */) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case 61 /* QuestionQuestionToken */:
      case 78 /* QuestionQuestionEqualsToken */: {
        const resultType2 = hasTypeFacts(leftType, 262144 /* EQUndefinedOrNull */) ? getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) : leftType;
        if (operator === 78 /* QuestionQuestionEqualsToken */) {
          checkAssignmentOperator(rightType);
        }
        return resultType2;
      }
      case 64 /* EqualsToken */:
        const declKind = isBinaryExpression(left.parent) ? getAssignmentDeclarationKind(left.parent) : 0 /* None */;
        checkAssignmentDeclaration(declKind, rightType);
        if (isAssignmentDeclaration2(declKind)) {
          if (!(rightType.flags & 524288 /* Object */) || declKind !== 2 /* ModuleExports */ && declKind !== 6 /* Prototype */ && !isEmptyObjectType(rightType) && !isFunctionObjectType(rightType) && !(getObjectFlags(rightType) & 1 /* Class */)) {
            checkAssignmentOperator(rightType);
          }
          return leftType;
        } else {
          checkAssignmentOperator(rightType);
          return rightType;
        }
      case 28 /* CommaToken */:
        if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isIndirectCall(left.parent)) {
          const sf = getSourceFileOfNode(left);
          const sourceText = sf.text;
          const start = skipTrivia(sourceText, left.pos);
          const isInDiag2657 = sf.parseDiagnostics.some((diag2) => {
            if (diag2.code !== Diagnostics.JSX_expressions_must_have_one_parent_element.code) return false;
            return textSpanContainsPosition(diag2, start);
          });
          if (!isInDiag2657) error(left, Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
        }
        return rightType;
      default:
        return Debug.fail();
    }
    function bothAreBigIntLike(left2, right2) {
      return isTypeAssignableToKind(left2, 2112 /* BigIntLike */) && isTypeAssignableToKind(right2, 2112 /* BigIntLike */);
    }
    function checkAssignmentDeclaration(kind, rightType2) {
      if (kind === 2 /* ModuleExports */) {
        for (const prop of getPropertiesOfObjectType(rightType2)) {
          const propType = getTypeOfSymbol(prop);
          if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
            const name = prop.escapedName;
            const symbol = resolveName(
              prop.valueDeclaration,
              name,
              788968 /* Type */,
              /*nameNotFoundMessage*/
              void 0,
              /*isUse*/
              false
            );
            if ((symbol == null ? void 0 : symbol.declarations) && symbol.declarations.some(isJSDocTypedefTag)) {
              addDuplicateDeclarationErrorsForSymbols(symbol, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), prop);
              addDuplicateDeclarationErrorsForSymbols(prop, Diagnostics.Duplicate_identifier_0, unescapeLeadingUnderscores(name), symbol);
            }
          }
        }
      }
    }
    function isIndirectCall(node) {
      return node.parent.kind === 217 /* ParenthesizedExpression */ && isNumericLiteral(node.left) && node.left.text === "0" && (isCallExpression(node.parent.parent) && node.parent.parent.expression === node.parent || node.parent.parent.kind === 215 /* TaggedTemplateExpression */) && // special-case for "eval" because it's the only non-access case where an indirect call actually affects behavior.
      (isAccessExpression(node.right) || isIdentifier(node.right) && node.right.escapedText === "eval");
    }
    function checkForDisallowedESSymbolOperand(operator2) {
      const offendingSymbolOperand = maybeTypeOfKindConsideringBaseConstraint(leftType, 12288 /* ESSymbolLike */) ? left : maybeTypeOfKindConsideringBaseConstraint(rightType, 12288 /* ESSymbolLike */) ? right : void 0;
      if (offendingSymbolOperand) {
        error(offendingSymbolOperand, Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, tokenToString(operator2));
        return false;
      }
      return true;
    }
    function getSuggestedBooleanOperator(operator2) {
      switch (operator2) {
        case 52 /* BarToken */:
        case 75 /* BarEqualsToken */:
          return 57 /* BarBarToken */;
        case 53 /* CaretToken */:
        case 79 /* CaretEqualsToken */:
          return 38 /* ExclamationEqualsEqualsToken */;
        case 51 /* AmpersandToken */:
        case 74 /* AmpersandEqualsToken */:
          return 56 /* AmpersandAmpersandToken */;
        default:
          return void 0;
      }
    }
    function checkAssignmentOperator(valueType) {
      if (isAssignmentOperator(operator)) {
        addLazyDiagnostic(checkAssignmentOperatorWorker);
      }
      function checkAssignmentOperatorWorker() {
        let assigneeType = leftType;
        if (isCompoundAssignment(operatorToken.kind) && left.kind === 211 /* PropertyAccessExpression */) {
          assigneeType = checkPropertyAccessExpression(
            left,
            /*checkMode*/
            void 0,
            /*writeOnly*/
            true
          );
        }
        if (checkReferenceExpression(left, Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access, Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access)) {
          let headMessage;
          if (exactOptionalPropertyTypes && isPropertyAccessExpression(left) && maybeTypeOfKind(valueType, 32768 /* Undefined */)) {
            const target = getTypeOfPropertyOfType(getTypeOfExpression(left.expression), left.name.escapedText);
            if (isExactOptionalPropertyMismatch(valueType, target)) {
              headMessage = Diagnostics.Type_0_is_not_assignable_to_type_1_with_exactOptionalPropertyTypes_Colon_true_Consider_adding_undefined_to_the_type_of_the_target;
            }
          }
          checkTypeAssignableToAndOptionallyElaborate(valueType, assigneeType, left, right, headMessage);
        }
      }
    }
    function isAssignmentDeclaration2(kind) {
      var _a;
      switch (kind) {
        case 2 /* ModuleExports */:
          return true;
        case 1 /* ExportsProperty */:
        case 5 /* Property */:
        case 6 /* Prototype */:
        case 3 /* PrototypeProperty */:
        case 4 /* ThisProperty */:
          const symbol = getSymbolOfNode(left);
          const init = getAssignedExpandoInitializer(right);
          return !!init && isObjectLiteralExpression(init) && !!((_a = symbol == null ? void 0 : symbol.exports) == null ? void 0 : _a.size);
        default:
          return false;
      }
    }
    function reportOperatorErrorUnless(typesAreCompatible) {
      if (!typesAreCompatible(leftType, rightType)) {
        reportOperatorError(typesAreCompatible);
        return true;
      }
      return false;
    }
    function reportOperatorError(isRelated) {
      let wouldWorkWithAwait = false;
      const errNode = errorNode || operatorToken;
      if (isRelated) {
        const awaitedLeftType = getAwaitedTypeNoAlias(leftType);
        const awaitedRightType = getAwaitedTypeNoAlias(rightType);
        wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType) && !!(awaitedLeftType && awaitedRightType) && isRelated(awaitedLeftType, awaitedRightType);
      }
      let effectiveLeft = leftType;
      let effectiveRight = rightType;
      if (!wouldWorkWithAwait && isRelated) {
        [effectiveLeft, effectiveRight] = getBaseTypesIfUnrelated(leftType, rightType, isRelated);
      }
      const [leftStr, rightStr] = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight);
      if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
        errorAndMaybeSuggestAwait(
          errNode,
          wouldWorkWithAwait,
          Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2,
          tokenToString(operatorToken.kind),
          leftStr,
          rightStr
        );
      }
    }
    function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
      switch (operatorToken.kind) {
        case 37 /* EqualsEqualsEqualsToken */:
        case 35 /* EqualsEqualsToken */:
        case 38 /* ExclamationEqualsEqualsToken */:
        case 36 /* ExclamationEqualsToken */:
          return errorAndMaybeSuggestAwait(
            errNode,
            maybeMissingAwait,
            Diagnostics.This_comparison_appears_to_be_unintentional_because_the_types_0_and_1_have_no_overlap,
            leftStr,
            rightStr
          );
        default:
          return void 0;
      }
    }
    function checkNaNEquality(errorNode2, operator2, left2, right2) {
      const isLeftNaN = isGlobalNaN(skipParentheses(left2));
      const isRightNaN = isGlobalNaN(skipParentheses(right2));
      if (isLeftNaN || isRightNaN) {
        const err = error(errorNode2, Diagnostics.This_condition_will_always_return_0, tokenToString(operator2 === 37 /* EqualsEqualsEqualsToken */ || operator2 === 35 /* EqualsEqualsToken */ ? 97 /* FalseKeyword */ : 112 /* TrueKeyword */));
        if (isLeftNaN && isRightNaN) return;
        const operatorString = operator2 === 38 /* ExclamationEqualsEqualsToken */ || operator2 === 36 /* ExclamationEqualsToken */ ? tokenToString(54 /* ExclamationToken */) : "";
        const location = isLeftNaN ? right2 : left2;
        const expression = skipParentheses(location);
        addRelatedInfo(err, createDiagnosticForNode(location, Diagnostics.Did_you_mean_0, `${operatorString}Number.isNaN(${isEntityNameExpression(expression) ? entityNameToString(expression) : "..."})`));
      }
    }
    function isGlobalNaN(expr) {
      if (isIdentifier(expr) && expr.escapedText === "NaN") {
        const globalNaNSymbol = getGlobalNaNSymbol();
        return !!globalNaNSymbol && globalNaNSymbol === getResolvedSymbol(expr);
      }
      return false;
    }
  }
  function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
    let effectiveLeft = leftType;
    let effectiveRight = rightType;
    const leftBase = getBaseTypeOfLiteralType(leftType);
    const rightBase = getBaseTypeOfLiteralType(rightType);
    if (!isRelated(leftBase, rightBase)) {
      effectiveLeft = leftBase;
      effectiveRight = rightBase;
    }
    return [effectiveLeft, effectiveRight];
  }
  function checkYieldExpression(node) {
    addLazyDiagnostic(checkYieldExpressionGrammar);
    const func = getContainingFunction(node);
    if (!func) return anyType;
    const functionFlags = getFunctionFlags(func);
    if (!(functionFlags & 1 /* Generator */)) {
      return anyType;
    }
    const isAsync = (functionFlags & 2 /* Async */) !== 0;
    if (node.asteriskToken) {
      if (isAsync && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) {
        checkExternalEmitHelpers(node, 26624 /* AsyncDelegatorIncludes */);
      }
      if (!isAsync && languageVersion < LanguageFeatureMinimumTarget.Generators && compilerOptions.downlevelIteration) {
        checkExternalEmitHelpers(node, 256 /* Values */);
      }
    }
    let returnType = getReturnTypeFromAnnotation(func);
    if (returnType && returnType.flags & 1048576 /* Union */) {
      returnType = filterType(returnType, (t) => checkGeneratorInstantiationAssignabilityToReturnType(
        t,
        functionFlags,
        /*errorNode*/
        void 0
      ));
    }
    const iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
    const signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
    const signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
    const yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
    const yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, signatureNextType, isAsync);
    if (returnType && yieldedType) {
      checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
    }
    if (node.asteriskToken) {
      const use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
      return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression) || anyType;
    } else if (returnType) {
      return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync) || anyType;
    }
    let type = getContextualIterationType(2 /* Next */, func);
    if (!type) {
      type = anyType;
      addLazyDiagnostic(() => {
        if (noImplicitAny && !expressionResultIsUnused(node)) {
          const contextualType = getContextualType(
            node,
            /*contextFlags*/
            void 0
          );
          if (!contextualType || isTypeAny(contextualType)) {
            error(node, Diagnostics.yield_expression_implicitly_results_in_an_any_type_because_its_containing_generator_lacks_a_return_type_annotation);
          }
        }
      });
    }
    return type;
    function checkYieldExpressionGrammar() {
      if (!(node.flags & 16384 /* YieldContext */)) {
        grammarErrorOnFirstToken(node, Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
      }
      if (isInParameterInitializerBeforeContainingFunction(node)) {
        error(node, Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
      }
    }
  }
  function checkConditionalExpression(node, checkMode) {
    const type = checkTruthinessExpression(node.condition, checkMode);
    checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.condition, type, node.whenTrue);
    const type1 = checkExpression(node.whenTrue, checkMode);
    const type2 = checkExpression(node.whenFalse, checkMode);
    return getUnionType([type1, type2], 2 /* Subtype */);
  }
  function isTemplateLiteralContext(node) {
    const parent = node.parent;
    return isParenthesizedExpression(parent) && isTemplateLiteralContext(parent) || isElementAccessExpression(parent) && parent.argumentExpression === node;
  }
  function checkTemplateExpression(node) {
    const texts = [node.head.text];
    const types = [];
    for (const span of node.templateSpans) {
      const type = checkExpression(span.expression);
      if (maybeTypeOfKindConsideringBaseConstraint(type, 12288 /* ESSymbolLike */)) {
        error(span.expression, Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
      }
      texts.push(span.literal.text);
      types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType);
    }
    const evaluated = node.parent.kind !== 215 /* TaggedTemplateExpression */ && evaluate(node).value;
    if (evaluated) {
      return getFreshTypeOfLiteralType(getStringLiteralType(evaluated));
    }
    if (isConstContext(node) || isTemplateLiteralContext(node) || someType(getContextualType(
      node,
      /*contextFlags*/
      void 0
    ) || unknownType, isTemplateLiteralContextualType)) {
      return getTemplateLiteralType(texts, types);
    }
    return stringType;
  }
  function isTemplateLiteralContextualType(type) {
    return !!(type.flags & (128 /* StringLiteral */ | 134217728 /* TemplateLiteral */) || type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 402653316 /* StringLike */));
  }
  function getContextNode(node) {
    if (isJsxAttributes(node) && !isJsxSelfClosingElement(node.parent)) {
      return node.parent.parent;
    }
    return node;
  }
  function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
    const contextNode = getContextNode(node);
    pushContextualType(
      contextNode,
      contextualType,
      /*isCache*/
      false
    );
    pushInferenceContext(contextNode, inferenceContext);
    const type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
    if (inferenceContext && inferenceContext.intraExpressionInferenceSites) {
      inferenceContext.intraExpressionInferenceSites = void 0;
    }
    const result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(
      contextualType,
      node,
      /*contextFlags*/
      void 0
    )) ? getRegularTypeOfLiteralType(type) : type;
    popInferenceContext();
    popContextualType();
    return result;
  }
  function checkExpressionCached(node, checkMode) {
    if (checkMode) {
      return checkExpression(node, checkMode);
    }
    const links = getNodeLinks(node);
    if (!links.resolvedType) {
      const saveFlowLoopStart = flowLoopStart;
      const saveFlowTypeCache = flowTypeCache;
      flowLoopStart = flowLoopCount;
      flowTypeCache = void 0;
      links.resolvedType = checkExpression(node, checkMode);
      flowTypeCache = saveFlowTypeCache;
      flowLoopStart = saveFlowLoopStart;
    }
    return links.resolvedType;
  }
  function isTypeAssertion(node) {
    node = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    return node.kind === 216 /* TypeAssertionExpression */ || node.kind === 234 /* AsExpression */ || isJSDocTypeAssertion(node);
  }
  function checkDeclarationInitializer(declaration, checkMode, contextualType) {
    const initializer = getEffectiveInitializer(declaration);
    if (isInJSFile(declaration)) {
      const typeNode = tryGetJSDocSatisfiesTypeNode(declaration);
      if (typeNode) {
        return checkSatisfiesExpressionWorker(initializer, typeNode, checkMode);
      }
    }
    const type = getQuickTypeOfExpression(initializer) || (contextualType ? checkExpressionWithContextualType(
      initializer,
      contextualType,
      /*inferenceContext*/
      void 0,
      checkMode || 0 /* Normal */
    ) : checkExpressionCached(initializer, checkMode));
    if (isParameter(isBindingElement(declaration) ? walkUpBindingElementsAndPatterns(declaration) : declaration)) {
      if (declaration.name.kind === 206 /* ObjectBindingPattern */ && isObjectLiteralType(type)) {
        return padObjectLiteralType(type, declaration.name);
      }
      if (declaration.name.kind === 207 /* ArrayBindingPattern */ && isTupleType(type)) {
        return padTupleType(type, declaration.name);
      }
    }
    return type;
  }
  function padObjectLiteralType(type, pattern) {
    let missingElements;
    for (const e of pattern.elements) {
      if (e.initializer) {
        const name = getPropertyNameFromBindingElement(e);
        if (name && !getPropertyOfType(type, name)) {
          missingElements = append(missingElements, e);
        }
      }
    }
    if (!missingElements) {
      return type;
    }
    const members = createSymbolTable();
    for (const prop of getPropertiesOfObjectType(type)) {
      members.set(prop.escapedName, prop);
    }
    for (const e of missingElements) {
      const symbol = createSymbol(4 /* Property */ | 16777216 /* Optional */, getPropertyNameFromBindingElement(e));
      symbol.links.type = getTypeFromBindingElement(
        e,
        /*includePatternInType*/
        false,
        /*reportErrors*/
        false
      );
      members.set(symbol.escapedName, symbol);
    }
    const result = createAnonymousType(type.symbol, members, emptyArray, emptyArray, getIndexInfosOfType(type));
    result.objectFlags = type.objectFlags;
    return result;
  }
  function getPropertyNameFromBindingElement(e) {
    const exprType = getLiteralTypeFromPropertyName(e.propertyName || e.name);
    return isTypeUsableAsPropertyName(exprType) ? getPropertyNameFromType(exprType) : void 0;
  }
  function padTupleType(type, pattern) {
    if (type.target.combinedFlags & 12 /* Variable */ || getTypeReferenceArity(type) >= pattern.elements.length) {
      return type;
    }
    const patternElements = pattern.elements;
    const elementTypes = getElementTypes(type).slice();
    const elementFlags = type.target.elementFlags.slice();
    for (let i = getTypeReferenceArity(type); i < patternElements.length; i++) {
      const e = patternElements[i];
      if (i < patternElements.length - 1 || !(e.kind === 208 /* BindingElement */ && e.dotDotDotToken)) {
        elementTypes.push(!isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(
          e,
          /*includePatternInType*/
          false,
          /*reportErrors*/
          false
        ) : anyType);
        elementFlags.push(2 /* Optional */);
        if (!isOmittedExpression(e) && !hasDefaultValue(e)) {
          reportImplicitAny(e, anyType);
        }
      }
    }
    return createTupleType(elementTypes, elementFlags, type.target.readonly);
  }
  function widenTypeInferredFromInitializer(declaration, type) {
    const widened = getWidenedLiteralTypeForInitializer(declaration, type);
    if (isInJSFile(declaration)) {
      if (isEmptyLiteralType(widened)) {
        reportImplicitAny(declaration, anyType);
        return anyType;
      } else if (isEmptyArrayLiteralType(widened)) {
        reportImplicitAny(declaration, anyArrayType);
        return anyArrayType;
      }
    }
    return widened;
  }
  function getWidenedLiteralTypeForInitializer(declaration, type) {
    return getCombinedNodeFlagsCached(declaration) & 6 /* Constant */ || isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
  }
  function isLiteralOfContextualType(candidateType, contextualType) {
    if (contextualType) {
      if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
        const types = contextualType.types;
        return some(types, (t) => isLiteralOfContextualType(candidateType, t));
      }
      if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
        const constraint = getBaseConstraintOfType(contextualType) || unknownType;
        return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) || isLiteralOfContextualType(candidateType, constraint);
      }
      return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) || contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) || contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) || contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) || contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
    }
    return false;
  }
  function isConstContext(node) {
    const parent = node.parent;
    return isAssertionExpression(parent) && isConstTypeReference(parent.type) || isJSDocTypeAssertion(parent) && isConstTypeReference(getJSDocTypeAssertionType(parent)) || isValidConstAssertionArgument(node) && isConstTypeVariable(getContextualType(node, 0 /* None */)) || (isParenthesizedExpression(parent) || isArrayLiteralExpression(parent) || isSpreadElement(parent)) && isConstContext(parent) || (isPropertyAssignment(parent) || isShorthandPropertyAssignment(parent) || isTemplateSpan(parent)) && isConstContext(parent.parent);
  }
  function checkExpressionForMutableLocation(node, checkMode, forceTuple) {
    const type = checkExpression(node, checkMode, forceTuple);
    return isConstContext(node) || isCommonJsExportedExpression(node) ? getRegularTypeOfLiteralType(type) : isTypeAssertion(node) ? type : getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(
      getContextualType(
        node,
        /*contextFlags*/
        void 0
      ),
      node,
      /*contextFlags*/
      void 0
    ));
  }
  function checkPropertyAssignment(node, checkMode) {
    if (node.name.kind === 167 /* ComputedPropertyName */) {
      checkComputedPropertyName(node.name);
    }
    return checkExpressionForMutableLocation(node.initializer, checkMode);
  }
  function checkObjectLiteralMethod(node, checkMode) {
    checkGrammarMethod(node);
    if (node.name.kind === 167 /* ComputedPropertyName */) {
      checkComputedPropertyName(node.name);
    }
    const uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
    return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
  }
  function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
    if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
      const callSignature = getSingleSignature(
        type,
        0 /* Call */,
        /*allowMembers*/
        true
      );
      const constructSignature = getSingleSignature(
        type,
        1 /* Construct */,
        /*allowMembers*/
        true
      );
      const signature = callSignature || constructSignature;
      if (signature && signature.typeParameters) {
        const contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
        if (contextualType) {
          const contextualSignature = getSingleSignature(
            getNonNullableType(contextualType),
            callSignature ? 0 /* Call */ : 1 /* Construct */,
            /*allowMembers*/
            false
          );
          if (contextualSignature && !contextualSignature.typeParameters) {
            if (checkMode & 8 /* SkipGenericFunctions */) {
              skippedGenericFunction(node, checkMode);
              return anyFunctionType;
            }
            const context = getInferenceContext(node);
            const returnType = context.signature && getReturnTypeOfSignature(context.signature);
            const returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
            if (returnSignature && !returnSignature.typeParameters && !every(context.inferences, hasInferenceCandidates)) {
              const uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
              const instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
              const inferences = map(context.inferences, (info) => createInferenceInfo(info.typeParameter));
              applyToParameterTypes(instantiatedSignature, contextualSignature, (source, target) => {
                inferTypes(
                  inferences,
                  source,
                  target,
                  /*priority*/
                  0,
                  /*contravariant*/
                  true
                );
              });
              if (some(inferences, hasInferenceCandidates)) {
                applyToReturnTypes(instantiatedSignature, contextualSignature, (source, target) => {
                  inferTypes(inferences, source, target);
                });
                if (!hasOverlappingInferences(context.inferences, inferences)) {
                  mergeInferences(context.inferences, inferences);
                  context.inferredTypeParameters = concatenate(context.inferredTypeParameters, uniqueTypeParameters);
                  return getOrCreateTypeFromSignature(instantiatedSignature);
                }
              }
            }
            return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context), flatMap(inferenceContexts, (c) => c && map(c.inferences, (i) => i.typeParameter)).slice());
          }
        }
      }
    }
    return type;
  }
  function skippedGenericFunction(node, checkMode) {
    if (checkMode & 2 /* Inferential */) {
      const context = getInferenceContext(node);
      context.flags |= 4 /* SkippedGenericFunction */;
    }
  }
  function hasInferenceCandidates(info) {
    return !!(info.candidates || info.contraCandidates);
  }
  function hasInferenceCandidatesOrDefault(info) {
    return !!(info.candidates || info.contraCandidates || hasTypeParameterDefault(info.typeParameter));
  }
  function hasOverlappingInferences(a, b) {
    for (let i = 0; i < a.length; i++) {
      if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
        return true;
      }
    }
    return false;
  }
  function mergeInferences(target, source) {
    for (let i = 0; i < target.length; i++) {
      if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
        target[i] = source[i];
      }
    }
  }
  function getUniqueTypeParameters(context, typeParameters) {
    const result = [];
    let oldTypeParameters;
    let newTypeParameters;
    for (const tp of typeParameters) {
      const name = tp.symbol.escapedName;
      if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
        const newName = getUniqueTypeParameterName(concatenate(context.inferredTypeParameters, result), name);
        const symbol = createSymbol(262144 /* TypeParameter */, newName);
        const newTypeParameter = createTypeParameter(symbol);
        newTypeParameter.target = tp;
        oldTypeParameters = append(oldTypeParameters, tp);
        newTypeParameters = append(newTypeParameters, newTypeParameter);
        result.push(newTypeParameter);
      } else {
        result.push(tp);
      }
    }
    if (newTypeParameters) {
      const mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
      for (const tp of newTypeParameters) {
        tp.mapper = mapper;
      }
    }
    return result;
  }
  function hasTypeParameterByName(typeParameters, name) {
    return some(typeParameters, (tp) => tp.symbol.escapedName === name);
  }
  function getUniqueTypeParameterName(typeParameters, baseName) {
    let len = baseName.length;
    while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */) len--;
    const s = baseName.slice(0, len);
    for (let index = 1; true; index++) {
      const augmentedName = s + index;
      if (!hasTypeParameterByName(typeParameters, augmentedName)) {
        return augmentedName;
      }
    }
  }
  function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
    const signature = getSingleCallSignature(funcType);
    if (signature && !signature.typeParameters) {
      return getReturnTypeOfSignature(signature);
    }
  }
  function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
    const funcType = checkExpression(expr.expression);
    const nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
    const returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
    return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
  }
  function getTypeOfExpression(node) {
    const quickType = getQuickTypeOfExpression(node);
    if (quickType) {
      return quickType;
    }
    if (node.flags & 268435456 /* TypeCached */ && flowTypeCache) {
      const cachedType = flowTypeCache[getNodeId(node)];
      if (cachedType) {
        return cachedType;
      }
    }
    const startInvocationCount = flowInvocationCount;
    const type = checkExpression(node, 64 /* TypeOnly */);
    if (flowInvocationCount !== startInvocationCount) {
      const cache = flowTypeCache || (flowTypeCache = []);
      cache[getNodeId(node)] = type;
      setNodeFlags(node, node.flags | 268435456 /* TypeCached */);
    }
    return type;
  }
  function getQuickTypeOfExpression(node) {
    let expr = skipParentheses(
      node,
      /*excludeJSDocTypeAssertions*/
      true
    );
    if (isJSDocTypeAssertion(expr)) {
      const type = getJSDocTypeAssertionType(expr);
      if (!isConstTypeReference(type)) {
        return getTypeFromTypeNode(type);
      }
    }
    expr = skipParentheses(node);
    if (isAwaitExpression(expr)) {
      const type = getQuickTypeOfExpression(expr.expression);
      return type ? getAwaitedType(type) : void 0;
    }
    if (isCallExpression(expr) && expr.expression.kind !== 108 /* SuperKeyword */ && !isRequireCall(
      expr,
      /*requireStringLiteralLikeArgument*/
      true
    ) && !isSymbolOrSymbolForCall(expr)) {
      return isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) : getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
    } else if (isAssertionExpression(expr) && !isConstTypeReference(expr.type)) {
      return getTypeFromTypeNode(expr.type);
    } else if (isLiteralExpression(node) || isBooleanLiteral(node)) {
      return checkExpression(node);
    }
    return void 0;
  }
  function getContextFreeTypeOfExpression(node) {
    const links = getNodeLinks(node);
    if (links.contextFreeType) {
      return links.contextFreeType;
    }
    pushContextualType(
      node,
      anyType,
      /*isCache*/
      false
    );
    const type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
    popContextualType();
    return type;
  }
  function checkExpression(node, checkMode, forceTuple) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    const saveCurrentNode = currentNode;
    currentNode = node;
    instantiationCount = 0;
    const uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
    const type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
    if (isConstEnumObjectType(type)) {
      checkConstEnumAccess(node, type);
    }
    currentNode = saveCurrentNode;
    (_b = tracing) == null ? void 0 : _b.pop();
    return type;
  }
  function checkConstEnumAccess(node, type) {
    const ok = node.parent.kind === 211 /* PropertyAccessExpression */ && node.parent.expression === node || node.parent.kind === 212 /* ElementAccessExpression */ && node.parent.expression === node || ((node.kind === 80 /* Identifier */ || node.kind === 166 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || node.parent.kind === 186 /* TypeQuery */ && node.parent.exprName === node) || node.parent.kind === 281 /* ExportSpecifier */;
    if (!ok) {
      error(node, Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query);
    }
    if (compilerOptions.isolatedModules || compilerOptions.verbatimModuleSyntax && ok && !resolveName(
      node,
      getFirstIdentifier(node),
      2097152 /* Alias */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      false,
      /*excludeGlobals*/
      true
    )) {
      Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
      const constEnumDeclaration = type.symbol.valueDeclaration;
      const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath);
      if (constEnumDeclaration.flags & 33554432 /* Ambient */ && !isValidTypeOnlyAliasUseSite(node) && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) {
        error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName);
      }
    }
  }
  function checkParenthesizedExpression(node, checkMode) {
    if (hasJSDocNodes(node)) {
      if (isJSDocSatisfiesExpression(node)) {
        return checkSatisfiesExpressionWorker(node.expression, getJSDocSatisfiesExpressionType(node), checkMode);
      }
      if (isJSDocTypeAssertion(node)) {
        return checkAssertionWorker(node, checkMode);
      }
    }
    return checkExpression(node.expression, checkMode);
  }
  function checkExpressionWorker(node, checkMode, forceTuple) {
    const kind = node.kind;
    if (cancellationToken) {
      switch (kind) {
        case 231 /* ClassExpression */:
        case 218 /* FunctionExpression */:
        case 219 /* ArrowFunction */:
          cancellationToken.throwIfCancellationRequested();
      }
    }
    switch (kind) {
      case 80 /* Identifier */:
        return checkIdentifier(node, checkMode);
      case 81 /* PrivateIdentifier */:
        return checkPrivateIdentifierExpression(node);
      case 110 /* ThisKeyword */:
        return checkThisExpression(node);
      case 108 /* SuperKeyword */:
        return checkSuperExpression(node);
      case 106 /* NullKeyword */:
        return nullWideningType;
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 11 /* StringLiteral */:
        return hasSkipDirectInferenceFlag(node) ? blockedStringType : getFreshTypeOfLiteralType(getStringLiteralType(node.text));
      case 9 /* NumericLiteral */:
        checkGrammarNumericLiteral(node);
        return getFreshTypeOfLiteralType(getNumberLiteralType(+node.text));
      case 10 /* BigIntLiteral */:
        checkGrammarBigIntLiteral(node);
        return getFreshTypeOfLiteralType(getBigIntLiteralType({
          negative: false,
          base10Value: parsePseudoBigInt(node.text)
        }));
      case 112 /* TrueKeyword */:
        return trueType;
      case 97 /* FalseKeyword */:
        return falseType;
      case 228 /* TemplateExpression */:
        return checkTemplateExpression(node);
      case 14 /* RegularExpressionLiteral */:
        return checkRegularExpressionLiteral(node);
      case 209 /* ArrayLiteralExpression */:
        return checkArrayLiteral(node, checkMode, forceTuple);
      case 210 /* ObjectLiteralExpression */:
        return checkObjectLiteral(node, checkMode);
      case 211 /* PropertyAccessExpression */:
        return checkPropertyAccessExpression(node, checkMode);
      case 166 /* QualifiedName */:
        return checkQualifiedName(node, checkMode);
      case 212 /* ElementAccessExpression */:
        return checkIndexedAccess(node, checkMode);
      case 213 /* CallExpression */:
        if (node.expression.kind === 102 /* ImportKeyword */) {
          return checkImportCallExpression(node);
        }
      // falls through
      case 214 /* NewExpression */:
        return checkCallExpression(node, checkMode);
      case 215 /* TaggedTemplateExpression */:
        return checkTaggedTemplateExpression(node);
      case 217 /* ParenthesizedExpression */:
        return checkParenthesizedExpression(node, checkMode);
      case 231 /* ClassExpression */:
        return checkClassExpression(node);
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
      case 221 /* TypeOfExpression */:
        return checkTypeOfExpression(node);
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
        return checkAssertion(node, checkMode);
      case 235 /* NonNullExpression */:
        return checkNonNullAssertion(node);
      case 233 /* ExpressionWithTypeArguments */:
        return checkExpressionWithTypeArguments(node);
      case 238 /* SatisfiesExpression */:
        return checkSatisfiesExpression(node);
      case 236 /* MetaProperty */:
        return checkMetaProperty(node);
      case 220 /* DeleteExpression */:
        return checkDeleteExpression(node);
      case 222 /* VoidExpression */:
        return checkVoidExpression(node);
      case 223 /* AwaitExpression */:
        return checkAwaitExpression(node);
      case 224 /* PrefixUnaryExpression */:
        return checkPrefixUnaryExpression(node);
      case 225 /* PostfixUnaryExpression */:
        return checkPostfixUnaryExpression(node);
      case 226 /* BinaryExpression */:
        return checkBinaryExpression(node, checkMode);
      case 227 /* ConditionalExpression */:
        return checkConditionalExpression(node, checkMode);
      case 230 /* SpreadElement */:
        return checkSpreadExpression(node, checkMode);
      case 232 /* OmittedExpression */:
        return undefinedWideningType;
      case 229 /* YieldExpression */:
        return checkYieldExpression(node);
      case 237 /* SyntheticExpression */:
        return checkSyntheticExpression(node);
      case 294 /* JsxExpression */:
        return checkJsxExpression(node, checkMode);
      case 284 /* JsxElement */:
        return checkJsxElement(node, checkMode);
      case 285 /* JsxSelfClosingElement */:
        return checkJsxSelfClosingElement(node, checkMode);
      case 288 /* JsxFragment */:
        return checkJsxFragment(node);
      case 292 /* JsxAttributes */:
        return checkJsxAttributes(node, checkMode);
      case 286 /* JsxOpeningElement */:
        Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
    }
    return errorType;
  }
  function checkTypeParameter(node) {
    checkGrammarModifiers(node);
    if (node.expression) {
      grammarErrorOnFirstToken(node.expression, Diagnostics.Type_expected);
    }
    checkSourceElement(node.constraint);
    checkSourceElement(node.default);
    const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node));
    getBaseConstraintOfType(typeParameter);
    if (!hasNonCircularTypeParameterDefault(typeParameter)) {
      error(node.default, Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
    }
    const constraintType = getConstraintOfTypeParameter(typeParameter);
    const defaultType = getDefaultFromTypeParameter(typeParameter);
    if (constraintType && defaultType) {
      checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
    }
    checkNodeDeferred(node);
    addLazyDiagnostic(() => checkTypeNameIsReserved(node.name, Diagnostics.Type_parameter_name_cannot_be_0));
  }
  function checkTypeParameterDeferred(node) {
    var _a, _b;
    if (isInterfaceDeclaration(node.parent) || isClassLike(node.parent) || isTypeAliasDeclaration(node.parent)) {
      const typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfDeclaration(node));
      const modifiers = getTypeParameterModifiers(typeParameter) & (8192 /* In */ | 16384 /* Out */);
      if (modifiers) {
        const symbol = getSymbolOfDeclaration(node.parent);
        if (isTypeAliasDeclaration(node.parent) && !(getObjectFlags(getDeclaredTypeOfSymbol(symbol)) & (16 /* Anonymous */ | 32 /* Mapped */))) {
          error(node, Diagnostics.Variance_annotations_are_only_supported_in_type_aliases_for_object_function_constructor_and_mapped_types);
        } else if (modifiers === 8192 /* In */ || modifiers === 16384 /* Out */) {
          (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.CheckTypes, "checkTypeParameterDeferred", { parent: getTypeId(getDeclaredTypeOfSymbol(symbol)), id: getTypeId(typeParameter) });
          const source = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSubTypeForCheck : markerSuperTypeForCheck);
          const target = createMarkerType(symbol, typeParameter, modifiers === 16384 /* Out */ ? markerSuperTypeForCheck : markerSubTypeForCheck);
          const saveVarianceTypeParameter = typeParameter;
          varianceTypeParameter = typeParameter;
          checkTypeAssignableTo(source, target, node, Diagnostics.Type_0_is_not_assignable_to_type_1_as_implied_by_variance_annotation);
          varianceTypeParameter = saveVarianceTypeParameter;
          (_b = tracing) == null ? void 0 : _b.pop();
        }
      }
    }
  }
  function checkParameter(node) {
    checkGrammarModifiers(node);
    checkVariableLikeDeclaration(node);
    const func = getContainingFunction(node);
    if (hasSyntacticModifier(node, 31 /* ParameterPropertyModifier */)) {
      if (!(func.kind === 176 /* Constructor */ && nodeIsPresent(func.body))) {
        error(node, Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
      }
      if (func.kind === 176 /* Constructor */ && isIdentifier(node.name) && node.name.escapedText === "constructor") {
        error(node.name, Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
      }
    }
    if (!node.initializer && isOptionalDeclaration(node) && isBindingPattern(node.name) && func.body) {
      error(node, Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
    }
    if (node.name && isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
      if (func.parameters.indexOf(node) !== 0) {
        error(node, Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
      }
      if (func.kind === 176 /* Constructor */ || func.kind === 180 /* ConstructSignature */ || func.kind === 185 /* ConstructorType */) {
        error(node, Diagnostics.A_constructor_cannot_have_a_this_parameter);
      }
      if (func.kind === 219 /* ArrowFunction */) {
        error(node, Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
      }
      if (func.kind === 177 /* GetAccessor */ || func.kind === 178 /* SetAccessor */) {
        error(node, Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
      }
    }
    if (node.dotDotDotToken && !isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
      error(node, Diagnostics.A_rest_parameter_must_be_of_an_array_type);
    }
  }
  function checkTypePredicate(node) {
    const parent = getTypePredicateParent(node);
    if (!parent) {
      error(node, Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
      return;
    }
    const signature = getSignatureFromDeclaration(parent);
    const typePredicate = getTypePredicateOfSignature(signature);
    if (!typePredicate) {
      return;
    }
    checkSourceElement(node.type);
    const { parameterName } = node;
    if (typePredicate.kind !== 0 /* This */ && typePredicate.kind !== 2 /* AssertsThis */) {
      if (typePredicate.parameterIndex >= 0) {
        if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
          error(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
        } else {
          if (typePredicate.type) {
            const leadingError = () => chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type
            );
            checkTypeAssignableTo(
              typePredicate.type,
              getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]),
              node.type,
              /*headMessage*/
              void 0,
              leadingError
            );
          }
        }
      } else if (parameterName) {
        let hasReportedError = false;
        for (const { name } of parent.parameters) {
          if (isBindingPattern(name) && checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
            hasReportedError = true;
            break;
          }
        }
        if (!hasReportedError) {
          error(node.parameterName, Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
        }
      }
    }
  }
  function getTypePredicateParent(node) {
    switch (node.parent.kind) {
      case 219 /* ArrowFunction */:
      case 179 /* CallSignature */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 184 /* FunctionType */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        const parent = node.parent;
        if (node === parent.type) {
          return parent;
        }
    }
  }
  function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
    for (const element of pattern.elements) {
      if (isOmittedExpression(element)) {
        continue;
      }
      const name = element.name;
      if (name.kind === 80 /* Identifier */ && name.escapedText === predicateVariableName) {
        error(predicateVariableNode, Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
        return true;
      } else if (name.kind === 207 /* ArrayBindingPattern */ || name.kind === 206 /* ObjectBindingPattern */) {
        if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(
          name,
          predicateVariableNode,
          predicateVariableName
        )) {
          return true;
        }
      }
    }
  }
  function checkSignatureDeclaration(node) {
    if (node.kind === 181 /* IndexSignature */) {
      checkGrammarIndexSignature(node);
    } else if (node.kind === 184 /* FunctionType */ || node.kind === 262 /* FunctionDeclaration */ || node.kind === 185 /* ConstructorType */ || node.kind === 179 /* CallSignature */ || node.kind === 176 /* Constructor */ || node.kind === 180 /* ConstructSignature */) {
      checkGrammarFunctionLikeDeclaration(node);
    }
    const functionFlags = getFunctionFlags(node);
    if (!(functionFlags & 4 /* Invalid */)) {
      if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < LanguageFeatureMinimumTarget.AsyncGenerators) {
        checkExternalEmitHelpers(node, 6144 /* AsyncGeneratorIncludes */);
      }
      if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.AsyncFunctions) {
        checkExternalEmitHelpers(node, 64 /* Awaiter */);
      }
      if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < LanguageFeatureMinimumTarget.Generators) {
        checkExternalEmitHelpers(node, 128 /* Generator */);
      }
    }
    checkTypeParameters(getEffectiveTypeParameterDeclarations(node));
    checkUnmatchedJSDocParameters(node);
    forEach(node.parameters, checkParameter);
    if (node.type) {
      checkSourceElement(node.type);
    }
    addLazyDiagnostic(checkSignatureDeclarationDiagnostics);
    function checkSignatureDeclarationDiagnostics() {
      checkCollisionWithArgumentsInGeneratedCode(node);
      let returnTypeNode = getEffectiveReturnTypeNode(node);
      let returnTypeErrorLocation = returnTypeNode;
      if (isInJSFile(node)) {
        const typeTag = getJSDocTypeTag(node);
        if (typeTag && typeTag.typeExpression && isTypeReferenceNode(typeTag.typeExpression.type)) {
          const signature = getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
          if (signature && signature.declaration) {
            returnTypeNode = getEffectiveReturnTypeNode(signature.declaration);
            returnTypeErrorLocation = typeTag.typeExpression.type;
          }
        }
      }
      if (noImplicitAny && !returnTypeNode) {
        switch (node.kind) {
          case 180 /* ConstructSignature */:
            error(node, Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
            break;
          case 179 /* CallSignature */:
            error(node, Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
            break;
        }
      }
      if (returnTypeNode && returnTypeErrorLocation) {
        const functionFlags2 = getFunctionFlags(node);
        if ((functionFlags2 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
          const returnType = getTypeFromTypeNode(returnTypeNode);
          if (returnType === voidType) {
            error(returnTypeErrorLocation, Diagnostics.A_generator_cannot_have_a_void_type_annotation);
          } else {
            checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags2, returnTypeErrorLocation);
          }
        } else if ((functionFlags2 & 3 /* AsyncGenerator */) === 2 /* Async */) {
          checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation);
        }
      }
      if (node.kind !== 181 /* IndexSignature */ && node.kind !== 317 /* JSDocFunctionType */) {
        registerForUnusedIdentifiersCheck(node);
      }
    }
  }
  function checkGeneratorInstantiationAssignabilityToReturnType(returnType, functionFlags, errorNode) {
    const generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags & 2 /* Async */) !== 0) || anyType;
    const generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags & 2 /* Async */) !== 0) || generatorYieldType;
    const generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags & 2 /* Async */) !== 0) || unknownType;
    const generatorInstantiation = createGeneratorType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags & 2 /* Async */));
    return checkTypeAssignableTo(generatorInstantiation, returnType, errorNode);
  }
  function checkClassForDuplicateDeclarations(node) {
    const instanceNames = /* @__PURE__ */ new Map();
    const staticNames = /* @__PURE__ */ new Map();
    const privateIdentifiers = /* @__PURE__ */ new Map();
    for (const member of node.members) {
      if (member.kind === 176 /* Constructor */) {
        for (const param of member.parameters) {
          if (isParameterPropertyDeclaration(param, member) && !isBindingPattern(param.name)) {
            addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
          }
        }
      } else {
        const isStaticMember = isStatic(member);
        const name = member.name;
        if (!name) {
          continue;
        }
        const isPrivate = isPrivateIdentifier(name);
        const privateStaticFlags = isPrivate && isStaticMember ? 16 /* PrivateStatic */ : 0;
        const names = isPrivate ? privateIdentifiers : isStaticMember ? staticNames : instanceNames;
        const memberName = name && getEffectivePropertyNameForPropertyNameNode(name);
        if (memberName) {
          switch (member.kind) {
            case 177 /* GetAccessor */:
              addName(names, name, memberName, 1 /* GetAccessor */ | privateStaticFlags);
              break;
            case 178 /* SetAccessor */:
              addName(names, name, memberName, 2 /* SetAccessor */ | privateStaticFlags);
              break;
            case 172 /* PropertyDeclaration */:
              addName(names, name, memberName, 3 /* GetOrSetAccessor */ | privateStaticFlags);
              break;
            case 174 /* MethodDeclaration */:
              addName(names, name, memberName, 8 /* Method */ | privateStaticFlags);
              break;
          }
        }
      }
    }
    function addName(names, location, name, meaning) {
      const prev = names.get(name);
      if (prev) {
        if ((prev & 16 /* PrivateStatic */) !== (meaning & 16 /* PrivateStatic */)) {
          error(location, Diagnostics.Duplicate_identifier_0_Static_and_instance_elements_cannot_share_the_same_private_name, getTextOfNode(location));
        } else {
          const prevIsMethod = !!(prev & 8 /* Method */);
          const isMethod = !!(meaning & 8 /* Method */);
          if (prevIsMethod || isMethod) {
            if (prevIsMethod !== isMethod) {
              error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location));
            }
          } else if (prev & meaning & ~16 /* PrivateStatic */) {
            error(location, Diagnostics.Duplicate_identifier_0, getTextOfNode(location));
          } else {
            names.set(name, prev | meaning);
          }
        }
      } else {
        names.set(name, meaning);
      }
    }
  }
  function checkClassForStaticPropertyNameConflicts(node) {
    for (const member of node.members) {
      const memberNameNode = member.name;
      const isStaticMember = isStatic(member);
      if (isStaticMember && memberNameNode) {
        const memberName = getEffectivePropertyNameForPropertyNameNode(memberNameNode);
        switch (memberName) {
          case "name":
          case "length":
          case "caller":
          case "arguments":
            if (useDefineForClassFields) {
              break;
            }
          // fall through
          case "prototype":
            const message = Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
            const className = getNameOfSymbolAsWritten(getSymbolOfDeclaration(node));
            error(memberNameNode, message, memberName, className);
            break;
        }
      }
    }
  }
  function checkObjectTypeForDuplicateDeclarations(node) {
    const names = /* @__PURE__ */ new Map();
    for (const member of node.members) {
      if (member.kind === 171 /* PropertySignature */) {
        let memberName;
        const name = member.name;
        switch (name.kind) {
          case 11 /* StringLiteral */:
          case 9 /* NumericLiteral */:
            memberName = name.text;
            break;
          case 80 /* Identifier */:
            memberName = idText(name);
            break;
          default:
            continue;
        }
        if (names.get(memberName)) {
          error(getNameOfDeclaration(member.symbol.valueDeclaration), Diagnostics.Duplicate_identifier_0, memberName);
          error(member.name, Diagnostics.Duplicate_identifier_0, memberName);
        } else {
          names.set(memberName, true);
        }
      }
    }
  }
  function checkTypeForDuplicateIndexSignatures(node) {
    if (node.kind === 264 /* InterfaceDeclaration */) {
      const nodeSymbol = getSymbolOfDeclaration(node);
      if (nodeSymbol.declarations && nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
        return;
      }
    }
    const indexSymbol = getIndexSymbol(getSymbolOfDeclaration(node));
    if (indexSymbol == null ? void 0 : indexSymbol.declarations) {
      const indexSignatureMap = /* @__PURE__ */ new Map();
      for (const declaration of indexSymbol.declarations) {
        if (isIndexSignatureDeclaration(declaration)) {
          if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
            forEachType(getTypeFromTypeNode(declaration.parameters[0].type), (type) => {
              const entry = indexSignatureMap.get(getTypeId(type));
              if (entry) {
                entry.declarations.push(declaration);
              } else {
                indexSignatureMap.set(getTypeId(type), { type, declarations: [declaration] });
              }
            });
          }
        }
      }
      indexSignatureMap.forEach((entry) => {
        if (entry.declarations.length > 1) {
          for (const declaration of entry.declarations) {
            error(declaration, Diagnostics.Duplicate_index_signature_for_type_0, typeToString(entry.type));
          }
        }
      });
    }
  }
  function checkPropertyDeclaration(node) {
    if (!checkGrammarModifiers(node) && !checkGrammarProperty(node)) checkGrammarComputedPropertyName(node.name);
    checkVariableLikeDeclaration(node);
    setNodeLinksForPrivateIdentifierScope(node);
    if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 172 /* PropertyDeclaration */ && node.initializer) {
      error(node, Diagnostics.Property_0_cannot_have_an_initializer_because_it_is_marked_abstract, declarationNameToString(node.name));
    }
  }
  function checkPropertySignature(node) {
    if (isPrivateIdentifier(node.name)) {
      error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
    }
    return checkPropertyDeclaration(node);
  }
  function checkMethodDeclaration(node) {
    if (!checkGrammarMethod(node)) checkGrammarComputedPropertyName(node.name);
    if (isMethodDeclaration(node) && node.asteriskToken && isIdentifier(node.name) && idText(node.name) === "constructor") {
      error(node.name, Diagnostics.Class_constructor_may_not_be_a_generator);
    }
    checkFunctionOrMethodDeclaration(node);
    if (hasSyntacticModifier(node, 64 /* Abstract */) && node.kind === 174 /* MethodDeclaration */ && node.body) {
      error(node, Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, declarationNameToString(node.name));
    }
    if (isPrivateIdentifier(node.name) && !getContainingClass(node)) {
      error(node, Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
    }
    setNodeLinksForPrivateIdentifierScope(node);
  }
  function setNodeLinksForPrivateIdentifierScope(node) {
    if (isPrivateIdentifier(node.name)) {
      if (languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators || !useDefineForClassFields) {
        for (let lexicalScope = getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = getEnclosingBlockScopeContainer(lexicalScope)) {
          getNodeLinks(lexicalScope).flags |= 1048576 /* ContainsClassWithPrivateIdentifiers */;
        }
        if (isClassExpression(node.parent)) {
          const enclosingIterationStatement = getEnclosingIterationStatement(node.parent);
          if (enclosingIterationStatement) {
            getNodeLinks(node.name).flags |= 32768 /* BlockScopedBindingInLoop */;
            getNodeLinks(enclosingIterationStatement).flags |= 4096 /* LoopWithCapturedBlockScopedBinding */;
          }
        }
      }
    }
  }
  function checkClassStaticBlockDeclaration(node) {
    checkGrammarModifiers(node);
    forEachChild(node, checkSourceElement);
  }
  function checkConstructorDeclaration(node) {
    checkSignatureDeclaration(node);
    if (!checkGrammarConstructorTypeParameters(node)) checkGrammarConstructorTypeAnnotation(node);
    checkSourceElement(node.body);
    const symbol = getSymbolOfDeclaration(node);
    const firstDeclaration = getDeclarationOfKind(symbol, node.kind);
    if (node === firstDeclaration) {
      checkFunctionOrConstructorSymbol(symbol);
    }
    if (nodeIsMissing(node.body)) {
      return;
    }
    addLazyDiagnostic(checkConstructorDeclarationDiagnostics);
    return;
    function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
      if (isPrivateIdentifierClassElementDeclaration(n)) {
        return true;
      }
      return n.kind === 172 /* PropertyDeclaration */ && !isStatic(n) && !!n.initializer;
    }
    function checkConstructorDeclarationDiagnostics() {
      const containingClassDecl = node.parent;
      if (getClassExtendsHeritageElement(containingClassDecl)) {
        captureLexicalThis(node.parent, containingClassDecl);
        const classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
        const superCall = findFirstSuperCall(node.body);
        if (superCall) {
          if (classExtendsNull) {
            error(superCall, Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
          }
          const superCallShouldBeRootLevel = !emitStandardClassFields && (some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) || some(node.parameters, (p) => hasSyntacticModifier(p, 31 /* ParameterPropertyModifier */)));
          if (superCallShouldBeRootLevel) {
            if (!superCallIsRootLevelInConstructor(superCall, node.body)) {
              error(superCall, Diagnostics.A_super_call_must_be_a_root_level_statement_within_a_constructor_of_a_derived_class_that_contains_initialized_properties_parameter_properties_or_private_identifiers);
            } else {
              let superCallStatement;
              for (const statement of node.body.statements) {
                if (isExpressionStatement(statement) && isSuperCall(skipOuterExpressions(statement.expression))) {
                  superCallStatement = statement;
                  break;
                }
                if (nodeImmediatelyReferencesSuperOrThis(statement)) {
                  break;
                }
              }
              if (superCallStatement === void 0) {
                error(node, Diagnostics.A_super_call_must_be_the_first_statement_in_the_constructor_to_refer_to_super_or_this_when_a_derived_class_contains_initialized_properties_parameter_properties_or_private_identifiers);
              }
            }
          }
        } else if (!classExtendsNull) {
          error(node, Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
        }
      }
    }
  }
  function superCallIsRootLevelInConstructor(superCall, body) {
    const superCallParent = walkUpParenthesizedExpressions(superCall.parent);
    return isExpressionStatement(superCallParent) && superCallParent.parent === body;
  }
  function nodeImmediatelyReferencesSuperOrThis(node) {
    if (node.kind === 108 /* SuperKeyword */ || node.kind === 110 /* ThisKeyword */) {
      return true;
    }
    if (isThisContainerOrFunctionBlock(node)) {
      return false;
    }
    return !!forEachChild(node, nodeImmediatelyReferencesSuperOrThis);
  }
  function checkAccessorDeclaration(node) {
    if (isIdentifier(node.name) && idText(node.name) === "constructor" && isClassLike(node.parent)) {
      error(node.name, Diagnostics.Class_constructor_may_not_be_an_accessor);
    }
    addLazyDiagnostic(checkAccessorDeclarationDiagnostics);
    checkSourceElement(node.body);
    setNodeLinksForPrivateIdentifierScope(node);
    function checkAccessorDeclarationDiagnostics() {
      if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node)) checkGrammarComputedPropertyName(node.name);
      checkDecorators(node);
      checkSignatureDeclaration(node);
      if (node.kind === 177 /* GetAccessor */) {
        if (!(node.flags & 33554432 /* Ambient */) && nodeIsPresent(node.body) && node.flags & 512 /* HasImplicitReturn */) {
          if (!(node.flags & 1024 /* HasExplicitReturn */)) {
            error(node.name, Diagnostics.A_get_accessor_must_return_a_value);
          }
        }
      }
      if (node.name.kind === 167 /* ComputedPropertyName */) {
        checkComputedPropertyName(node.name);
      }
      if (hasBindableName(node)) {
        const symbol = getSymbolOfDeclaration(node);
        const getter = getDeclarationOfKind(symbol, 177 /* GetAccessor */);
        const setter = getDeclarationOfKind(symbol, 178 /* SetAccessor */);
        if (getter && setter && !(getNodeCheckFlags(getter) & 1 /* TypeChecked */)) {
          getNodeLinks(getter).flags |= 1 /* TypeChecked */;
          const getterFlags = getEffectiveModifierFlags(getter);
          const setterFlags = getEffectiveModifierFlags(setter);
          if ((getterFlags & 64 /* Abstract */) !== (setterFlags & 64 /* Abstract */)) {
            error(getter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
            error(setter.name, Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
          }
          if (getterFlags & 4 /* Protected */ && !(setterFlags & (4 /* Protected */ | 2 /* Private */)) || getterFlags & 2 /* Private */ && !(setterFlags & 2 /* Private */)) {
            error(getter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
            error(setter.name, Diagnostics.A_get_accessor_must_be_at_least_as_accessible_as_the_setter);
          }
        }
      }
      const returnType = getTypeOfAccessors(getSymbolOfDeclaration(node));
      if (node.kind === 177 /* GetAccessor */) {
        checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
      }
    }
  }
  function checkMissingDeclaration(node) {
    checkDecorators(node);
  }
  function getEffectiveTypeArgumentAtIndex(node, typeParameters, index) {
    if (node.typeArguments && index < node.typeArguments.length) {
      return getTypeFromTypeNode(node.typeArguments[index]);
    }
    return getEffectiveTypeArguments(node, typeParameters)[index];
  }
  function getEffectiveTypeArguments(node, typeParameters) {
    return fillMissingTypeArguments(map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isInJSFile(node));
  }
  function checkTypeArgumentConstraints(node, typeParameters) {
    let typeArguments;
    let mapper;
    let result = true;
    for (let i = 0; i < typeParameters.length; i++) {
      const constraint = getConstraintOfTypeParameter(typeParameters[i]);
      if (constraint) {
        if (!typeArguments) {
          typeArguments = getEffectiveTypeArguments(node, typeParameters);
          mapper = createTypeMapper(typeParameters, typeArguments);
        }
        result = result && checkTypeAssignableTo(
          typeArguments[i],
          instantiateType(constraint, mapper),
          node.typeArguments[i],
          Diagnostics.Type_0_does_not_satisfy_the_constraint_1
        );
      }
    }
    return result;
  }
  function getTypeParametersForTypeAndSymbol(type, symbol) {
    if (!isErrorType(type)) {
      return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters || (getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : void 0);
    }
    return void 0;
  }
  function getTypeParametersForTypeReferenceOrImport(node) {
    const type = getTypeFromTypeNode(node);
    if (!isErrorType(type)) {
      const symbol = getNodeLinks(node).resolvedSymbol;
      if (symbol) {
        return getTypeParametersForTypeAndSymbol(type, symbol);
      }
    }
    return void 0;
  }
  function checkTypeReferenceNode(node) {
    checkGrammarTypeArguments(node, node.typeArguments);
    if (node.kind === 183 /* TypeReference */ && !isInJSFile(node) && !isInJSDoc(node) && node.typeArguments && node.typeName.end !== node.typeArguments.pos) {
      const sourceFile = getSourceFileOfNode(node);
      if (scanTokenAtPosition(sourceFile, node.typeName.end) === 25 /* DotToken */) {
        grammarErrorAtPos(node, skipTrivia(sourceFile.text, node.typeName.end), 1, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
      }
    }
    forEach(node.typeArguments, checkSourceElement);
    checkTypeReferenceOrImport(node);
  }
  function checkTypeReferenceOrImport(node) {
    const type = getTypeFromTypeNode(node);
    if (!isErrorType(type)) {
      if (node.typeArguments) {
        addLazyDiagnostic(() => {
          const typeParameters = getTypeParametersForTypeReferenceOrImport(node);
          if (typeParameters) {
            checkTypeArgumentConstraints(node, typeParameters);
          }
        });
      }
      const symbol = getNodeLinks(node).resolvedSymbol;
      if (symbol) {
        if (some(symbol.declarations, (d) => isTypeDeclaration(d) && !!(d.flags & 536870912 /* Deprecated */))) {
          addDeprecatedSuggestion(
            getDeprecatedSuggestionNode(node),
            symbol.declarations,
            symbol.escapedName
          );
        }
      }
    }
  }
  function getTypeArgumentConstraint(node) {
    const typeReferenceNode = tryCast(node.parent, isTypeReferenceType);
    if (!typeReferenceNode) return void 0;
    const typeParameters = getTypeParametersForTypeReferenceOrImport(typeReferenceNode);
    if (!typeParameters) return void 0;
    const constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
    return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
  }
  function checkTypeQuery(node) {
    getTypeFromTypeQueryNode(node);
  }
  function checkTypeLiteral(node) {
    forEach(node.members, checkSourceElement);
    addLazyDiagnostic(checkTypeLiteralDiagnostics);
    function checkTypeLiteralDiagnostics() {
      const type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
      checkIndexConstraints(type, type.symbol);
      checkTypeForDuplicateIndexSignatures(node);
      checkObjectTypeForDuplicateDeclarations(node);
    }
  }
  function checkArrayType(node) {
    checkSourceElement(node.elementType);
  }
  function checkTupleType(node) {
    let seenOptionalElement = false;
    let seenRestElement = false;
    for (const e of node.elements) {
      let flags = getTupleElementFlags(e);
      if (flags & 8 /* Variadic */) {
        const type = getTypeFromTypeNode(e.type);
        if (!isArrayLikeType(type)) {
          error(e, Diagnostics.A_rest_element_type_must_be_an_array_type);
          break;
        }
        if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & 4 /* Rest */) {
          flags |= 4 /* Rest */;
        }
      }
      if (flags & 4 /* Rest */) {
        if (seenRestElement) {
          grammarErrorOnNode(e, Diagnostics.A_rest_element_cannot_follow_another_rest_element);
          break;
        }
        seenRestElement = true;
      } else if (flags & 2 /* Optional */) {
        if (seenRestElement) {
          grammarErrorOnNode(e, Diagnostics.An_optional_element_cannot_follow_a_rest_element);
          break;
        }
        seenOptionalElement = true;
      } else if (flags & 1 /* Required */ && seenOptionalElement) {
        grammarErrorOnNode(e, Diagnostics.A_required_element_cannot_follow_an_optional_element);
        break;
      }
    }
    forEach(node.elements, checkSourceElement);
    getTypeFromTypeNode(node);
  }
  function checkUnionOrIntersectionType(node) {
    forEach(node.types, checkSourceElement);
    getTypeFromTypeNode(node);
  }
  function checkIndexedAccessIndexType(type, accessNode) {
    if (!(type.flags & 8388608 /* IndexedAccess */)) {
      return type;
    }
    const objectType = type.objectType;
    const indexType = type.indexType;
    const objectIndexType = isGenericMappedType(objectType) && getMappedTypeNameTypeKind(objectType) === 2 /* Remapping */ ? getIndexTypeForMappedType(objectType, 0 /* None */) : getIndexType(objectType, 0 /* None */);
    const hasNumberIndexInfo = !!getIndexInfoOfType(objectType, numberType);
    if (everyType(indexType, (t) => isTypeAssignableTo(t, objectIndexType) || hasNumberIndexInfo && isApplicableIndexType(t, numberType))) {
      if (accessNode.kind === 212 /* ElementAccessExpression */ && isAssignmentTarget(accessNode) && getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
        error(accessNode, Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
      }
      return type;
    }
    if (isGenericObjectType(objectType)) {
      const propertyName = getPropertyNameFromIndex(indexType, accessNode);
      if (propertyName) {
        const propertySymbol = forEachType(getApparentType(objectType), (t) => getPropertyOfType(t, propertyName));
        if (propertySymbol && getDeclarationModifierFlagsFromSymbol(propertySymbol) & 6 /* NonPublicAccessibilityModifier */) {
          error(accessNode, Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, unescapeLeadingUnderscores(propertyName));
          return errorType;
        }
      }
    }
    error(accessNode, Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
    return errorType;
  }
  function checkIndexedAccessType(node) {
    checkSourceElement(node.objectType);
    checkSourceElement(node.indexType);
    checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
  }
  function checkMappedType(node) {
    checkGrammarMappedType(node);
    checkSourceElement(node.typeParameter);
    checkSourceElement(node.nameType);
    checkSourceElement(node.type);
    if (!node.type) {
      reportImplicitAny(node, anyType);
    }
    const type = getTypeFromMappedTypeNode(node);
    const nameType = getNameTypeFromMappedType(type);
    if (nameType) {
      checkTypeAssignableTo(nameType, stringNumberSymbolType, node.nameType);
    } else {
      const constraintType = getConstraintTypeFromMappedType(type);
      checkTypeAssignableTo(constraintType, stringNumberSymbolType, getEffectiveConstraintOfTypeParameter(node.typeParameter));
    }
  }
  function checkGrammarMappedType(node) {
    var _a;
    if ((_a = node.members) == null ? void 0 : _a.length) {
      return grammarErrorOnNode(node.members[0], Diagnostics.A_mapped_type_may_not_declare_properties_or_methods);
    }
  }
  function checkThisType(node) {
    getTypeFromThisTypeNode(node);
  }
  function checkTypeOperator(node) {
    checkGrammarTypeOperatorNode(node);
    checkSourceElement(node.type);
  }
  function checkConditionalType(node) {
    forEachChild(node, checkSourceElement);
  }
  function checkInferType(node) {
    if (!findAncestor(node, (n) => n.parent && n.parent.kind === 194 /* ConditionalType */ && n.parent.extendsType === n)) {
      grammarErrorOnNode(node, Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
    }
    checkSourceElement(node.typeParameter);
    const symbol = getSymbolOfDeclaration(node.typeParameter);
    if (symbol.declarations && symbol.declarations.length > 1) {
      const links = getSymbolLinks(symbol);
      if (!links.typeParametersChecked) {
        links.typeParametersChecked = true;
        const typeParameter = getDeclaredTypeOfTypeParameter(symbol);
        const declarations = getDeclarationsOfKind(symbol, 168 /* TypeParameter */);
        if (!areTypeParametersIdentical(declarations, [typeParameter], (decl) => [decl])) {
          const name = symbolToString(symbol);
          for (const declaration of declarations) {
            error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_constraints, name);
          }
        }
      }
    }
    registerForUnusedIdentifiersCheck(node);
  }
  function checkTemplateLiteralType(node) {
    for (const span of node.templateSpans) {
      checkSourceElement(span.type);
      const type = getTypeFromTypeNode(span.type);
      checkTypeAssignableTo(type, templateConstraintType, span.type);
    }
    getTypeFromTypeNode(node);
  }
  function checkImportType(node) {
    checkSourceElement(node.argument);
    if (node.attributes) {
      getResolutionModeOverride(node.attributes, grammarErrorOnNode);
    }
    checkTypeReferenceOrImport(node);
  }
  function checkNamedTupleMember(node) {
    if (node.dotDotDotToken && node.questionToken) {
      grammarErrorOnNode(node, Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest);
    }
    if (node.type.kind === 190 /* OptionalType */) {
      grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type);
    }
    if (node.type.kind === 191 /* RestType */) {
      grammarErrorOnNode(node.type, Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type);
    }
    checkSourceElement(node.type);
    getTypeFromTypeNode(node);
  }
  function isPrivateWithinAmbient(node) {
    return (hasEffectiveModifier(node, 2 /* Private */) || isPrivateIdentifierClassElementDeclaration(node)) && !!(node.flags & 33554432 /* Ambient */);
  }
  function getEffectiveDeclarationFlags(n, flagsToCheck) {
    let flags = getCombinedModifierFlagsCached(n);
    if (n.parent.kind !== 264 /* InterfaceDeclaration */ && n.parent.kind !== 263 /* ClassDeclaration */ && n.parent.kind !== 231 /* ClassExpression */ && n.flags & 33554432 /* Ambient */) {
      const container = getEnclosingContainer(n);
      if (container && container.flags & 128 /* ExportContext */ && !(flags & 128 /* Ambient */) && !(isModuleBlock(n.parent) && isModuleDeclaration(n.parent.parent) && isGlobalScopeAugmentation(n.parent.parent))) {
        flags |= 32 /* Export */;
      }
      flags |= 128 /* Ambient */;
    }
    return flags & flagsToCheck;
  }
  function checkFunctionOrConstructorSymbol(symbol) {
    addLazyDiagnostic(() => checkFunctionOrConstructorSymbolWorker(symbol));
  }
  function checkFunctionOrConstructorSymbolWorker(symbol) {
    function getCanonicalOverload(overloads, implementation) {
      const implementationSharesContainerWithFirstOverload = implementation !== void 0 && implementation.parent === overloads[0].parent;
      return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
    }
    function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck2, someOverloadFlags, allOverloadFlags) {
      const someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
      if (someButNotAllOverloadFlags !== 0) {
        const canonicalFlags = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck2);
        group(overloads, (o) => getSourceFileOfNode(o).fileName).forEach((overloadsInFile) => {
          const canonicalFlagsForFile = getEffectiveDeclarationFlags(getCanonicalOverload(overloadsInFile, implementation), flagsToCheck2);
          for (const o of overloadsInFile) {
            const deviation = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlags;
            const deviationInFile = getEffectiveDeclarationFlags(o, flagsToCheck2) ^ canonicalFlagsForFile;
            if (deviationInFile & 32 /* Export */) {
              error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
            } else if (deviationInFile & 128 /* Ambient */) {
              error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
            } else if (deviation & (2 /* Private */ | 4 /* Protected */)) {
              error(getNameOfDeclaration(o) || o, Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
            } else if (deviation & 64 /* Abstract */) {
              error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
            }
          }
        });
      }
    }
    function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken2, allHaveQuestionToken2) {
      if (someHaveQuestionToken2 !== allHaveQuestionToken2) {
        const canonicalHasQuestionToken = hasQuestionToken(getCanonicalOverload(overloads, implementation));
        forEach(overloads, (o) => {
          const deviation = hasQuestionToken(o) !== canonicalHasQuestionToken;
          if (deviation) {
            error(getNameOfDeclaration(o), Diagnostics.Overload_signatures_must_all_be_optional_or_required);
          }
        });
      }
    }
    const flagsToCheck = 32 /* Export */ | 128 /* Ambient */ | 2 /* Private */ | 4 /* Protected */ | 64 /* Abstract */;
    let someNodeFlags = 0 /* None */;
    let allNodeFlags = flagsToCheck;
    let someHaveQuestionToken = false;
    let allHaveQuestionToken = true;
    let hasOverloads = false;
    let bodyDeclaration;
    let lastSeenNonAmbientDeclaration;
    let previousDeclaration;
    const declarations = symbol.declarations;
    const isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
    function reportImplementationExpectedError(node) {
      if (node.name && nodeIsMissing(node.name)) {
        return;
      }
      let seen = false;
      const subsequentNode = forEachChild(node.parent, (c) => {
        if (seen) {
          return c;
        } else {
          seen = c === node;
        }
      });
      if (subsequentNode && subsequentNode.pos === node.end) {
        if (subsequentNode.kind === node.kind) {
          const errorNode2 = subsequentNode.name || subsequentNode;
          const subsequentName = subsequentNode.name;
          if (node.name && subsequentName && // both are private identifiers
          (isPrivateIdentifier(node.name) && isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText || // Both are computed property names
          isComputedPropertyName(node.name) && isComputedPropertyName(subsequentName) && isTypeIdenticalTo(checkComputedPropertyName(node.name), checkComputedPropertyName(subsequentName)) || // Both are literal property names that are the same.
          isPropertyNameLiteral(node.name) && isPropertyNameLiteral(subsequentName) && getEscapedTextOfIdentifierOrLiteral(node.name) === getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
            const reportError = (node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */) && isStatic(node) !== isStatic(subsequentNode);
            if (reportError) {
              const diagnostic = isStatic(node) ? Diagnostics.Function_overload_must_be_static : Diagnostics.Function_overload_must_not_be_static;
              error(errorNode2, diagnostic);
            }
            return;
          }
          if (nodeIsPresent(subsequentNode.body)) {
            error(errorNode2, Diagnostics.Function_implementation_name_must_be_0, declarationNameToString(node.name));
            return;
          }
        }
      }
      const errorNode = node.name || node;
      if (isConstructor) {
        error(errorNode, Diagnostics.Constructor_implementation_is_missing);
      } else {
        if (hasSyntacticModifier(node, 64 /* Abstract */)) {
          error(errorNode, Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
        } else {
          error(errorNode, Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
        }
      }
    }
    let duplicateFunctionDeclaration = false;
    let multipleConstructorImplementation = false;
    let hasNonAmbientClass = false;
    const functionDeclarations = [];
    if (declarations) {
      for (const current of declarations) {
        const node = current;
        const inAmbientContext = node.flags & 33554432 /* Ambient */;
        const inAmbientContextOrInterface = node.parent && (node.parent.kind === 264 /* InterfaceDeclaration */ || node.parent.kind === 187 /* TypeLiteral */) || inAmbientContext;
        if (inAmbientContextOrInterface) {
          previousDeclaration = void 0;
        }
        if ((node.kind === 263 /* ClassDeclaration */ || node.kind === 231 /* ClassExpression */) && !inAmbientContext) {
          hasNonAmbientClass = true;
        }
        if (node.kind === 262 /* FunctionDeclaration */ || node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ || node.kind === 176 /* Constructor */) {
          functionDeclarations.push(node);
          const currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
          someNodeFlags |= currentNodeFlags;
          allNodeFlags &= currentNodeFlags;
          someHaveQuestionToken = someHaveQuestionToken || hasQuestionToken(node);
          allHaveQuestionToken = allHaveQuestionToken && hasQuestionToken(node);
          const bodyIsPresent = nodeIsPresent(node.body);
          if (bodyIsPresent && bodyDeclaration) {
            if (isConstructor) {
              multipleConstructorImplementation = true;
            } else {
              duplicateFunctionDeclaration = true;
            }
          } else if ((previousDeclaration == null ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) {
            reportImplementationExpectedError(previousDeclaration);
          }
          if (bodyIsPresent) {
            if (!bodyDeclaration) {
              bodyDeclaration = node;
            }
          } else {
            hasOverloads = true;
          }
          previousDeclaration = node;
          if (!inAmbientContextOrInterface) {
            lastSeenNonAmbientDeclaration = node;
          }
        }
        if (isInJSFile(current) && isFunctionLike(current) && current.jsDoc) {
          hasOverloads = length(getJSDocOverloadTags(current)) > 0;
        }
      }
    }
    if (multipleConstructorImplementation) {
      forEach(functionDeclarations, (declaration) => {
        error(declaration, Diagnostics.Multiple_constructor_implementations_are_not_allowed);
      });
    }
    if (duplicateFunctionDeclaration) {
      forEach(functionDeclarations, (declaration) => {
        error(getNameOfDeclaration(declaration) || declaration, Diagnostics.Duplicate_function_implementation);
      });
    }
    if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */ && declarations) {
      const relatedDiagnostics = filter(declarations, (d) => d.kind === 263 /* ClassDeclaration */).map((d) => createDiagnosticForNode(d, Diagnostics.Consider_adding_a_declare_modifier_to_this_class));
      forEach(declarations, (declaration) => {
        const diagnostic = declaration.kind === 263 /* ClassDeclaration */ ? Diagnostics.Class_declaration_cannot_implement_overload_list_for_0 : declaration.kind === 262 /* FunctionDeclaration */ ? Diagnostics.Function_with_bodies_can_only_merge_with_classes_that_are_ambient : void 0;
        if (diagnostic) {
          addRelatedInfo(
            error(getNameOfDeclaration(declaration) || declaration, diagnostic, symbolName(symbol)),
            ...relatedDiagnostics
          );
        }
      });
    }
    if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body && !hasSyntacticModifier(lastSeenNonAmbientDeclaration, 64 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
      reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
    }
    if (hasOverloads) {
      if (declarations) {
        checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
        checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
      }
      if (bodyDeclaration) {
        const signatures = getSignaturesOfSymbol(symbol);
        const bodySignature = getSignatureFromDeclaration(bodyDeclaration);
        for (const signature of signatures) {
          if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
            const errorNode = signature.declaration && isJSDocSignature(signature.declaration) ? signature.declaration.parent.tagName : signature.declaration;
            addRelatedInfo(
              error(errorNode, Diagnostics.This_overload_signature_is_not_compatible_with_its_implementation_signature),
              createDiagnosticForNode(bodyDeclaration, Diagnostics.The_implementation_signature_is_declared_here)
            );
            break;
          }
        }
      }
    }
  }
  function checkExportsOnMergedDeclarations(node) {
    addLazyDiagnostic(() => checkExportsOnMergedDeclarationsWorker(node));
  }
  function checkExportsOnMergedDeclarationsWorker(node) {
    let symbol = node.localSymbol;
    if (!symbol) {
      symbol = getSymbolOfDeclaration(node);
      if (!symbol.exportSymbol) {
        return;
      }
    }
    if (getDeclarationOfKind(symbol, node.kind) !== node) {
      return;
    }
    let exportedDeclarationSpaces = 0 /* None */;
    let nonExportedDeclarationSpaces = 0 /* None */;
    let defaultExportedDeclarationSpaces = 0 /* None */;
    for (const d of symbol.declarations) {
      const declarationSpaces = getDeclarationSpaces(d);
      const effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 32 /* Export */ | 2048 /* Default */);
      if (effectiveDeclarationFlags & 32 /* Export */) {
        if (effectiveDeclarationFlags & 2048 /* Default */) {
          defaultExportedDeclarationSpaces |= declarationSpaces;
        } else {
          exportedDeclarationSpaces |= declarationSpaces;
        }
      } else {
        nonExportedDeclarationSpaces |= declarationSpaces;
      }
    }
    const nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
    const commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
    const commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
    if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
      for (const d of symbol.declarations) {
        const declarationSpaces = getDeclarationSpaces(d);
        const name = getNameOfDeclaration(d);
        if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
          error(name, Diagnostics.Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead, declarationNameToString(name));
        } else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
          error(name, Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, declarationNameToString(name));
        }
      }
    }
    function getDeclarationSpaces(decl) {
      let d = decl;
      switch (d.kind) {
        case 264 /* InterfaceDeclaration */:
        case 265 /* TypeAliasDeclaration */:
        // A jsdoc typedef and callback are, by definition, type aliases.
        // falls through
        case 346 /* JSDocTypedefTag */:
        case 338 /* JSDocCallbackTag */:
        case 340 /* JSDocEnumTag */:
          return 2 /* ExportType */;
        case 267 /* ModuleDeclaration */:
          return isAmbientModule(d) || getModuleInstanceState(d) !== 0 /* NonInstantiated */ ? 4 /* ExportNamespace */ | 1 /* ExportValue */ : 4 /* ExportNamespace */;
        case 263 /* ClassDeclaration */:
        case 266 /* EnumDeclaration */:
        case 306 /* EnumMember */:
          return 2 /* ExportType */ | 1 /* ExportValue */;
        case 307 /* SourceFile */:
          return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
        case 277 /* ExportAssignment */:
        case 226 /* BinaryExpression */:
          const node2 = d;
          const expression = isExportAssignment(node2) ? node2.expression : node2.right;
          if (!isEntityNameExpression(expression)) {
            return 1 /* ExportValue */;
          }
          d = expression;
        // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
        // falls through
        case 271 /* ImportEqualsDeclaration */:
        case 274 /* NamespaceImport */:
        case 273 /* ImportClause */:
          let result = 0 /* None */;
          const target = resolveAlias(getSymbolOfDeclaration(d));
          forEach(target.declarations, (d2) => {
            result |= getDeclarationSpaces(d2);
          });
          return result;
        case 260 /* VariableDeclaration */:
        case 208 /* BindingElement */:
        case 262 /* FunctionDeclaration */:
        case 276 /* ImportSpecifier */:
        // https://github.com/Microsoft/TypeScript/pull/7591
        case 80 /* Identifier */:
          return 1 /* ExportValue */;
        case 173 /* MethodSignature */:
        case 171 /* PropertySignature */:
          return 2 /* ExportType */;
        default:
          return Debug.failBadSyntaxKind(d);
      }
    }
  }
  function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, ...args) {
    const promisedType = getPromisedTypeOfPromise(type, errorNode);
    return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, ...args);
  }
  function getPromisedTypeOfPromise(type, errorNode, thisTypeForErrorOut) {
    if (isTypeAny(type)) {
      return void 0;
    }
    const typeAsPromise = type;
    if (typeAsPromise.promisedTypeOfPromise) {
      return typeAsPromise.promisedTypeOfPromise;
    }
    if (isReferenceToType(type, getGlobalPromiseType(
      /*reportErrors*/
      false
    ))) {
      return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
    }
    if (allTypesAssignableToKind(getBaseConstraintOrType(type), 402784252 /* Primitive */ | 131072 /* Never */)) {
      return void 0;
    }
    const thenFunction = getTypeOfPropertyOfType(type, "then");
    if (isTypeAny(thenFunction)) {
      return void 0;
    }
    const thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : emptyArray;
    if (thenSignatures.length === 0) {
      if (errorNode) {
        error(errorNode, Diagnostics.A_promise_must_have_a_then_method);
      }
      return void 0;
    }
    let thisTypeForError;
    let candidates;
    for (const thenSignature of thenSignatures) {
      const thisType = getThisTypeOfSignature(thenSignature);
      if (thisType && thisType !== voidType && !isTypeRelatedTo(type, thisType, subtypeRelation)) {
        thisTypeForError = thisType;
      } else {
        candidates = append(candidates, thenSignature);
      }
    }
    if (!candidates) {
      Debug.assertIsDefined(thisTypeForError);
      if (thisTypeForErrorOut) {
        thisTypeForErrorOut.value = thisTypeForError;
      }
      if (errorNode) {
        error(errorNode, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForError));
      }
      return void 0;
    }
    const onfulfilledParameterType = getTypeWithFacts(getUnionType(map(candidates, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
    if (isTypeAny(onfulfilledParameterType)) {
      return void 0;
    }
    const onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
    if (onfulfilledParameterSignatures.length === 0) {
      if (errorNode) {
        error(errorNode, Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
      }
      return void 0;
    }
    return typeAsPromise.promisedTypeOfPromise = getUnionType(map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
  }
  function checkAwaitedType(type, withAlias, errorNode, diagnosticMessage, ...args) {
    const awaitedType = withAlias ? getAwaitedType(type, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args);
    return awaitedType || errorType;
  }
  function isThenableType(type) {
    if (allTypesAssignableToKind(getBaseConstraintOrType(type), 402784252 /* Primitive */ | 131072 /* Never */)) {
      return false;
    }
    const thenFunction = getTypeOfPropertyOfType(type, "then");
    return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
  }
  function isAwaitedTypeInstantiation(type) {
    var _a;
    if (type.flags & 16777216 /* Conditional */) {
      const awaitedSymbol = getGlobalAwaitedSymbol(
        /*reportErrors*/
        false
      );
      return !!awaitedSymbol && type.aliasSymbol === awaitedSymbol && ((_a = type.aliasTypeArguments) == null ? void 0 : _a.length) === 1;
    }
    return false;
  }
  function unwrapAwaitedType(type) {
    return type.flags & 1048576 /* Union */ ? mapType(type, unwrapAwaitedType) : isAwaitedTypeInstantiation(type) ? type.aliasTypeArguments[0] : type;
  }
  function isAwaitedTypeNeeded(type) {
    if (isTypeAny(type) || isAwaitedTypeInstantiation(type)) {
      return false;
    }
    if (isGenericObjectType(type)) {
      const baseConstraint = getBaseConstraintOfType(type);
      if (baseConstraint ? baseConstraint.flags & 3 /* AnyOrUnknown */ || isEmptyObjectType(baseConstraint) || someType(baseConstraint, isThenableType) : maybeTypeOfKind(type, 8650752 /* TypeVariable */)) {
        return true;
      }
    }
    return false;
  }
  function tryCreateAwaitedType(type) {
    const awaitedSymbol = getGlobalAwaitedSymbol(
      /*reportErrors*/
      true
    );
    if (awaitedSymbol) {
      return getTypeAliasInstantiation(awaitedSymbol, [unwrapAwaitedType(type)]);
    }
    return void 0;
  }
  function createAwaitedTypeIfNeeded(type) {
    if (isAwaitedTypeNeeded(type)) {
      return tryCreateAwaitedType(type) ?? type;
    }
    Debug.assert(isAwaitedTypeInstantiation(type) || getPromisedTypeOfPromise(type) === void 0, "type provided should not be a non-generic 'promise'-like.");
    return type;
  }
  function getAwaitedType(type, errorNode, diagnosticMessage, ...args) {
    const awaitedType = getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args);
    return awaitedType && createAwaitedTypeIfNeeded(awaitedType);
  }
  function getAwaitedTypeNoAlias(type, errorNode, diagnosticMessage, ...args) {
    if (isTypeAny(type)) {
      return type;
    }
    if (isAwaitedTypeInstantiation(type)) {
      return type;
    }
    const typeAsAwaitable = type;
    if (typeAsAwaitable.awaitedTypeOfType) {
      return typeAsAwaitable.awaitedTypeOfType;
    }
    if (type.flags & 1048576 /* Union */) {
      if (awaitedTypeStack.lastIndexOf(type.id) >= 0) {
        if (errorNode) {
          error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
        }
        return void 0;
      }
      const mapper = errorNode ? (constituentType) => getAwaitedTypeNoAlias(constituentType, errorNode, diagnosticMessage, ...args) : getAwaitedTypeNoAlias;
      awaitedTypeStack.push(type.id);
      const mapped = mapType(type, mapper);
      awaitedTypeStack.pop();
      return typeAsAwaitable.awaitedTypeOfType = mapped;
    }
    if (isAwaitedTypeNeeded(type)) {
      return typeAsAwaitable.awaitedTypeOfType = type;
    }
    const thisTypeForErrorOut = { value: void 0 };
    const promisedType = getPromisedTypeOfPromise(
      type,
      /*errorNode*/
      void 0,
      thisTypeForErrorOut
    );
    if (promisedType) {
      if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
        if (errorNode) {
          error(errorNode, Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
        }
        return void 0;
      }
      awaitedTypeStack.push(type.id);
      const awaitedType = getAwaitedTypeNoAlias(promisedType, errorNode, diagnosticMessage, ...args);
      awaitedTypeStack.pop();
      if (!awaitedType) {
        return void 0;
      }
      return typeAsAwaitable.awaitedTypeOfType = awaitedType;
    }
    if (isThenableType(type)) {
      if (errorNode) {
        Debug.assertIsDefined(diagnosticMessage);
        let chain;
        if (thisTypeForErrorOut.value) {
          chain = chainDiagnosticMessages(chain, Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1, typeToString(type), typeToString(thisTypeForErrorOut.value));
        }
        chain = chainDiagnosticMessages(chain, diagnosticMessage, ...args);
        diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(errorNode), errorNode, chain));
      }
      return void 0;
    }
    return typeAsAwaitable.awaitedTypeOfType = type;
  }
  function checkAsyncFunctionReturnType(node, returnTypeNode, returnTypeErrorLocation) {
    const returnType = getTypeFromTypeNode(returnTypeNode);
    if (languageVersion >= 2 /* ES2015 */) {
      if (isErrorType(returnType)) {
        return;
      }
      const globalPromiseType = getGlobalPromiseType(
        /*reportErrors*/
        true
      );
      if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
        reportErrorForInvalidReturnType(Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, returnTypeNode, returnTypeErrorLocation, typeToString(getAwaitedTypeNoAlias(returnType) || voidType));
        return;
      }
    } else {
      markLinkedReferences(node, 5 /* AsyncFunction */);
      if (isErrorType(returnType)) {
        return;
      }
      const promiseConstructorName = getEntityNameFromTypeNode(returnTypeNode);
      if (promiseConstructorName === void 0) {
        reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, typeToString(returnType));
        return;
      }
      const promiseConstructorSymbol = resolveEntityName(
        promiseConstructorName,
        111551 /* Value */,
        /*ignoreErrors*/
        true
      );
      const promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
      if (isErrorType(promiseConstructorType)) {
        if (promiseConstructorName.kind === 80 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(
          /*reportErrors*/
          false
        )) {
          error(returnTypeErrorLocation, Diagnostics.An_async_function_or_method_in_ES5_requires_the_Promise_constructor_Make_sure_you_have_a_declaration_for_the_Promise_constructor_or_include_ES2015_in_your_lib_option);
        } else {
          reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName));
        }
        return;
      }
      const globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(
        /*reportErrors*/
        true
      );
      if (globalPromiseConstructorLikeType === emptyObjectType) {
        reportErrorForInvalidReturnType(Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value, returnTypeNode, returnTypeErrorLocation, entityNameToString(promiseConstructorName));
        return;
      }
      const headMessage = Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_because_it_does_not_refer_to_a_Promise_compatible_constructor_value;
      const errorInfo = () => returnTypeNode === returnTypeErrorLocation ? void 0 : chainDiagnosticMessages(
        /*details*/
        void 0,
        Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type
      );
      if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeErrorLocation, headMessage, errorInfo)) {
        return;
      }
      const rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName);
      const collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
      if (collidingSymbol) {
        error(collidingSymbol.valueDeclaration, Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, idText(rootName), entityNameToString(promiseConstructorName));
        return;
      }
    }
    checkAwaitedType(
      returnType,
      /*withAlias*/
      false,
      node,
      Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
    );
    function reportErrorForInvalidReturnType(message, returnTypeNode2, returnTypeErrorLocation2, typeName) {
      if (returnTypeNode2 === returnTypeErrorLocation2) {
        error(returnTypeErrorLocation2, message, typeName);
      } else {
        const diag2 = error(returnTypeErrorLocation2, Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type);
        addRelatedInfo(diag2, createDiagnosticForNode(returnTypeNode2, message, typeName));
      }
    }
  }
  function checkGrammarDecorator(decorator) {
    const sourceFile = getSourceFileOfNode(decorator);
    if (!hasParseDiagnostics(sourceFile)) {
      let node = decorator.expression;
      if (isParenthesizedExpression(node)) {
        return false;
      }
      let canHaveCallExpression = true;
      let errorNode;
      while (true) {
        if (isExpressionWithTypeArguments(node) || isNonNullExpression(node)) {
          node = node.expression;
          continue;
        }
        if (isCallExpression(node)) {
          if (!canHaveCallExpression) {
            errorNode = node;
          }
          if (node.questionDotToken) {
            errorNode = node.questionDotToken;
          }
          node = node.expression;
          canHaveCallExpression = false;
          continue;
        }
        if (isPropertyAccessExpression(node)) {
          if (node.questionDotToken) {
            errorNode = node.questionDotToken;
          }
          node = node.expression;
          canHaveCallExpression = false;
          continue;
        }
        if (!isIdentifier(node)) {
          errorNode = node;
        }
        break;
      }
      if (errorNode) {
        addRelatedInfo(
          error(decorator.expression, Diagnostics.Expression_must_be_enclosed_in_parentheses_to_be_used_as_a_decorator),
          createDiagnosticForNode(errorNode, Diagnostics.Invalid_syntax_in_decorator)
        );
        return true;
      }
    }
    return false;
  }
  function checkDecorator(node) {
    checkGrammarDecorator(node);
    const signature = getResolvedSignature(node);
    checkDeprecatedSignature(signature, node);
    const returnType = getReturnTypeOfSignature(signature);
    if (returnType.flags & 1 /* Any */) {
      return;
    }
    const decoratorSignature = getDecoratorCallSignature(node);
    if (!(decoratorSignature == null ? void 0 : decoratorSignature.resolvedReturnType)) return;
    let headMessage;
    const expectedReturnType = decoratorSignature.resolvedReturnType;
    switch (node.parent.kind) {
      case 263 /* ClassDeclaration */:
      case 231 /* ClassExpression */:
        headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
        break;
      case 172 /* PropertyDeclaration */:
        if (!legacyDecorators) {
          headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
          break;
        }
      // falls through
      case 169 /* Parameter */:
        headMessage = Diagnostics.Decorator_function_return_type_is_0_but_is_expected_to_be_void_or_any;
        break;
      case 174 /* MethodDeclaration */:
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        headMessage = Diagnostics.Decorator_function_return_type_0_is_not_assignable_to_type_1;
        break;
      default:
        return Debug.failBadSyntaxKind(node.parent);
    }
    checkTypeAssignableTo(returnType, expectedReturnType, node.expression, headMessage);
  }
  function createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount = parameters.length, flags = 0 /* None */) {
    const decl = factory.createFunctionTypeNode(
      /*typeParameters*/
      void 0,
      emptyArray,
      factory.createKeywordTypeNode(133 /* AnyKeyword */)
    );
    return createSignature(decl, typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags);
  }
  function createFunctionType(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags) {
    const signature = createCallSignature(typeParameters, thisParameter, parameters, returnType, typePredicate, minArgumentCount, flags);
    return getOrCreateTypeFromSignature(signature);
  }
  function createGetterFunctionType(type) {
    return createFunctionType(
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      emptyArray,
      type
    );
  }
  function createSetterFunctionType(type) {
    const valueParam = createParameter("value", type);
    return createFunctionType(
      /*typeParameters*/
      void 0,
      /*thisParameter*/
      void 0,
      [valueParam],
      voidType
    );
  }
  function getEntityNameForDecoratorMetadata(node) {
    if (node) {
      switch (node.kind) {
        case 193 /* IntersectionType */:
        case 192 /* UnionType */:
          return getEntityNameForDecoratorMetadataFromTypeList(node.types);
        case 194 /* ConditionalType */:
          return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
        case 196 /* ParenthesizedType */:
        case 202 /* NamedTupleMember */:
          return getEntityNameForDecoratorMetadata(node.type);
        case 183 /* TypeReference */:
          return node.typeName;
      }
    }
  }
  function getEntityNameForDecoratorMetadataFromTypeList(types) {
    let commonEntityName;
    for (let typeNode of types) {
      while (typeNode.kind === 196 /* ParenthesizedType */ || typeNode.kind === 202 /* NamedTupleMember */) {
        typeNode = typeNode.type;
      }
      if (typeNode.kind === 146 /* NeverKeyword */) {
        continue;
      }
      if (!strictNullChecks && (typeNode.kind === 201 /* LiteralType */ && typeNode.literal.kind === 106 /* NullKeyword */ || typeNode.kind === 157 /* UndefinedKeyword */)) {
        continue;
      }
      const individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
      if (!individualEntityName) {
        return void 0;
      }
      if (commonEntityName) {
        if (!isIdentifier(commonEntityName) || !isIdentifier(individualEntityName) || commonEntityName.escapedText !== individualEntityName.escapedText) {
          return void 0;
        }
      } else {
        commonEntityName = individualEntityName;
      }
    }
    return commonEntityName;
  }
  function getParameterTypeNodeForDecoratorCheck(node) {
    const typeNode = getEffectiveTypeAnnotationNode(node);
    return isRestParameter(node) ? getRestParameterElementType(typeNode) : typeNode;
  }
  function checkDecorators(node) {
    if (!canHaveDecorators(node) || !hasDecorators(node) || !node.modifiers || !nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) {
      return;
    }
    const firstDecorator = find(node.modifiers, isDecorator);
    if (!firstDecorator) {
      return;
    }
    if (legacyDecorators) {
      checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
      if (node.kind === 169 /* Parameter */) {
        checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
      }
    } else if (languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators) {
      checkExternalEmitHelpers(firstDecorator, 8 /* ESDecorateAndRunInitializers */);
      if (isClassDeclaration(node)) {
        if (!node.name) {
          checkExternalEmitHelpers(firstDecorator, 4194304 /* SetFunctionName */);
        } else {
          const member = getFirstTransformableStaticClassElement(node);
          if (member) {
            checkExternalEmitHelpers(firstDecorator, 4194304 /* SetFunctionName */);
          }
        }
      } else if (!isClassExpression(node)) {
        if (isPrivateIdentifier(node.name) && (isMethodDeclaration(node) || isAccessor(node) || isAutoAccessorPropertyDeclaration(node))) {
          checkExternalEmitHelpers(firstDecorator, 4194304 /* SetFunctionName */);
        }
        if (isComputedPropertyName(node.name)) {
          checkExternalEmitHelpers(firstDecorator, 8388608 /* PropKey */);
        }
      }
    }
    markLinkedReferences(node, 8 /* Decorator */);
    for (const modifier of node.modifiers) {
      if (isDecorator(modifier)) {
        checkDecorator(modifier);
      }
    }
  }
  function checkFunctionDeclaration(node) {
    addLazyDiagnostic(checkFunctionDeclarationDiagnostics);
    function checkFunctionDeclarationDiagnostics() {
      checkFunctionOrMethodDeclaration(node);
      checkGrammarForGenerator(node);
      checkCollisionsForDeclarationName(node, node.name);
    }
  }
  function checkJSDocTypeAliasTag(node) {
    if (!node.typeExpression) {
      error(node.name, Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
    }
    if (node.name) {
      checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0);
    }
    checkSourceElement(node.typeExpression);
    checkTypeParameters(getEffectiveTypeParameterDeclarations(node));
  }
  function checkJSDocTemplateTag(node) {
    checkSourceElement(node.constraint);
    for (const tp of node.typeParameters) {
      checkSourceElement(tp);
    }
  }
  function checkJSDocTypeTag(node) {
    checkSourceElement(node.typeExpression);
  }
  function checkJSDocSatisfiesTag(node) {
    checkSourceElement(node.typeExpression);
    const host2 = getEffectiveJSDocHost(node);
    if (host2) {
      const tags = getAllJSDocTags(host2, isJSDocSatisfiesTag);
      if (length(tags) > 1) {
        for (let i = 1; i < length(tags); i++) {
          const tagName = tags[i].tagName;
          error(tagName, Diagnostics._0_tag_already_specified, idText(tagName));
        }
      }
    }
  }
  function checkJSDocLinkLikeTag(node) {
    if (node.name) {
      resolveJSDocMemberName(
        node.name,
        /*ignoreErrors*/
        true
      );
    }
  }
  function checkJSDocParameterTag(node) {
    checkSourceElement(node.typeExpression);
  }
  function checkJSDocPropertyTag(node) {
    checkSourceElement(node.typeExpression);
  }
  function checkJSDocFunctionType(node) {
    addLazyDiagnostic(checkJSDocFunctionTypeImplicitAny);
    checkSignatureDeclaration(node);
    function checkJSDocFunctionTypeImplicitAny() {
      if (!node.type && !isJSDocConstructSignature(node)) {
        reportImplicitAny(node, anyType);
      }
    }
  }
  function checkJSDocThisTag(node) {
    const host2 = getEffectiveJSDocHost(node);
    if (host2 && isArrowFunction(host2)) {
      error(node.tagName, Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
    }
  }
  function checkJSDocImportTag(node) {
    checkImportAttributes(node);
  }
  function checkJSDocImplementsTag(node) {
    const classLike = getEffectiveJSDocHost(node);
    if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) {
      error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName));
    }
  }
  function checkJSDocAugmentsTag(node) {
    const classLike = getEffectiveJSDocHost(node);
    if (!classLike || !isClassDeclaration(classLike) && !isClassExpression(classLike)) {
      error(classLike, Diagnostics.JSDoc_0_is_not_attached_to_a_class, idText(node.tagName));
      return;
    }
    const augmentsTags = getJSDocTags(classLike).filter(isJSDocAugmentsTag);
    Debug.assert(augmentsTags.length > 0);
    if (augmentsTags.length > 1) {
      error(augmentsTags[1], Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
    }
    const name = getIdentifierFromEntityNameExpression(node.class.expression);
    const extend2 = getClassExtendsHeritageElement(classLike);
    if (extend2) {
      const className = getIdentifierFromEntityNameExpression(extend2.expression);
      if (className && name.escapedText !== className.escapedText) {
        error(name, Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, idText(node.tagName), idText(name), idText(className));
      }
    }
  }
  function checkJSDocAccessibilityModifiers(node) {
    const host2 = getJSDocHost(node);
    if (host2 && isPrivateIdentifierClassElementDeclaration(host2)) {
      error(node, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
    }
  }
  function getIdentifierFromEntityNameExpression(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return node;
      case 211 /* PropertyAccessExpression */:
        return node.name;
      default:
        return void 0;
    }
  }
  function checkFunctionOrMethodDeclaration(node) {
    var _a;
    checkDecorators(node);
    checkSignatureDeclaration(node);
    const functionFlags = getFunctionFlags(node);
    if (node.name && node.name.kind === 167 /* ComputedPropertyName */) {
      checkComputedPropertyName(node.name);
    }
    if (hasBindableName(node)) {
      const symbol = getSymbolOfDeclaration(node);
      const localSymbol = node.localSymbol || symbol;
      const firstDeclaration = (_a = localSymbol.declarations) == null ? void 0 : _a.find(
        // Get first non javascript function declaration
        (declaration) => declaration.kind === node.kind && !(declaration.flags & 524288 /* JavaScriptFile */)
      );
      if (node === firstDeclaration) {
        checkFunctionOrConstructorSymbol(localSymbol);
      }
      if (symbol.parent) {
        checkFunctionOrConstructorSymbol(symbol);
      }
    }
    const body = node.kind === 173 /* MethodSignature */ ? void 0 : node.body;
    checkSourceElement(body);
    checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
    addLazyDiagnostic(checkFunctionOrMethodDeclarationDiagnostics);
    if (isInJSFile(node)) {
      const typeTag = getJSDocTypeTag(node);
      if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
        error(typeTag.typeExpression.type, Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
      }
    }
    function checkFunctionOrMethodDeclarationDiagnostics() {
      if (!getEffectiveReturnTypeNode(node)) {
        if (nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
          reportImplicitAny(node, anyType);
        }
        if (functionFlags & 1 /* Generator */ && nodeIsPresent(body)) {
          getReturnTypeOfSignature(getSignatureFromDeclaration(node));
        }
      }
    }
  }
  function registerForUnusedIdentifiersCheck(node) {
    addLazyDiagnostic(registerForUnusedIdentifiersCheckDiagnostics);
    function registerForUnusedIdentifiersCheckDiagnostics() {
      const sourceFile = getSourceFileOfNode(node);
      let potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
      if (!potentiallyUnusedIdentifiers) {
        potentiallyUnusedIdentifiers = [];
        allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
      }
      potentiallyUnusedIdentifiers.push(node);
    }
  }
  function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
    for (const node of potentiallyUnusedIdentifiers) {
      switch (node.kind) {
        case 263 /* ClassDeclaration */:
        case 231 /* ClassExpression */:
          checkUnusedClassMembers(node, addDiagnostic);
          checkUnusedTypeParameters(node, addDiagnostic);
          break;
        case 307 /* SourceFile */:
        case 267 /* ModuleDeclaration */:
        case 241 /* Block */:
        case 269 /* CaseBlock */:
        case 248 /* ForStatement */:
        case 249 /* ForInStatement */:
        case 250 /* ForOfStatement */:
          checkUnusedLocalsAndParameters(node, addDiagnostic);
          break;
        case 176 /* Constructor */:
        case 218 /* FunctionExpression */:
        case 262 /* FunctionDeclaration */:
        case 219 /* ArrowFunction */:
        case 174 /* MethodDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          if (node.body) {
            checkUnusedLocalsAndParameters(node, addDiagnostic);
          }
          checkUnusedTypeParameters(node, addDiagnostic);
          break;
        case 173 /* MethodSignature */:
        case 179 /* CallSignature */:
        case 180 /* ConstructSignature */:
        case 184 /* FunctionType */:
        case 185 /* ConstructorType */:
        case 265 /* TypeAliasDeclaration */:
        case 264 /* InterfaceDeclaration */:
          checkUnusedTypeParameters(node, addDiagnostic);
          break;
        case 195 /* InferType */:
          checkUnusedInferTypeParameter(node, addDiagnostic);
          break;
        default:
          Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
      }
    }
  }
  function errorUnusedLocal(declaration, name, addDiagnostic) {
    const node = getNameOfDeclaration(declaration) || declaration;
    const message = isTypeDeclaration(declaration) ? Diagnostics._0_is_declared_but_never_used : Diagnostics._0_is_declared_but_its_value_is_never_read;
    addDiagnostic(declaration, 0 /* Local */, createDiagnosticForNode(node, message, name));
  }
  function isIdentifierThatStartsWithUnderscore(node) {
    return isIdentifier(node) && idText(node).charCodeAt(0) === 95 /* _ */;
  }
  function checkUnusedClassMembers(node, addDiagnostic) {
    for (const member of node.members) {
      switch (member.kind) {
        case 174 /* MethodDeclaration */:
        case 172 /* PropertyDeclaration */:
        case 177 /* GetAccessor */:
        case 178 /* SetAccessor */:
          if (member.kind === 178 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
            break;
          }
          const symbol = getSymbolOfDeclaration(member);
          if (!symbol.isReferenced && (hasEffectiveModifier(member, 2 /* Private */) || isNamedDeclaration(member) && isPrivateIdentifier(member.name)) && !(member.flags & 33554432 /* Ambient */)) {
            addDiagnostic(member, 0 /* Local */, createDiagnosticForNode(member.name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
          }
          break;
        case 176 /* Constructor */:
          for (const parameter of member.parameters) {
            if (!parameter.symbol.isReferenced && hasSyntacticModifier(parameter, 2 /* Private */)) {
              addDiagnostic(parameter, 0 /* Local */, createDiagnosticForNode(parameter.name, Diagnostics.Property_0_is_declared_but_its_value_is_never_read, symbolName(parameter.symbol)));
            }
          }
          break;
        case 181 /* IndexSignature */:
        case 240 /* SemicolonClassElement */:
        case 175 /* ClassStaticBlockDeclaration */:
          break;
        default:
          Debug.fail("Unexpected class member");
      }
    }
  }
  function checkUnusedInferTypeParameter(node, addDiagnostic) {
    const { typeParameter } = node;
    if (isTypeParameterUnused(typeParameter)) {
      addDiagnostic(node, 1 /* Parameter */, createDiagnosticForNode(node, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(typeParameter.name)));
    }
  }
  function checkUnusedTypeParameters(node, addDiagnostic) {
    const declarations = getSymbolOfDeclaration(node).declarations;
    if (!declarations || last(declarations) !== node) return;
    const typeParameters = getEffectiveTypeParameterDeclarations(node);
    const seenParentsWithEveryUnused = /* @__PURE__ */ new Set();
    for (const typeParameter of typeParameters) {
      if (!isTypeParameterUnused(typeParameter)) continue;
      const name = idText(typeParameter.name);
      const { parent } = typeParameter;
      if (parent.kind !== 195 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
        if (tryAddToSet(seenParentsWithEveryUnused, parent)) {
          const sourceFile = getSourceFileOfNode(parent);
          const range = isJSDocTemplateTag(parent) ? rangeOfNode(parent) : rangeOfTypeParameters(sourceFile, parent.typeParameters);
          const only = parent.typeParameters.length === 1;
          const messageAndArg = only ? [Diagnostics._0_is_declared_but_its_value_is_never_read, name] : [Diagnostics.All_type_parameters_are_unused];
          addDiagnostic(typeParameter, 1 /* Parameter */, createFileDiagnostic(sourceFile, range.pos, range.end - range.pos, ...messageAndArg));
        }
      } else {
        addDiagnostic(typeParameter, 1 /* Parameter */, createDiagnosticForNode(typeParameter, Diagnostics._0_is_declared_but_its_value_is_never_read, name));
      }
    }
  }
  function isTypeParameterUnused(typeParameter) {
    return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
  }
  function addToGroup(map2, key, value, getKey) {
    const keyString = String(getKey(key));
    const group2 = map2.get(keyString);
    if (group2) {
      group2[1].push(value);
    } else {
      map2.set(keyString, [key, [value]]);
    }
  }
  function tryGetRootParameterDeclaration(node) {
    return tryCast(getRootDeclaration(node), isParameter);
  }
  function isValidUnusedLocalDeclaration(declaration) {
    if (isBindingElement(declaration)) {
      if (isObjectBindingPattern(declaration.parent)) {
        return !!(declaration.propertyName && isIdentifierThatStartsWithUnderscore(declaration.name));
      }
      return isIdentifierThatStartsWithUnderscore(declaration.name);
    }
    return isAmbientModule(declaration) || (isVariableDeclaration(declaration) && isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
  }
  function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
    const unusedImports = /* @__PURE__ */ new Map();
    const unusedDestructures = /* @__PURE__ */ new Map();
    const unusedVariables = /* @__PURE__ */ new Map();
    nodeWithLocals.locals.forEach((local) => {
      if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
        return;
      }
      if (local.declarations) {
        for (const declaration of local.declarations) {
          if (isValidUnusedLocalDeclaration(declaration)) {
            continue;
          }
          if (isImportedDeclaration(declaration)) {
            addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
          } else if (isBindingElement(declaration) && isObjectBindingPattern(declaration.parent)) {
            const lastElement = last(declaration.parent.elements);
            if (declaration === lastElement || !last(declaration.parent.elements).dotDotDotToken) {
              addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
            }
          } else if (isVariableDeclaration(declaration)) {
            const blockScopeKind = getCombinedNodeFlagsCached(declaration) & 7 /* BlockScoped */;
            const name = getNameOfDeclaration(declaration);
            if (blockScopeKind !== 4 /* Using */ && blockScopeKind !== 6 /* AwaitUsing */ || !name || !isIdentifierThatStartsWithUnderscore(name)) {
              addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
            }
          } else {
            const parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
            const name = local.valueDeclaration && getNameOfDeclaration(local.valueDeclaration);
            if (parameter && name) {
              if (!isParameterPropertyDeclaration(parameter, parameter.parent) && !parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
                if (isBindingElement(declaration) && isArrayBindingPattern(declaration.parent)) {
                  addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
                } else {
                  addDiagnostic(parameter, 1 /* Parameter */, createDiagnosticForNode(name, Diagnostics._0_is_declared_but_its_value_is_never_read, symbolName(local)));
                }
              }
            } else {
              errorUnusedLocal(declaration, symbolName(local), addDiagnostic);
            }
          }
        }
      }
    });
    unusedImports.forEach(([importClause, unuseds]) => {
      const importDecl = importClause.parent;
      const nDeclarations = (importClause.name ? 1 : 0) + (importClause.namedBindings ? importClause.namedBindings.kind === 274 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length : 0);
      if (nDeclarations === unuseds.length) {
        addDiagnostic(
          importDecl,
          0 /* Local */,
          unuseds.length === 1 ? createDiagnosticForNode(importDecl, Diagnostics._0_is_declared_but_its_value_is_never_read, idText(first(unuseds).name)) : createDiagnosticForNode(importDecl, Diagnostics.All_imports_in_import_declaration_are_unused)
        );
      } else {
        for (const unused of unuseds) errorUnusedLocal(unused, idText(unused.name), addDiagnostic);
      }
    });
    unusedDestructures.forEach(([bindingPattern, bindingElements]) => {
      const kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
      if (bindingPattern.elements.length === bindingElements.length) {
        if (bindingElements.length === 1 && bindingPattern.parent.kind === 260 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 261 /* VariableDeclarationList */) {
          addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
        } else {
          addDiagnostic(
            bindingPattern,
            kind,
            bindingElements.length === 1 ? createDiagnosticForNode(bindingPattern, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(bindingElements).name)) : createDiagnosticForNode(bindingPattern, Diagnostics.All_destructured_elements_are_unused)
          );
        }
      } else {
        for (const e of bindingElements) {
          addDiagnostic(e, kind, createDiagnosticForNode(e, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
        }
      }
    });
    unusedVariables.forEach(([declarationList, declarations]) => {
      if (declarationList.declarations.length === declarations.length) {
        addDiagnostic(
          declarationList,
          0 /* Local */,
          declarations.length === 1 ? createDiagnosticForNode(first(declarations).name, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(first(declarations).name)) : createDiagnosticForNode(declarationList.parent.kind === 243 /* VariableStatement */ ? declarationList.parent : declarationList, Diagnostics.All_variables_are_unused)
        );
      } else {
        for (const decl of declarations) {
          addDiagnostic(decl, 0 /* Local */, createDiagnosticForNode(decl, Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
        }
      }
    });
  }
  function checkPotentialUncheckedRenamedBindingElementsInTypes() {
    var _a;
    for (const node of potentialUnusedRenamedBindingElementsInTypes) {
      if (!((_a = getSymbolOfDeclaration(node)) == null ? void 0 : _a.isReferenced)) {
        const wrappingDeclaration = walkUpBindingElementsAndPatterns(node);
        Debug.assert(isPartOfParameterDeclaration(wrappingDeclaration), "Only parameter declaration should be checked here");
        const diagnostic = createDiagnosticForNode(node.name, Diagnostics._0_is_an_unused_renaming_of_1_Did_you_intend_to_use_it_as_a_type_annotation, declarationNameToString(node.name), declarationNameToString(node.propertyName));
        if (!wrappingDeclaration.type) {
          addRelatedInfo(
            diagnostic,
            createFileDiagnostic(getSourceFileOfNode(wrappingDeclaration), wrappingDeclaration.end, 0, Diagnostics.We_can_only_write_a_type_for_0_by_adding_a_type_for_the_entire_parameter_here, declarationNameToString(node.propertyName))
          );
        }
        diagnostics.add(diagnostic);
      }
    }
  }
  function bindingNameText(name) {
    switch (name.kind) {
      case 80 /* Identifier */:
        return idText(name);
      case 207 /* ArrayBindingPattern */:
      case 206 /* ObjectBindingPattern */:
        return bindingNameText(cast(first(name.elements), isBindingElement).name);
      default:
        return Debug.assertNever(name);
    }
  }
  function isImportedDeclaration(node) {
    return node.kind === 273 /* ImportClause */ || node.kind === 276 /* ImportSpecifier */ || node.kind === 274 /* NamespaceImport */;
  }
  function importClauseFromImported(decl) {
    return decl.kind === 273 /* ImportClause */ ? decl : decl.kind === 274 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
  }
  function checkBlock(node) {
    if (node.kind === 241 /* Block */) {
      checkGrammarStatementInAmbientContext(node);
    }
    if (isFunctionOrModuleBlock(node)) {
      const saveFlowAnalysisDisabled = flowAnalysisDisabled;
      forEach(node.statements, checkSourceElement);
      flowAnalysisDisabled = saveFlowAnalysisDisabled;
    } else {
      forEach(node.statements, checkSourceElement);
    }
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkCollisionWithArgumentsInGeneratedCode(node) {
    if (languageVersion >= 2 /* ES2015 */ || !hasRestParameter(node) || node.flags & 33554432 /* Ambient */ || nodeIsMissing(node.body)) {
      return;
    }
    forEach(node.parameters, (p) => {
      if (p.name && !isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
        errorSkippedOn("noEmit", p, Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
      }
    });
  }
  function needCollisionCheckForIdentifier(node, identifier, name) {
    if ((identifier == null ? void 0 : identifier.escapedText) !== name) {
      return false;
    }
    if (node.kind === 172 /* PropertyDeclaration */ || node.kind === 171 /* PropertySignature */ || node.kind === 174 /* MethodDeclaration */ || node.kind === 173 /* MethodSignature */ || node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */ || node.kind === 303 /* PropertyAssignment */) {
      return false;
    }
    if (node.flags & 33554432 /* Ambient */) {
      return false;
    }
    if (isImportClause(node) || isImportEqualsDeclaration(node) || isImportSpecifier(node)) {
      if (isTypeOnlyImportOrExportDeclaration(node)) {
        return false;
      }
    }
    const root = getRootDeclaration(node);
    if (isParameter(root) && nodeIsMissing(root.parent.body)) {
      return false;
    }
    return true;
  }
  function checkIfThisIsCapturedInEnclosingScope(node) {
    findAncestor(node, (current) => {
      if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
        const isDeclaration2 = node.kind !== 80 /* Identifier */;
        if (isDeclaration2) {
          error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
        } else {
          error(node, Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
        }
        return true;
      }
      return false;
    });
  }
  function checkIfNewTargetIsCapturedInEnclosingScope(node) {
    findAncestor(node, (current) => {
      if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
        const isDeclaration2 = node.kind !== 80 /* Identifier */;
        if (isDeclaration2) {
          error(getNameOfDeclaration(node), Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
        } else {
          error(node, Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
        }
        return true;
      }
      return false;
    });
  }
  function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
    if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) >= 5 /* ES2015 */) {
      return;
    }
    if (!name || !needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
      return;
    }
    if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */) {
      return;
    }
    const parent = getDeclarationContainer(node);
    if (parent.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(parent)) {
      errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, declarationNameToString(name), declarationNameToString(name));
    }
  }
  function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
    if (!name || languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
      return;
    }
    if (isModuleDeclaration(node) && getModuleInstanceState(node) !== 1 /* Instantiated */) {
      return;
    }
    const parent = getDeclarationContainer(node);
    if (parent.kind === 307 /* SourceFile */ && isExternalOrCommonJsModule(parent) && parent.flags & 4096 /* HasAsyncFunctions */) {
      errorSkippedOn("noEmit", name, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module_containing_async_functions, declarationNameToString(name), declarationNameToString(name));
    }
  }
  function recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name) {
    if (languageVersion <= 8 /* ES2021 */ && (needCollisionCheckForIdentifier(node, name, "WeakMap") || needCollisionCheckForIdentifier(node, name, "WeakSet"))) {
      potentialWeakMapSetCollisions.push(node);
    }
  }
  function checkWeakMapSetCollision(node) {
    const enclosingBlockScope = getEnclosingBlockScopeContainer(node);
    if (getNodeCheckFlags(enclosingBlockScope) & 1048576 /* ContainsClassWithPrivateIdentifiers */) {
      Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name) && typeof node.name.escapedText === "string", "The target of a WeakMap/WeakSet collision check should be an identifier");
      errorSkippedOn("noEmit", node, Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, node.name.escapedText);
    }
  }
  function recordPotentialCollisionWithReflectInGeneratedCode(node, name) {
    if (name && languageVersion >= 2 /* ES2015 */ && languageVersion <= 8 /* ES2021 */ && needCollisionCheckForIdentifier(node, name, "Reflect")) {
      potentialReflectCollisions.push(node);
    }
  }
  function checkReflectCollision(node) {
    let hasCollision = false;
    if (isClassExpression(node)) {
      for (const member of node.members) {
        if (getNodeCheckFlags(member) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) {
          hasCollision = true;
          break;
        }
      }
    } else if (isFunctionExpression(node)) {
      if (getNodeCheckFlags(node) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) {
        hasCollision = true;
      }
    } else {
      const container = getEnclosingBlockScopeContainer(node);
      if (container && getNodeCheckFlags(container) & 2097152 /* ContainsSuperPropertyInStaticInitializer */) {
        hasCollision = true;
      }
    }
    if (hasCollision) {
      Debug.assert(isNamedDeclaration(node) && isIdentifier(node.name), "The target of a Reflect collision check should be an identifier");
      errorSkippedOn("noEmit", node, Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_when_emitting_super_references_in_static_initializers, declarationNameToString(node.name), "Reflect");
    }
  }
  function checkCollisionsForDeclarationName(node, name) {
    if (!name) return;
    checkCollisionWithRequireExportsInGeneratedCode(node, name);
    checkCollisionWithGlobalPromiseInGeneratedCode(node, name);
    recordPotentialCollisionWithWeakMapSetInGeneratedCode(node, name);
    recordPotentialCollisionWithReflectInGeneratedCode(node, name);
    if (isClassLike(node)) {
      checkTypeNameIsReserved(name, Diagnostics.Class_name_cannot_be_0);
      if (!(node.flags & 33554432 /* Ambient */)) {
        checkClassNameCollisionWithObject(name);
      }
    } else if (isEnumDeclaration(node)) {
      checkTypeNameIsReserved(name, Diagnostics.Enum_name_cannot_be_0);
    }
  }
  function checkVarDeclaredNamesNotShadowed(node) {
    if ((getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */) !== 0 || isPartOfParameterDeclaration(node)) {
      return;
    }
    const symbol = getSymbolOfDeclaration(node);
    if (symbol.flags & 1 /* FunctionScopedVariable */) {
      if (!isIdentifier(node.name)) return Debug.fail();
      const localDeclarationSymbol = resolveName(
        node,
        node.name.escapedText,
        3 /* Variable */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        false
      );
      if (localDeclarationSymbol && localDeclarationSymbol !== symbol && localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
        if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 7 /* BlockScoped */) {
          const varDeclList = getAncestor(localDeclarationSymbol.valueDeclaration, 261 /* VariableDeclarationList */);
          const container = varDeclList.parent.kind === 243 /* VariableStatement */ && varDeclList.parent.parent ? varDeclList.parent.parent : void 0;
          const namesShareScope = container && (container.kind === 241 /* Block */ && isFunctionLike(container.parent) || container.kind === 268 /* ModuleBlock */ || container.kind === 267 /* ModuleDeclaration */ || container.kind === 307 /* SourceFile */);
          if (!namesShareScope) {
            const name = symbolToString(localDeclarationSymbol);
            error(node, Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
          }
        }
      }
    }
  }
  function convertAutoToAny(type) {
    return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
  }
  function checkVariableLikeDeclaration(node) {
    var _a;
    checkDecorators(node);
    if (!isBindingElement(node)) {
      checkSourceElement(node.type);
    }
    if (!node.name) {
      return;
    }
    if (node.name.kind === 167 /* ComputedPropertyName */) {
      checkComputedPropertyName(node.name);
      if (hasOnlyExpressionInitializer(node) && node.initializer) {
        checkExpressionCached(node.initializer);
      }
    }
    if (isBindingElement(node)) {
      if (node.propertyName && isIdentifier(node.name) && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) {
        potentialUnusedRenamedBindingElementsInTypes.push(node);
        return;
      }
      if (isObjectBindingPattern(node.parent) && node.dotDotDotToken && languageVersion < LanguageFeatureMinimumTarget.ObjectSpreadRest) {
        checkExternalEmitHelpers(node, 4 /* Rest */);
      }
      if (node.propertyName && node.propertyName.kind === 167 /* ComputedPropertyName */) {
        checkComputedPropertyName(node.propertyName);
      }
      const parent = node.parent.parent;
      const parentCheckMode = node.dotDotDotToken ? 32 /* RestBindingElement */ : 0 /* Normal */;
      const parentType = getTypeForBindingElementParent(parent, parentCheckMode);
      const name = node.propertyName || node.name;
      if (parentType && !isBindingPattern(name)) {
        const exprType = getLiteralTypeFromPropertyName(name);
        if (isTypeUsableAsPropertyName(exprType)) {
          const nameText = getPropertyNameFromType(exprType);
          const property = getPropertyOfType(parentType, nameText);
          if (property) {
            markPropertyAsReferenced(
              property,
              /*nodeForCheckWriteOnly*/
              void 0,
              /*isSelfTypeAccess*/
              false
            );
            checkPropertyAccessibility(
              node,
              !!parent.initializer && parent.initializer.kind === 108 /* SuperKeyword */,
              /*writing*/
              false,
              parentType,
              property
            );
          }
        }
      }
    }
    if (isBindingPattern(node.name)) {
      if (node.name.kind === 207 /* ArrayBindingPattern */ && languageVersion < LanguageFeatureMinimumTarget.BindingPatterns && compilerOptions.downlevelIteration) {
        checkExternalEmitHelpers(node, 512 /* Read */);
      }
      forEach(node.name.elements, checkSourceElement);
    }
    if (node.initializer && isPartOfParameterDeclaration(node) && nodeIsMissing(getContainingFunction(node).body)) {
      error(node, Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
      return;
    }
    if (isBindingPattern(node.name)) {
      if (isInAmbientOrTypeNode(node)) {
        return;
      }
      const needCheckInitializer = hasOnlyExpressionInitializer(node) && node.initializer && node.parent.parent.kind !== 249 /* ForInStatement */;
      const needCheckWidenedType = !some(node.name.elements, not(isOmittedExpression));
      if (needCheckInitializer || needCheckWidenedType) {
        const widenedType = getWidenedTypeForVariableLikeDeclaration(node);
        if (needCheckInitializer) {
          const initializerType = checkExpressionCached(node.initializer);
          if (strictNullChecks && needCheckWidenedType) {
            checkNonNullNonVoidType(initializerType, node);
          } else {
            checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
          }
        }
        if (needCheckWidenedType) {
          if (isArrayBindingPattern(node.name)) {
            checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
          } else if (strictNullChecks) {
            checkNonNullNonVoidType(widenedType, node);
          }
        }
      }
      return;
    }
    const symbol = getSymbolOfDeclaration(node);
    if (symbol.flags & 2097152 /* Alias */ && (isVariableDeclarationInitializedToBareOrAccessedRequire(node) || isBindingElementOfBareOrAccessedRequire(node))) {
      checkAliasSymbol(node);
      return;
    }
    if (node.name.kind === 10 /* BigIntLiteral */) {
      error(node.name, Diagnostics.A_bigint_literal_cannot_be_used_as_a_property_name);
    }
    const type = convertAutoToAny(getTypeOfSymbol(symbol));
    if (node === symbol.valueDeclaration) {
      const initializer = hasOnlyExpressionInitializer(node) && getEffectiveInitializer(node);
      if (initializer) {
        const isJSObjectLiteralInitializer = isInJSFile(node) && isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAccess(node.name)) && !!((_a = symbol.exports) == null ? void 0 : _a.size);
        if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 249 /* ForInStatement */) {
          const initializerType = checkExpressionCached(initializer);
          checkTypeAssignableToAndOptionallyElaborate(
            initializerType,
            type,
            node,
            initializer,
            /*headMessage*/
            void 0
          );
          const blockScopeKind = getCombinedNodeFlagsCached(node) & 7 /* BlockScoped */;
          if (blockScopeKind === 6 /* AwaitUsing */) {
            const globalAsyncDisposableType = getGlobalAsyncDisposableType(
              /*reportErrors*/
              true
            );
            const globalDisposableType = getGlobalDisposableType(
              /*reportErrors*/
              true
            );
            if (globalAsyncDisposableType !== emptyObjectType && globalDisposableType !== emptyObjectType) {
              const optionalDisposableType = getUnionType([globalAsyncDisposableType, globalDisposableType, nullType, undefinedType]);
              checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_an_await_using_declaration_must_be_either_an_object_with_a_Symbol_asyncDispose_or_Symbol_dispose_method_or_be_null_or_undefined);
            }
          } else if (blockScopeKind === 4 /* Using */) {
            const globalDisposableType = getGlobalDisposableType(
              /*reportErrors*/
              true
            );
            if (globalDisposableType !== emptyObjectType) {
              const optionalDisposableType = getUnionType([globalDisposableType, nullType, undefinedType]);
              checkTypeAssignableTo(widenTypeForVariableLikeDeclaration(initializerType, node), optionalDisposableType, initializer, Diagnostics.The_initializer_of_a_using_declaration_must_be_either_an_object_with_a_Symbol_dispose_method_or_be_null_or_undefined);
            }
          }
        }
      }
      if (symbol.declarations && symbol.declarations.length > 1) {
        if (some(symbol.declarations, (d) => d !== node && isVariableLike(d) && !areDeclarationFlagsIdentical(d, node))) {
          error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name));
        }
      }
    } else {
      const declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
      if (!isErrorType(type) && !isErrorType(declarationType) && !isTypeIdenticalTo(type, declarationType) && !(symbol.flags & 67108864 /* Assignment */)) {
        errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
      }
      if (hasOnlyExpressionInitializer(node) && node.initializer) {
        checkTypeAssignableToAndOptionallyElaborate(
          checkExpressionCached(node.initializer),
          declarationType,
          node,
          node.initializer,
          /*headMessage*/
          void 0
        );
      }
      if (symbol.valueDeclaration && !areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
        error(node.name, Diagnostics.All_declarations_of_0_must_have_identical_modifiers, declarationNameToString(node.name));
      }
    }
    if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */) {
      checkExportsOnMergedDeclarations(node);
      if (node.kind === 260 /* VariableDeclaration */ || node.kind === 208 /* BindingElement */) {
        checkVarDeclaredNamesNotShadowed(node);
      }
      checkCollisionsForDeclarationName(node, node.name);
    }
  }
  function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
    const nextDeclarationName = getNameOfDeclaration(nextDeclaration);
    const message = nextDeclaration.kind === 172 /* PropertyDeclaration */ || nextDeclaration.kind === 171 /* PropertySignature */ ? Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2 : Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
    const declName = declarationNameToString(nextDeclarationName);
    const err = error(
      nextDeclarationName,
      message,
      declName,
      typeToString(firstType),
      typeToString(nextType)
    );
    if (firstDeclaration) {
      addRelatedInfo(err, createDiagnosticForNode(firstDeclaration, Diagnostics._0_was_also_declared_here, declName));
    }
  }
  function areDeclarationFlagsIdentical(left, right) {
    if (left.kind === 169 /* Parameter */ && right.kind === 260 /* VariableDeclaration */ || left.kind === 260 /* VariableDeclaration */ && right.kind === 169 /* Parameter */) {
      return true;
    }
    if (hasQuestionToken(left) !== hasQuestionToken(right)) {
      return false;
    }
    const interestingFlags = 2 /* Private */ | 4 /* Protected */ | 1024 /* Async */ | 64 /* Abstract */ | 8 /* Readonly */ | 256 /* Static */;
    return getSelectedEffectiveModifierFlags(left, interestingFlags) === getSelectedEffectiveModifierFlags(right, interestingFlags);
  }
  function checkVariableDeclaration(node) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    checkGrammarVariableDeclaration(node);
    checkVariableLikeDeclaration(node);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  function checkBindingElement(node) {
    checkGrammarBindingElement(node);
    return checkVariableLikeDeclaration(node);
  }
  function checkVariableDeclarationList(node) {
    const blockScopeKind = getCombinedNodeFlags(node) & 7 /* BlockScoped */;
    if ((blockScopeKind === 4 /* Using */ || blockScopeKind === 6 /* AwaitUsing */) && languageVersion < LanguageFeatureMinimumTarget.UsingAndAwaitUsing) {
      checkExternalEmitHelpers(node, 16777216 /* AddDisposableResourceAndDisposeResources */);
    }
    forEach(node.declarations, checkSourceElement);
  }
  function checkVariableStatement(node) {
    if (!checkGrammarModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList)) checkGrammarForDisallowedBlockScopedVariableStatement(node);
    checkVariableDeclarationList(node.declarationList);
  }
  function checkExpressionStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkExpression(node.expression);
  }
  function checkIfStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    const type = checkTruthinessExpression(node.expression);
    checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(node.expression, type, node.thenStatement);
    checkSourceElement(node.thenStatement);
    if (node.thenStatement.kind === 242 /* EmptyStatement */) {
      error(node.thenStatement, Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
    }
    checkSourceElement(node.elseStatement);
  }
  function checkTestingKnownTruthyCallableOrAwaitableOrEnumMemberType(condExpr, condType, body) {
    if (!strictNullChecks) return;
    bothHelper(condExpr, body);
    function bothHelper(condExpr2, body2) {
      condExpr2 = skipParentheses(condExpr2);
      helper(condExpr2, body2);
      while (isBinaryExpression(condExpr2) && (condExpr2.operatorToken.kind === 57 /* BarBarToken */ || condExpr2.operatorToken.kind === 61 /* QuestionQuestionToken */)) {
        condExpr2 = skipParentheses(condExpr2.left);
        helper(condExpr2, body2);
      }
    }
    function helper(condExpr2, body2) {
      const location = isLogicalOrCoalescingBinaryExpression(condExpr2) ? skipParentheses(condExpr2.right) : condExpr2;
      if (isModuleExportsAccessExpression(location)) {
        return;
      }
      if (isLogicalOrCoalescingBinaryExpression(location)) {
        bothHelper(location, body2);
        return;
      }
      const type = location === condExpr2 ? condType : checkExpression(location);
      if (type.flags & 1024 /* EnumLiteral */ && isPropertyAccessExpression(location) && (getNodeLinks(location.expression).resolvedSymbol ?? unknownSymbol).flags & 384 /* Enum */) {
        error(location, Diagnostics.This_condition_will_always_return_0, !!type.value ? "true" : "false");
        return;
      }
      const isPropertyExpressionCast = isPropertyAccessExpression(location) && isTypeAssertion(location.expression);
      if (!hasTypeFacts(type, 4194304 /* Truthy */) || isPropertyExpressionCast) return;
      const callSignatures = getSignaturesOfType(type, 0 /* Call */);
      const isPromise = !!getAwaitedTypeOfPromise(type);
      if (callSignatures.length === 0 && !isPromise) {
        return;
      }
      const testedNode = isIdentifier(location) ? location : isPropertyAccessExpression(location) ? location.name : void 0;
      const testedSymbol = testedNode && getSymbolAtLocation(testedNode);
      if (!testedSymbol && !isPromise) {
        return;
      }
      const isUsed = testedSymbol && isBinaryExpression(condExpr2.parent) && isSymbolUsedInBinaryExpressionChain(condExpr2.parent, testedSymbol) || testedSymbol && body2 && isSymbolUsedInConditionBody(condExpr2, body2, testedNode, testedSymbol);
      if (!isUsed) {
        if (isPromise) {
          errorAndMaybeSuggestAwait(
            location,
            /*maybeMissingAwait*/
            true,
            Diagnostics.This_condition_will_always_return_true_since_this_0_is_always_defined,
            getTypeNameForErrorDisplay(type)
          );
        } else {
          error(location, Diagnostics.This_condition_will_always_return_true_since_this_function_is_always_defined_Did_you_mean_to_call_it_instead);
        }
      }
    }
  }
  function isSymbolUsedInConditionBody(expr, body, testedNode, testedSymbol) {
    return !!forEachChild(body, function check(childNode) {
      if (isIdentifier(childNode)) {
        const childSymbol = getSymbolAtLocation(childNode);
        if (childSymbol && childSymbol === testedSymbol) {
          if (isIdentifier(expr) || isIdentifier(testedNode) && isBinaryExpression(testedNode.parent)) {
            return true;
          }
          let testedExpression = testedNode.parent;
          let childExpression = childNode.parent;
          while (testedExpression && childExpression) {
            if (isIdentifier(testedExpression) && isIdentifier(childExpression) || testedExpression.kind === 110 /* ThisKeyword */ && childExpression.kind === 110 /* ThisKeyword */) {
              return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
            } else if (isPropertyAccessExpression(testedExpression) && isPropertyAccessExpression(childExpression)) {
              if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
                return false;
              }
              childExpression = childExpression.expression;
              testedExpression = testedExpression.expression;
            } else if (isCallExpression(testedExpression) && isCallExpression(childExpression)) {
              childExpression = childExpression.expression;
              testedExpression = testedExpression.expression;
            } else {
              return false;
            }
          }
        }
      }
      return forEachChild(childNode, check);
    });
  }
  function isSymbolUsedInBinaryExpressionChain(node, testedSymbol) {
    while (isBinaryExpression(node) && node.operatorToken.kind === 56 /* AmpersandAmpersandToken */) {
      const isUsed = forEachChild(node.right, function visit(child) {
        if (isIdentifier(child)) {
          const symbol = getSymbolAtLocation(child);
          if (symbol && symbol === testedSymbol) {
            return true;
          }
        }
        return forEachChild(child, visit);
      });
      if (isUsed) {
        return true;
      }
      node = node.parent;
    }
    return false;
  }
  function checkDoStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkSourceElement(node.statement);
    checkTruthinessExpression(node.expression);
  }
  function checkWhileStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkTruthinessExpression(node.expression);
    checkSourceElement(node.statement);
  }
  function checkTruthinessOfType(type, node) {
    if (type.flags & 16384 /* Void */) {
      error(node, Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
    } else {
      const semantics = getSyntacticTruthySemantics(node);
      if (semantics !== 3 /* Sometimes */) {
        error(
          node,
          semantics === 1 /* Always */ ? Diagnostics.This_kind_of_expression_is_always_truthy : Diagnostics.This_kind_of_expression_is_always_falsy
        );
      }
    }
    return type;
  }
  function getSyntacticTruthySemantics(node) {
    node = skipOuterExpressions(node);
    switch (node.kind) {
      case 9 /* NumericLiteral */:
        if (node.text === "0" || node.text === "1") {
          return 3 /* Sometimes */;
        }
        return 1 /* Always */;
      case 209 /* ArrayLiteralExpression */:
      case 219 /* ArrowFunction */:
      case 10 /* BigIntLiteral */:
      case 231 /* ClassExpression */:
      case 218 /* FunctionExpression */:
      case 284 /* JsxElement */:
      case 285 /* JsxSelfClosingElement */:
      case 210 /* ObjectLiteralExpression */:
      case 14 /* RegularExpressionLiteral */:
        return 1 /* Always */;
      case 222 /* VoidExpression */:
      case 106 /* NullKeyword */:
        return 2 /* Never */;
      case 15 /* NoSubstitutionTemplateLiteral */:
      case 11 /* StringLiteral */:
        return !!node.text ? 1 /* Always */ : 2 /* Never */;
      case 227 /* ConditionalExpression */:
        return getSyntacticTruthySemantics(node.whenTrue) | getSyntacticTruthySemantics(node.whenFalse);
      case 80 /* Identifier */:
        if (getResolvedSymbol(node) === undefinedSymbol) {
          return 2 /* Never */;
        }
        return 3 /* Sometimes */;
    }
    return 3 /* Sometimes */;
  }
  function checkTruthinessExpression(node, checkMode) {
    return checkTruthinessOfType(checkExpression(node, checkMode), node);
  }
  function checkForStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (node.initializer && node.initializer.kind === 261 /* VariableDeclarationList */) {
        checkGrammarVariableDeclarationList(node.initializer);
      }
    }
    if (node.initializer) {
      if (node.initializer.kind === 261 /* VariableDeclarationList */) {
        checkVariableDeclarationList(node.initializer);
      } else {
        checkExpression(node.initializer);
      }
    }
    if (node.condition) checkTruthinessExpression(node.condition);
    if (node.incrementor) checkExpression(node.incrementor);
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkForOfStatement(node) {
    checkGrammarForInOrForOfStatement(node);
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (node.awaitModifier) {
      if (container && isClassStaticBlockDeclaration(container)) {
        grammarErrorOnNode(node.awaitModifier, Diagnostics.for_await_loops_cannot_be_used_inside_a_class_static_block);
      } else {
        const functionFlags = getFunctionFlags(container);
        if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < LanguageFeatureMinimumTarget.ForAwaitOf) {
          checkExternalEmitHelpers(node, 16384 /* ForAwaitOfIncludes */);
        }
      }
    } else if (compilerOptions.downlevelIteration && languageVersion < LanguageFeatureMinimumTarget.ForOf) {
      checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
    }
    if (node.initializer.kind === 261 /* VariableDeclarationList */) {
      checkVariableDeclarationList(node.initializer);
    } else {
      const varExpr = node.initializer;
      const iteratedType = checkRightHandSideOfForOf(node);
      if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */) {
        checkDestructuringAssignment(varExpr, iteratedType || errorType);
      } else {
        const leftType = checkExpression(varExpr);
        checkReferenceExpression(
          varExpr,
          Diagnostics.The_left_hand_side_of_a_for_of_statement_must_be_a_variable_or_a_property_access,
          Diagnostics.The_left_hand_side_of_a_for_of_statement_may_not_be_an_optional_property_access
        );
        if (iteratedType) {
          checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
        }
      }
    }
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkForInStatement(node) {
    checkGrammarForInOrForOfStatement(node);
    const rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
    if (node.initializer.kind === 261 /* VariableDeclarationList */) {
      const variable = node.initializer.declarations[0];
      if (variable && isBindingPattern(variable.name)) {
        error(variable.name, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
      }
      checkVariableDeclarationList(node.initializer);
    } else {
      const varExpr = node.initializer;
      const leftType = checkExpression(varExpr);
      if (varExpr.kind === 209 /* ArrayLiteralExpression */ || varExpr.kind === 210 /* ObjectLiteralExpression */) {
        error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
      } else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
        error(varExpr, Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
      } else {
        checkReferenceExpression(
          varExpr,
          Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_a_variable_or_a_property_access,
          Diagnostics.The_left_hand_side_of_a_for_in_statement_may_not_be_an_optional_property_access
        );
      }
    }
    if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
      error(node.expression, Diagnostics.The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_but_here_has_type_0, typeToString(rightType));
    }
    checkSourceElement(node.statement);
    if (node.locals) {
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function checkRightHandSideOfForOf(statement) {
    const use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
    return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
  }
  function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
    if (isTypeAny(inputType)) {
      return inputType;
    }
    return getIteratedTypeOrElementType(
      use,
      inputType,
      sentType,
      errorNode,
      /*checkAssignability*/
      true
    ) || anyType;
  }
  function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
    const allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
    if (inputType === neverType) {
      if (errorNode) {
        reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables);
      }
      return void 0;
    }
    const uplevelIteration = languageVersion >= 2 /* ES2015 */;
    const downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
    const possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */);
    if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
      const iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : void 0);
      if (checkAssignability) {
        if (iterationTypes) {
          const diagnostic = use & 8 /* ForOfFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_for_of_will_always_send_0 : use & 32 /* SpreadFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_spread_will_always_send_0 : use & 64 /* DestructuringFlag */ ? Diagnostics.Cannot_iterate_value_because_the_next_method_of_its_iterator_expects_type_1_but_array_destructuring_will_always_send_0 : use & 16 /* YieldStarFlag */ ? Diagnostics.Cannot_delegate_iteration_to_value_because_the_next_method_of_its_iterator_expects_type_1_but_the_containing_generator_will_always_send_0 : void 0;
          if (diagnostic) {
            checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
          }
        }
      }
      if (iterationTypes || uplevelIteration) {
        return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : iterationTypes && iterationTypes.yieldType;
      }
    }
    let arrayType = inputType;
    let hasStringConstituent = false;
    if (use & 4 /* AllowsStringInputFlag */) {
      if (arrayType.flags & 1048576 /* Union */) {
        const arrayTypes = inputType.types;
        const filteredTypes = filter(arrayTypes, (t) => !(t.flags & 402653316 /* StringLike */));
        if (filteredTypes !== arrayTypes) {
          arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
        }
      } else if (arrayType.flags & 402653316 /* StringLike */) {
        arrayType = neverType;
      }
      hasStringConstituent = arrayType !== inputType;
      if (hasStringConstituent) {
        if (arrayType.flags & 131072 /* Never */) {
          return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType;
        }
      }
    }
    if (!isArrayLikeType(arrayType)) {
      if (errorNode) {
        const allowsStrings = !!(use & 4 /* AllowsStringInputFlag */) && !hasStringConstituent;
        const [defaultDiagnostic, maybeMissingAwait] = getIterationDiagnosticDetails(allowsStrings, downlevelIteration);
        errorAndMaybeSuggestAwait(
          errorNode,
          maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType),
          defaultDiagnostic,
          typeToString(arrayType)
        );
      }
      return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : void 0;
    }
    const arrayElementType = getIndexTypeOfType(arrayType, numberType);
    if (hasStringConstituent && arrayElementType) {
      if (arrayElementType.flags & 402653316 /* StringLike */ && !compilerOptions.noUncheckedIndexedAccess) {
        return stringType;
      }
      return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */);
    }
    return use & 128 /* PossiblyOutOfBounds */ ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType;
    function getIterationDiagnosticDetails(allowsStrings, downlevelIteration2) {
      var _a;
      if (downlevelIteration2) {
        return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true] : [Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true];
      }
      const yieldType = getIterationTypeOfIterable(
        use,
        0 /* Yield */,
        inputType,
        /*errorNode*/
        void 0
      );
      if (yieldType) {
        return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, false];
      }
      if (isES2015OrLaterIterable((_a = inputType.symbol) == null ? void 0 : _a.escapedName)) {
        return [Diagnostics.Type_0_can_only_be_iterated_through_when_using_the_downlevelIteration_flag_or_with_a_target_of_es2015_or_higher, true];
      }
      return allowsStrings ? [Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true] : [Diagnostics.Type_0_is_not_an_array_type, true];
    }
  }
  function isES2015OrLaterIterable(n) {
    switch (n) {
      case "Float32Array":
      case "Float64Array":
      case "Int16Array":
      case "Int32Array":
      case "Int8Array":
      case "NodeList":
      case "Uint16Array":
      case "Uint32Array":
      case "Uint8Array":
      case "Uint8ClampedArray":
        return true;
    }
    return false;
  }
  function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
    if (isTypeAny(inputType)) {
      return void 0;
    }
    const iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
    return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
  }
  function createIterationTypes(yieldType = neverType, returnType = neverType, nextType = unknownType) {
    if (yieldType.flags & 67359327 /* Intrinsic */ && returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) && nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
      const id = getTypeListId([yieldType, returnType, nextType]);
      let iterationTypes = iterationTypesCache.get(id);
      if (!iterationTypes) {
        iterationTypes = { yieldType, returnType, nextType };
        iterationTypesCache.set(id, iterationTypes);
      }
      return iterationTypes;
    }
    return { yieldType, returnType, nextType };
  }
  function combineIterationTypes(array) {
    let yieldTypes;
    let returnTypes;
    let nextTypes;
    for (const iterationTypes of array) {
      if (iterationTypes === void 0 || iterationTypes === noIterationTypes) {
        continue;
      }
      if (iterationTypes === anyIterationTypes) {
        return anyIterationTypes;
      }
      yieldTypes = append(yieldTypes, iterationTypes.yieldType);
      returnTypes = append(returnTypes, iterationTypes.returnType);
      nextTypes = append(nextTypes, iterationTypes.nextType);
    }
    if (yieldTypes || returnTypes || nextTypes) {
      return createIterationTypes(
        yieldTypes && getUnionType(yieldTypes),
        returnTypes && getUnionType(returnTypes),
        nextTypes && getIntersectionType(nextTypes)
      );
    }
    return noIterationTypes;
  }
  function getCachedIterationTypes(type, cacheKey) {
    return type[cacheKey];
  }
  function setCachedIterationTypes(type, cacheKey, cachedTypes2) {
    return type[cacheKey] = cachedTypes2;
  }
  function getIterationTypesOfIterable(type, use, errorNode) {
    var _a, _b;
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    if (!(type.flags & 1048576 /* Union */)) {
      const errorOutputContainer = errorNode ? { errors: void 0, skipLogging: true } : void 0;
      const iterationTypes2 = getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer);
      if (iterationTypes2 === noIterationTypes) {
        if (errorNode) {
          const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
          if (errorOutputContainer == null ? void 0 : errorOutputContainer.errors) {
            addRelatedInfo(rootDiag, ...errorOutputContainer.errors);
          }
        }
        return void 0;
      } else if ((_a = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _a.length) {
        for (const diag2 of errorOutputContainer.errors) {
          diagnostics.add(diag2);
        }
      }
      return iterationTypes2;
    }
    const cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
    const cachedTypes2 = getCachedIterationTypes(type, cacheKey);
    if (cachedTypes2) return cachedTypes2 === noIterationTypes ? void 0 : cachedTypes2;
    let allIterationTypes;
    for (const constituent of type.types) {
      const errorOutputContainer = errorNode ? { errors: void 0 } : void 0;
      const iterationTypes2 = getIterationTypesOfIterableWorker(constituent, use, errorNode, errorOutputContainer);
      if (iterationTypes2 === noIterationTypes) {
        if (errorNode) {
          const rootDiag = reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
          if (errorOutputContainer == null ? void 0 : errorOutputContainer.errors) {
            addRelatedInfo(rootDiag, ...errorOutputContainer.errors);
          }
        }
        setCachedIterationTypes(type, cacheKey, noIterationTypes);
        return void 0;
      } else if ((_b = errorOutputContainer == null ? void 0 : errorOutputContainer.errors) == null ? void 0 : _b.length) {
        for (const diag2 of errorOutputContainer.errors) {
          diagnostics.add(diag2);
        }
      }
      allIterationTypes = append(allIterationTypes, iterationTypes2);
    }
    const iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
    setCachedIterationTypes(type, cacheKey, iterationTypes);
    return iterationTypes === noIterationTypes ? void 0 : iterationTypes;
  }
  function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
    if (iterationTypes === noIterationTypes) return noIterationTypes;
    if (iterationTypes === anyIterationTypes) return anyIterationTypes;
    const { yieldType, returnType, nextType } = iterationTypes;
    if (errorNode) {
      getGlobalAwaitedSymbol(
        /*reportErrors*/
        true
      );
    }
    return createIterationTypes(
      getAwaitedType(yieldType, errorNode) || anyType,
      getAwaitedType(returnType, errorNode) || anyType,
      nextType
    );
  }
  function getIterationTypesOfIterableWorker(type, use, errorNode, errorOutputContainer) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    let noCache = false;
    if (use & 2 /* AllowsAsyncIterablesFlag */) {
      const iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) || getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
      if (iterationTypes) {
        if (iterationTypes === noIterationTypes && errorNode) {
          noCache = true;
        } else {
          return use & 8 /* ForOfFlag */ ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode) : iterationTypes;
        }
      }
    }
    if (use & 1 /* AllowsSyncIterablesFlag */) {
      let iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) || getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
      if (iterationTypes) {
        if (iterationTypes === noIterationTypes && errorNode) {
          noCache = true;
        } else {
          if (use & 2 /* AllowsAsyncIterablesFlag */) {
            if (iterationTypes !== noIterationTypes) {
              iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode);
              return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes);
            }
          } else {
            return iterationTypes;
          }
        }
      }
    }
    if (use & 2 /* AllowsAsyncIterablesFlag */) {
      const iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode, errorOutputContainer, noCache);
      if (iterationTypes !== noIterationTypes) {
        return iterationTypes;
      }
    }
    if (use & 1 /* AllowsSyncIterablesFlag */) {
      let iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode, errorOutputContainer, noCache);
      if (iterationTypes !== noIterationTypes) {
        if (use & 2 /* AllowsAsyncIterablesFlag */) {
          iterationTypes = getAsyncFromSyncIterationTypes(iterationTypes, errorNode);
          return noCache ? iterationTypes : setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes);
        } else {
          return iterationTypes;
        }
      }
    }
    return noIterationTypes;
  }
  function getIterationTypesOfIterableCached(type, resolver) {
    return getCachedIterationTypes(type, resolver.iterableCacheKey);
  }
  function getIterationTypesOfIterableFast(type, resolver) {
    if (isReferenceToType(type, resolver.getGlobalIterableType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIterableIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    ))) {
      const [yieldType, returnType, nextType] = getTypeArguments(type);
      return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(
        yieldType,
        /*errorNode*/
        void 0
      ) || yieldType, resolver.resolveIterationType(
        returnType,
        /*errorNode*/
        void 0
      ) || returnType, nextType));
    }
    if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) {
      const [yieldType] = getTypeArguments(type);
      const returnType = getBuiltinIteratorReturnType();
      const nextType = unknownType;
      return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(resolver.resolveIterationType(
        yieldType,
        /*errorNode*/
        void 0
      ) || yieldType, resolver.resolveIterationType(
        returnType,
        /*errorNode*/
        void 0
      ) || returnType, nextType));
    }
  }
  function getPropertyNameForKnownSymbolName(symbolName2) {
    const ctorType = getGlobalESSymbolConstructorSymbol(
      /*reportErrors*/
      false
    );
    const uniqueType = ctorType && getTypeOfPropertyOfType(getTypeOfSymbol(ctorType), escapeLeadingUnderscores(symbolName2));
    return uniqueType && isTypeUsableAsPropertyName(uniqueType) ? getPropertyNameFromType(uniqueType) : `__@${symbolName2}`;
  }
  function getIterationTypesOfIterableSlow(type, resolver, errorNode, errorOutputContainer, noCache) {
    const method = getPropertyOfType(type, getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
    const methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : void 0;
    if (isTypeAny(methodType)) {
      return noCache ? anyIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
    }
    const allSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : void 0;
    const validSignatures = filter(allSignatures, (sig) => getMinArgumentCount(sig) === 0);
    if (!some(validSignatures)) {
      if (errorNode && some(allSignatures)) {
        checkTypeAssignableTo(
          type,
          resolver.getGlobalIterableType(
            /*reportErrors*/
            true
          ),
          errorNode,
          /*headMessage*/
          void 0,
          /*containingMessageChain*/
          void 0,
          errorOutputContainer
        );
      }
      return noCache ? noIterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
    }
    const iteratorType = getIntersectionType(map(validSignatures, getReturnTypeOfSignature));
    const iterationTypes = getIterationTypesOfIteratorWorker(iteratorType, resolver, errorNode, errorOutputContainer, noCache) ?? noIterationTypes;
    return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
  }
  function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
    const message = allowAsyncIterables ? Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator : Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
    const suggestAwait = (
      // for (const x of Promise<...>) or [...Promise<...>]
      !!getAwaitedTypeOfPromise(type) || !allowAsyncIterables && isForOfStatement(errorNode.parent) && errorNode.parent.expression === errorNode && getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      ) !== emptyGenericType && isTypeAssignableTo(type, createTypeFromGenericGlobalType(getGlobalAsyncIterableType(
        /*reportErrors*/
        false
      ), [anyType, anyType, anyType]))
    );
    return errorAndMaybeSuggestAwait(errorNode, suggestAwait, message, typeToString(type));
  }
  function getIterationTypesOfIterator(type, resolver, errorNode, errorOutputContainer) {
    return getIterationTypesOfIteratorWorker(
      type,
      resolver,
      errorNode,
      errorOutputContainer,
      /*noCache*/
      false
    );
  }
  function getIterationTypesOfIteratorWorker(type, resolver, errorNode, errorOutputContainer, noCache) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    let iterationTypes = getIterationTypesOfIteratorCached(type, resolver) || getIterationTypesOfIteratorFast(type, resolver);
    if (iterationTypes === noIterationTypes && errorNode) {
      iterationTypes = void 0;
      noCache = true;
    }
    iterationTypes ?? (iterationTypes = getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache));
    return iterationTypes === noIterationTypes ? void 0 : iterationTypes;
  }
  function getIterationTypesOfIteratorCached(type, resolver) {
    return getCachedIterationTypes(type, resolver.iteratorCacheKey);
  }
  function getIterationTypesOfIteratorFast(type, resolver) {
    if (isReferenceToType(type, resolver.getGlobalIterableIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalIteratorObjectType(
      /*reportErrors*/
      false
    )) || isReferenceToType(type, resolver.getGlobalGeneratorType(
      /*reportErrors*/
      false
    ))) {
      const [yieldType, returnType, nextType] = getTypeArguments(type);
      return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
    }
    if (isReferenceToSomeType(type, resolver.getGlobalBuiltinIteratorTypes())) {
      const [yieldType] = getTypeArguments(type);
      const returnType = getBuiltinIteratorReturnType();
      const nextType = unknownType;
      return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
    }
  }
  function isIteratorResult(type, kind) {
    const doneType = getTypeOfPropertyOfType(type, "done") || falseType;
    return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
  }
  function isYieldIteratorResult(type) {
    return isIteratorResult(type, 0 /* Yield */);
  }
  function isReturnIteratorResult(type) {
    return isIteratorResult(type, 1 /* Return */);
  }
  function getIterationTypesOfIteratorResult(type) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    const cachedTypes2 = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
    if (cachedTypes2) {
      return cachedTypes2;
    }
    if (isReferenceToType(type, getGlobalIteratorYieldResultType(
      /*reportErrors*/
      false
    ))) {
      const yieldType2 = getTypeArguments(type)[0];
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
        yieldType2,
        /*returnType*/
        void 0,
        /*nextType*/
        void 0
      ));
    }
    if (isReferenceToType(type, getGlobalIteratorReturnResultType(
      /*reportErrors*/
      false
    ))) {
      const returnType2 = getTypeArguments(type)[0];
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
        /*yieldType*/
        void 0,
        returnType2,
        /*nextType*/
        void 0
      ));
    }
    const yieldIteratorResult = filterType(type, isYieldIteratorResult);
    const yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : void 0;
    const returnIteratorResult = filterType(type, isReturnIteratorResult);
    const returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : void 0;
    if (!yieldType && !returnType) {
      return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
    }
    return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(
      yieldType,
      returnType || voidType,
      /*nextType*/
      void 0
    ));
  }
  function getIterationTypesOfMethod(type, resolver, methodName, errorNode, errorOutputContainer) {
    var _a, _b, _c, _d;
    const method = getPropertyOfType(type, methodName);
    if (!method && methodName !== "next") {
      return void 0;
    }
    const methodType = method && !(methodName === "next" && method.flags & 16777216 /* Optional */) ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */) : void 0;
    if (isTypeAny(methodType)) {
      return anyIterationTypes;
    }
    const methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : emptyArray;
    if (methodSignatures.length === 0) {
      if (errorNode) {
        const diagnostic = methodName === "next" ? resolver.mustHaveANextMethodDiagnostic : resolver.mustBeAMethodDiagnostic;
        if (errorOutputContainer) {
          errorOutputContainer.errors ?? (errorOutputContainer.errors = []);
          errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, diagnostic, methodName));
        } else {
          error(errorNode, diagnostic, methodName);
        }
      }
      return methodName === "next" ? noIterationTypes : void 0;
    }
    if ((methodType == null ? void 0 : methodType.symbol) && methodSignatures.length === 1) {
      const globalGeneratorType = resolver.getGlobalGeneratorType(
        /*reportErrors*/
        false
      );
      const globalIteratorType = resolver.getGlobalIteratorType(
        /*reportErrors*/
        false
      );
      const isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) == null ? void 0 : _a.members) == null ? void 0 : _b.get(methodName)) === methodType.symbol;
      const isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) == null ? void 0 : _c.members) == null ? void 0 : _d.get(methodName)) === methodType.symbol;
      if (isGeneratorMethod || isIteratorMethod) {
        const globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType;
        const { mapper } = methodType;
        return createIterationTypes(
          getMappedType(globalType.typeParameters[0], mapper),
          getMappedType(globalType.typeParameters[1], mapper),
          methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : void 0
        );
      }
    }
    let methodParameterTypes;
    let methodReturnTypes;
    for (const signature of methodSignatures) {
      if (methodName !== "throw" && some(signature.parameters)) {
        methodParameterTypes = append(methodParameterTypes, getTypeAtPosition(signature, 0));
      }
      methodReturnTypes = append(methodReturnTypes, getReturnTypeOfSignature(signature));
    }
    let returnTypes;
    let nextType;
    if (methodName !== "throw") {
      const methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
      if (methodName === "next") {
        nextType = methodParameterType;
      } else if (methodName === "return") {
        const resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
        returnTypes = append(returnTypes, resolvedMethodParameterType);
      }
    }
    let yieldType;
    const methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
    const resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
    const iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
    if (iterationTypes === noIterationTypes) {
      if (errorNode) {
        if (errorOutputContainer) {
          errorOutputContainer.errors ?? (errorOutputContainer.errors = []);
          errorOutputContainer.errors.push(createDiagnosticForNode(errorNode, resolver.mustHaveAValueDiagnostic, methodName));
        } else {
          error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
        }
      }
      yieldType = anyType;
      returnTypes = append(returnTypes, anyType);
    } else {
      yieldType = iterationTypes.yieldType;
      returnTypes = append(returnTypes, iterationTypes.returnType);
    }
    return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
  }
  function getIterationTypesOfIteratorSlow(type, resolver, errorNode, errorOutputContainer, noCache) {
    const iterationTypes = combineIterationTypes([
      getIterationTypesOfMethod(type, resolver, "next", errorNode, errorOutputContainer),
      getIterationTypesOfMethod(type, resolver, "return", errorNode, errorOutputContainer),
      getIterationTypesOfMethod(type, resolver, "throw", errorNode, errorOutputContainer)
    ]);
    return noCache ? iterationTypes : setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
  }
  function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
    if (isTypeAny(returnType)) {
      return void 0;
    }
    const iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
    return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
  }
  function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
    if (isTypeAny(type)) {
      return anyIterationTypes;
    }
    const use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
    const resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
    return getIterationTypesOfIterable(
      type,
      use,
      /*errorNode*/
      void 0
    ) || getIterationTypesOfIterator(
      type,
      resolver,
      /*errorNode*/
      void 0,
      /*errorOutputContainer*/
      void 0
    );
  }
  function checkBreakOrContinueStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) checkGrammarBreakOrContinueStatement(node);
  }
  function unwrapReturnType(returnType, functionFlags) {
    const isGenerator = !!(functionFlags & 1 /* Generator */);
    const isAsync = !!(functionFlags & 2 /* Async */);
    if (isGenerator) {
      const returnIterationType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync);
      if (!returnIterationType) {
        return errorType;
      }
      return isAsync ? getAwaitedTypeNoAlias(unwrapAwaitedType(returnIterationType)) : returnIterationType;
    }
    return isAsync ? getAwaitedTypeNoAlias(returnType) || errorType : returnType;
  }
  function isUnwrappedReturnTypeUndefinedVoidOrAny(func, returnType) {
    const type = unwrapReturnType(returnType, getFunctionFlags(func));
    return !!(type && (maybeTypeOfKind(type, 16384 /* Void */) || type.flags & (1 /* Any */ | 32768 /* Undefined */)));
  }
  function checkReturnStatement(node) {
    if (checkGrammarStatementInAmbientContext(node)) {
      return;
    }
    const container = getContainingFunctionOrClassStaticBlock(node);
    if (container && isClassStaticBlockDeclaration(container)) {
      grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_cannot_be_used_inside_a_class_static_block);
      return;
    }
    if (!container) {
      grammarErrorOnFirstToken(node, Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
      return;
    }
    const signature = getSignatureFromDeclaration(container);
    const returnType = getReturnTypeOfSignature(signature);
    const functionFlags = getFunctionFlags(container);
    if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
      const exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
      if (container.kind === 178 /* SetAccessor */) {
        if (node.expression) {
          error(node, Diagnostics.Setters_cannot_return_a_value);
        }
      } else if (container.kind === 176 /* Constructor */) {
        if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
          error(node, Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
        }
      } else if (getReturnTypeFromAnnotation(container)) {
        const unwrappedReturnType = unwrapReturnType(returnType, functionFlags) ?? returnType;
        const unwrappedExprType = functionFlags & 2 /* Async */ ? checkAwaitedType(
          exprType,
          /*withAlias*/
          false,
          node,
          Diagnostics.The_return_type_of_an_async_function_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member
        ) : exprType;
        if (unwrappedReturnType) {
          checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
        }
      }
    } else if (container.kind !== 176 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeUndefinedVoidOrAny(container, returnType)) {
      error(node, Diagnostics.Not_all_code_paths_return_a_value);
    }
  }
  function checkWithStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (node.flags & 65536 /* AwaitContext */) {
        grammarErrorOnFirstToken(node, Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
      }
    }
    checkExpression(node.expression);
    const sourceFile = getSourceFileOfNode(node);
    if (!hasParseDiagnostics(sourceFile)) {
      const start = getSpanOfTokenAtPosition(sourceFile, node.pos).start;
      const end = node.statement.pos;
      grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
    }
  }
  function checkSwitchStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    let firstDefaultClause;
    let hasDuplicateDefaultClause = false;
    const expressionType = checkExpression(node.expression);
    forEach(node.caseBlock.clauses, (clause) => {
      if (clause.kind === 297 /* DefaultClause */ && !hasDuplicateDefaultClause) {
        if (firstDefaultClause === void 0) {
          firstDefaultClause = clause;
        } else {
          grammarErrorOnNode(clause, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
          hasDuplicateDefaultClause = true;
        }
      }
      if (clause.kind === 296 /* CaseClause */) {
        addLazyDiagnostic(createLazyCaseClauseDiagnostics(clause));
      }
      forEach(clause.statements, checkSourceElement);
      if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
        error(clause, Diagnostics.Fallthrough_case_in_switch);
      }
      function createLazyCaseClauseDiagnostics(clause2) {
        return () => {
          const caseType = checkExpression(clause2.expression);
          if (!isTypeEqualityComparableTo(expressionType, caseType)) {
            checkTypeComparableTo(
              caseType,
              expressionType,
              clause2.expression,
              /*headMessage*/
              void 0
            );
          }
        };
      }
    });
    if (node.caseBlock.locals) {
      registerForUnusedIdentifiersCheck(node.caseBlock);
    }
  }
  function checkLabeledStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      findAncestor(node.parent, (current) => {
        if (isFunctionLike(current)) {
          return "quit";
        }
        if (current.kind === 256 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
          grammarErrorOnNode(node.label, Diagnostics.Duplicate_label_0, getTextOfNode(node.label));
          return true;
        }
        return false;
      });
    }
    checkSourceElement(node.statement);
  }
  function checkThrowStatement(node) {
    if (!checkGrammarStatementInAmbientContext(node)) {
      if (isIdentifier(node.expression) && !node.expression.escapedText) {
        grammarErrorAfterFirstToken(node, Diagnostics.Line_break_not_permitted_here);
      }
    }
    if (node.expression) {
      checkExpression(node.expression);
    }
  }
  function checkTryStatement(node) {
    checkGrammarStatementInAmbientContext(node);
    checkBlock(node.tryBlock);
    const catchClause = node.catchClause;
    if (catchClause) {
      if (catchClause.variableDeclaration) {
        const declaration = catchClause.variableDeclaration;
        checkVariableLikeDeclaration(declaration);
        const typeNode = getEffectiveTypeAnnotationNode(declaration);
        if (typeNode) {
          const type = getTypeFromTypeNode(typeNode);
          if (type && !(type.flags & 3 /* AnyOrUnknown */)) {
            grammarErrorOnFirstToken(typeNode, Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
          }
        } else if (declaration.initializer) {
          grammarErrorOnFirstToken(declaration.initializer, Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
        } else {
          const blockLocals = catchClause.block.locals;
          if (blockLocals) {
            forEachKey(catchClause.locals, (caughtName) => {
              const blockLocal = blockLocals.get(caughtName);
              if ((blockLocal == null ? void 0 : blockLocal.valueDeclaration) && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
                grammarErrorOnNode(blockLocal.valueDeclaration, Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, unescapeLeadingUnderscores(caughtName));
              }
            });
          }
        }
      }
      checkBlock(catchClause.block);
    }
    if (node.finallyBlock) {
      checkBlock(node.finallyBlock);
    }
  }
  function checkIndexConstraints(type, symbol, isStaticIndex) {
    const indexInfos = getIndexInfosOfType(type);
    if (indexInfos.length === 0) {
      return;
    }
    for (const prop of getPropertiesOfObjectType(type)) {
      if (!(isStaticIndex && prop.flags & 4194304 /* Prototype */)) {
        checkIndexConstraintForProperty(type, prop, getLiteralTypeFromProperty(
          prop,
          8576 /* StringOrNumberLiteralOrUnique */,
          /*includeNonPublic*/
          true
        ), getNonMissingTypeOfSymbol(prop));
      }
    }
    const typeDeclaration = symbol.valueDeclaration;
    if (typeDeclaration && isClassLike(typeDeclaration)) {
      for (const member of typeDeclaration.members) {
        if (!isStatic(member) && !hasBindableName(member)) {
          const symbol2 = getSymbolOfDeclaration(member);
          checkIndexConstraintForProperty(type, symbol2, getTypeOfExpression(member.name.expression), getNonMissingTypeOfSymbol(symbol2));
        }
      }
    }
    if (indexInfos.length > 1) {
      for (const info of indexInfos) {
        checkIndexConstraintForIndexSignature(type, info);
      }
    }
  }
  function checkIndexConstraintForProperty(type, prop, propNameType, propType) {
    const declaration = prop.valueDeclaration;
    const name = getNameOfDeclaration(declaration);
    if (name && isPrivateIdentifier(name)) {
      return;
    }
    const indexInfos = getApplicableIndexInfos(type, propNameType);
    const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0;
    const propDeclaration = declaration && declaration.kind === 226 /* BinaryExpression */ || name && name.kind === 167 /* ComputedPropertyName */ ? declaration : void 0;
    const localPropDeclaration = getParentOfSymbol(prop) === type.symbol ? declaration : void 0;
    for (const info of indexInfos) {
      const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0;
      const errorNode = localPropDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getPropertyOfObjectType(base, prop.escapedName) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0);
      if (errorNode && !isTypeAssignableTo(propType, info.type)) {
        const diagnostic = createError(errorNode, Diagnostics.Property_0_of_type_1_is_not_assignable_to_2_index_type_3, symbolToString(prop), typeToString(propType), typeToString(info.keyType), typeToString(info.type));
        if (propDeclaration && errorNode !== propDeclaration) {
          addRelatedInfo(diagnostic, createDiagnosticForNode(propDeclaration, Diagnostics._0_is_declared_here, symbolToString(prop)));
        }
        diagnostics.add(diagnostic);
      }
    }
  }
  function checkIndexConstraintForIndexSignature(type, checkInfo) {
    const declaration = checkInfo.declaration;
    const indexInfos = getApplicableIndexInfos(type, checkInfo.keyType);
    const interfaceDeclaration = getObjectFlags(type) & 2 /* Interface */ ? getDeclarationOfKind(type.symbol, 264 /* InterfaceDeclaration */) : void 0;
    const localCheckDeclaration = declaration && getParentOfSymbol(getSymbolOfDeclaration(declaration)) === type.symbol ? declaration : void 0;
    for (const info of indexInfos) {
      if (info === checkInfo) continue;
      const localIndexDeclaration = info.declaration && getParentOfSymbol(getSymbolOfDeclaration(info.declaration)) === type.symbol ? info.declaration : void 0;
      const errorNode = localCheckDeclaration || localIndexDeclaration || (interfaceDeclaration && !some(getBaseTypes(type), (base) => !!getIndexInfoOfType(base, checkInfo.keyType) && !!getIndexTypeOfType(base, info.keyType)) ? interfaceDeclaration : void 0);
      if (errorNode && !isTypeAssignableTo(checkInfo.type, info.type)) {
        error(errorNode, Diagnostics._0_index_type_1_is_not_assignable_to_2_index_type_3, typeToString(checkInfo.keyType), typeToString(checkInfo.type), typeToString(info.keyType), typeToString(info.type));
      }
    }
  }
  function checkTypeNameIsReserved(name, message) {
    switch (name.escapedText) {
      case "any":
      case "unknown":
      case "never":
      case "number":
      case "bigint":
      case "boolean":
      case "string":
      case "symbol":
      case "void":
      case "object":
      case "undefined":
        error(name, message, name.escapedText);
    }
  }
  function checkClassNameCollisionWithObject(name) {
    if (languageVersion >= 1 /* ES5 */ && name.escapedText === "Object" && host.getEmitModuleFormatOfFile(getSourceFileOfNode(name)) < 5 /* ES2015 */) {
      error(name, Diagnostics.Class_name_cannot_be_Object_when_targeting_ES5_with_module_0, ModuleKind[moduleKind]);
    }
  }
  function checkUnmatchedJSDocParameters(node) {
    const jsdocParameters = filter(getJSDocTags(node), isJSDocParameterTag);
    if (!length(jsdocParameters)) return;
    const isJs = isInJSFile(node);
    const parameters = /* @__PURE__ */ new Set();
    const excludedParameters = /* @__PURE__ */ new Set();
    forEach(node.parameters, ({ name }, index) => {
      if (isIdentifier(name)) {
        parameters.add(name.escapedText);
      }
      if (isBindingPattern(name)) {
        excludedParameters.add(index);
      }
    });
    const containsArguments = containsArgumentsReference(node);
    if (containsArguments) {
      const lastJSDocParamIndex = jsdocParameters.length - 1;
      const lastJSDocParam = jsdocParameters[lastJSDocParamIndex];
      if (isJs && lastJSDocParam && isIdentifier(lastJSDocParam.name) && lastJSDocParam.typeExpression && lastJSDocParam.typeExpression.type && !parameters.has(lastJSDocParam.name.escapedText) && !excludedParameters.has(lastJSDocParamIndex) && !isArrayType(getTypeFromTypeNode(lastJSDocParam.typeExpression.type))) {
        error(lastJSDocParam.name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name_It_would_match_arguments_if_it_had_an_array_type, idText(lastJSDocParam.name));
      }
    } else {
      forEach(jsdocParameters, ({ name, isNameFirst }, index) => {
        if (excludedParameters.has(index) || isIdentifier(name) && parameters.has(name.escapedText)) {
          return;
        }
        if (isQualifiedName(name)) {
          if (isJs) {
            error(name, Diagnostics.Qualified_name_0_is_not_allowed_without_a_leading_param_object_1, entityNameToString(name), entityNameToString(name.left));
          }
        } else {
          if (!isNameFirst) {
            errorOrSuggestion(isJs, name, Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, idText(name));
          }
        }
      });
    }
  }
  function checkTypeParameters(typeParameterDeclarations) {
    let seenDefault = false;
    if (typeParameterDeclarations) {
      for (let i = 0; i < typeParameterDeclarations.length; i++) {
        const node = typeParameterDeclarations[i];
        checkTypeParameter(node);
        addLazyDiagnostic(createCheckTypeParameterDiagnostic(node, i));
      }
    }
    function createCheckTypeParameterDiagnostic(node, i) {
      return () => {
        if (node.default) {
          seenDefault = true;
          checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
        } else if (seenDefault) {
          error(node, Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
        }
        for (let j = 0; j < i; j++) {
          if (typeParameterDeclarations[j].symbol === node.symbol) {
            error(node.name, Diagnostics.Duplicate_identifier_0, declarationNameToString(node.name));
          }
        }
      };
    }
  }
  function checkTypeParametersNotReferenced(root, typeParameters, index) {
    visit(root);
    function visit(node) {
      if (node.kind === 183 /* TypeReference */) {
        const type = getTypeFromTypeReference(node);
        if (type.flags & 262144 /* TypeParameter */) {
          for (let i = index; i < typeParameters.length; i++) {
            if (type.symbol === getSymbolOfDeclaration(typeParameters[i])) {
              error(node, Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
            }
          }
        }
      }
      forEachChild(node, visit);
    }
  }
  function checkTypeParameterListsIdentical(symbol) {
    if (symbol.declarations && symbol.declarations.length === 1) {
      return;
    }
    const links = getSymbolLinks(symbol);
    if (!links.typeParametersChecked) {
      links.typeParametersChecked = true;
      const declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
      if (!declarations || declarations.length <= 1) {
        return;
      }
      const type = getDeclaredTypeOfSymbol(symbol);
      if (!areTypeParametersIdentical(declarations, type.localTypeParameters, getEffectiveTypeParameterDeclarations)) {
        const name = symbolToString(symbol);
        for (const declaration of declarations) {
          error(declaration.name, Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
        }
      }
    }
  }
  function areTypeParametersIdentical(declarations, targetParameters, getTypeParameterDeclarations) {
    const maxTypeArgumentCount = length(targetParameters);
    const minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
    for (const declaration of declarations) {
      const sourceParameters = getTypeParameterDeclarations(declaration);
      const numTypeParameters = sourceParameters.length;
      if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
        return false;
      }
      for (let i = 0; i < numTypeParameters; i++) {
        const source = sourceParameters[i];
        const target = targetParameters[i];
        if (source.name.escapedText !== target.symbol.escapedName) {
          return false;
        }
        const constraint = getEffectiveConstraintOfTypeParameter(source);
        const sourceConstraint = constraint && getTypeFromTypeNode(constraint);
        const targetConstraint = getConstraintOfTypeParameter(target);
        if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
          return false;
        }
        const sourceDefault = source.default && getTypeFromTypeNode(source.default);
        const targetDefault = getDefaultFromTypeParameter(target);
        if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
          return false;
        }
      }
    }
    return true;
  }
  function getFirstTransformableStaticClassElement(node) {
    const willTransformStaticElementsOfDecoratedClass = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators && classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    );
    const willTransformPrivateElementsOrClassStaticBlocks = languageVersion < LanguageFeatureMinimumTarget.PrivateNamesAndClassStaticBlocks || languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators;
    const willTransformInitializers = !emitStandardClassFields;
    if (willTransformStaticElementsOfDecoratedClass || willTransformPrivateElementsOrClassStaticBlocks) {
      for (const member of node.members) {
        if (willTransformStaticElementsOfDecoratedClass && classElementOrClassElementParameterIsDecorated(
          /*useLegacyDecorators*/
          false,
          member,
          node
        )) {
          return firstOrUndefined(getDecorators(node)) ?? node;
        } else if (willTransformPrivateElementsOrClassStaticBlocks) {
          if (isClassStaticBlockDeclaration(member)) {
            return member;
          } else if (isStatic(member)) {
            if (isPrivateIdentifierClassElementDeclaration(member) || willTransformInitializers && isInitializedProperty(member)) {
              return member;
            }
          }
        }
      }
    }
  }
  function checkClassExpressionExternalHelpers(node) {
    if (node.name) return;
    const parent = walkUpOuterExpressions(node);
    if (!isNamedEvaluationSource(parent)) return;
    const willTransformESDecorators = !legacyDecorators && languageVersion < LanguageFeatureMinimumTarget.ClassAndClassElementDecorators;
    let location;
    if (willTransformESDecorators && classOrConstructorParameterIsDecorated(
      /*useLegacyDecorators*/
      false,
      node
    )) {
      location = firstOrUndefined(getDecorators(node)) ?? node;
    } else {
      location = getFirstTransformableStaticClassElement(node);
    }
    if (location) {
      checkExternalEmitHelpers(location, 4194304 /* SetFunctionName */);
      if ((isPropertyAssignment(parent) || isPropertyDeclaration(parent) || isBindingElement(parent)) && isComputedPropertyName(parent.name)) {
        checkExternalEmitHelpers(location, 8388608 /* PropKey */);
      }
    }
  }
  function checkClassExpression(node) {
    checkClassLikeDeclaration(node);
    checkNodeDeferred(node);
    checkClassExpressionExternalHelpers(node);
    return getTypeOfSymbol(getSymbolOfDeclaration(node));
  }
  function checkClassExpressionDeferred(node) {
    forEach(node.members, checkSourceElement);
    registerForUnusedIdentifiersCheck(node);
  }
  function checkClassDeclaration(node) {
    const firstDecorator = find(node.modifiers, isDecorator);
    if (legacyDecorators && firstDecorator && some(node.members, (p) => hasStaticModifier(p) && isPrivateIdentifierClassElementDeclaration(p))) {
      grammarErrorOnNode(firstDecorator, Diagnostics.Class_decorators_can_t_be_used_with_static_private_identifier_Consider_removing_the_experimental_decorator);
    }
    if (!node.name && !hasSyntacticModifier(node, 2048 /* Default */)) {
      grammarErrorOnFirstToken(node, Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
    }
    checkClassLikeDeclaration(node);
    forEach(node.members, checkSourceElement);
    registerForUnusedIdentifiersCheck(node);
  }
  function checkClassLikeDeclaration(node) {
    checkGrammarClassLikeDeclaration(node);
    checkDecorators(node);
    checkCollisionsForDeclarationName(node, node.name);
    checkTypeParameters(getEffectiveTypeParameterDeclarations(node));
    checkExportsOnMergedDeclarations(node);
    const symbol = getSymbolOfDeclaration(node);
    const type = getDeclaredTypeOfSymbol(symbol);
    const typeWithThis = getTypeWithThisArgument(type);
    const staticType = getTypeOfSymbol(symbol);
    checkTypeParameterListsIdentical(symbol);
    checkFunctionOrConstructorSymbol(symbol);
    checkClassForDuplicateDeclarations(node);
    const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */);
    if (!nodeInAmbientContext) {
      checkClassForStaticPropertyNameConflicts(node);
    }
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    if (baseTypeNode) {
      forEach(baseTypeNode.typeArguments, checkSourceElement);
      if (languageVersion < LanguageFeatureMinimumTarget.Classes) {
        checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
      }
      const extendsNode = getClassExtendsHeritageElement(node);
      if (extendsNode && extendsNode !== baseTypeNode) {
        checkExpression(extendsNode.expression);
      }
      const baseTypes = getBaseTypes(type);
      if (baseTypes.length) {
        addLazyDiagnostic(() => {
          const baseType = baseTypes[0];
          const baseConstructorType = getBaseConstructorTypeOfClass(type);
          const staticBaseType = getApparentType(baseConstructorType);
          checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
          checkSourceElement(baseTypeNode.expression);
          if (some(baseTypeNode.typeArguments)) {
            forEach(baseTypeNode.typeArguments, checkSourceElement);
            for (const constructor of getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode)) {
              if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
                break;
              }
            }
          }
          const baseWithThis = getTypeWithThisArgument(baseType, type.thisType);
          if (!checkTypeAssignableTo(
            typeWithThis,
            baseWithThis,
            /*errorNode*/
            void 0
          )) {
            issueMemberSpecificError(node, typeWithThis, baseWithThis, Diagnostics.Class_0_incorrectly_extends_base_class_1);
          } else {
            checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
          }
          if (baseConstructorType.flags & 8650752 /* TypeVariable */) {
            if (!isMixinConstructorType(staticType)) {
              error(node.name || node, Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
            } else {
              const constructSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
              if (constructSignatures.some((signature) => signature.flags & 4 /* Abstract */) && !hasSyntacticModifier(node, 64 /* Abstract */)) {
                error(node.name || node, Diagnostics.A_mixin_class_that_extends_from_a_type_variable_containing_an_abstract_construct_signature_must_also_be_declared_abstract);
              }
            }
          }
          if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
            const constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
            if (forEach(constructors, (sig) => !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType))) {
              error(baseTypeNode.expression, Diagnostics.Base_constructors_must_all_have_the_same_return_type);
            }
          }
          checkKindsOfPropertyMemberOverrides(type, baseType);
        });
      }
    }
    checkMembersForOverrideModifier(node, type, typeWithThis, staticType);
    const implementedTypeNodes = getEffectiveImplementsTypeNodes(node);
    if (implementedTypeNodes) {
      for (const typeRefNode of implementedTypeNodes) {
        if (!isEntityNameExpression(typeRefNode.expression) || isOptionalChain(typeRefNode.expression)) {
          error(typeRefNode.expression, Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
        }
        checkTypeReferenceNode(typeRefNode);
        addLazyDiagnostic(createImplementsDiagnostics(typeRefNode));
      }
    }
    addLazyDiagnostic(() => {
      checkIndexConstraints(type, symbol);
      checkIndexConstraints(
        staticType,
        symbol,
        /*isStaticIndex*/
        true
      );
      checkTypeForDuplicateIndexSignatures(node);
      checkPropertyInitialization(node);
    });
    function createImplementsDiagnostics(typeRefNode) {
      return () => {
        const t = getReducedType(getTypeFromTypeNode(typeRefNode));
        if (!isErrorType(t)) {
          if (isValidBaseType(t)) {
            const genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : Diagnostics.Class_0_incorrectly_implements_interface_1;
            const baseWithThis = getTypeWithThisArgument(t, type.thisType);
            if (!checkTypeAssignableTo(
              typeWithThis,
              baseWithThis,
              /*errorNode*/
              void 0
            )) {
              issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
            }
          } else {
            error(typeRefNode, Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
          }
        }
      };
    }
  }
  function checkMembersForOverrideModifier(node, type, typeWithThis, staticType) {
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    const baseTypes = baseTypeNode && getBaseTypes(type);
    const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0;
    const baseStaticType = getBaseConstructorTypeOfClass(type);
    for (const member of node.members) {
      if (hasAmbientModifier(member)) {
        continue;
      }
      if (isConstructorDeclaration(member)) {
        forEach(member.parameters, (param) => {
          if (isParameterPropertyDeclaration(param, member)) {
            checkExistingMemberForOverrideModifier(
              node,
              staticType,
              baseStaticType,
              baseWithThis,
              type,
              typeWithThis,
              param,
              /*memberIsParameterProperty*/
              true
            );
          }
        });
      }
      checkExistingMemberForOverrideModifier(
        node,
        staticType,
        baseStaticType,
        baseWithThis,
        type,
        typeWithThis,
        member,
        /*memberIsParameterProperty*/
        false
      );
    }
  }
  function checkExistingMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, member, memberIsParameterProperty, reportErrors2 = true) {
    const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
    if (!declaredProp) {
      return 0 /* Ok */;
    }
    return checkMemberForOverrideModifier(
      node,
      staticType,
      baseStaticType,
      baseWithThis,
      type,
      typeWithThis,
      hasOverrideModifier(member),
      hasAbstractModifier(member),
      isStatic(member),
      memberIsParameterProperty,
      declaredProp,
      reportErrors2 ? member : void 0
    );
  }
  function checkMemberForOverrideModifier(node, staticType, baseStaticType, baseWithThis, type, typeWithThis, memberHasOverrideModifier, memberHasAbstractModifier, memberIsStatic, memberIsParameterProperty, member, errorNode) {
    const isJs = isInJSFile(node);
    const nodeInAmbientContext = !!(node.flags & 33554432 /* Ambient */);
    if (baseWithThis && (memberHasOverrideModifier || compilerOptions.noImplicitOverride)) {
      const thisType = memberIsStatic ? staticType : typeWithThis;
      const baseType = memberIsStatic ? baseStaticType : baseWithThis;
      const prop = getPropertyOfType(thisType, member.escapedName);
      const baseProp = getPropertyOfType(baseType, member.escapedName);
      const baseClassName = typeToString(baseWithThis);
      if (prop && !baseProp && memberHasOverrideModifier) {
        if (errorNode) {
          const suggestion = getSuggestedSymbolForNonexistentClassMember(symbolName(member), baseType);
          suggestion ? error(
            errorNode,
            isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0_Did_you_mean_1,
            baseClassName,
            symbolToString(suggestion)
          ) : error(
            errorNode,
            isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_it_is_not_declared_in_the_base_class_0 : Diagnostics.This_member_cannot_have_an_override_modifier_because_it_is_not_declared_in_the_base_class_0,
            baseClassName
          );
        }
        return 2 /* HasInvalidOverride */;
      } else if (prop && (baseProp == null ? void 0 : baseProp.declarations) && compilerOptions.noImplicitOverride && !nodeInAmbientContext) {
        const baseHasAbstract = some(baseProp.declarations, hasAbstractModifier);
        if (memberHasOverrideModifier) {
          return 0 /* Ok */;
        }
        if (!baseHasAbstract) {
          if (errorNode) {
            const diag2 = memberIsParameterProperty ? isJs ? Diagnostics.This_parameter_property_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_parameter_property_must_have_an_override_modifier_because_it_overrides_a_member_in_base_class_0 : isJs ? Diagnostics.This_member_must_have_a_JSDoc_comment_with_an_override_tag_because_it_overrides_a_member_in_the_base_class_0 : Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_a_member_in_the_base_class_0;
            error(errorNode, diag2, baseClassName);
          }
          return 1 /* NeedsOverride */;
        } else if (memberHasAbstractModifier && baseHasAbstract) {
          if (errorNode) {
            error(errorNode, Diagnostics.This_member_must_have_an_override_modifier_because_it_overrides_an_abstract_method_that_is_declared_in_the_base_class_0, baseClassName);
          }
          return 1 /* NeedsOverride */;
        }
      }
    } else if (memberHasOverrideModifier) {
      if (errorNode) {
        const className = typeToString(type);
        error(
          errorNode,
          isJs ? Diagnostics.This_member_cannot_have_a_JSDoc_comment_with_an_override_tag_because_its_containing_class_0_does_not_extend_another_class : Diagnostics.This_member_cannot_have_an_override_modifier_because_its_containing_class_0_does_not_extend_another_class,
          className
        );
      }
      return 2 /* HasInvalidOverride */;
    }
    return 0 /* Ok */;
  }
  function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
    let issuedMemberError = false;
    for (const member of node.members) {
      if (isStatic(member)) {
        continue;
      }
      const declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
      if (declaredProp) {
        const prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
        const baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
        if (prop && baseProp) {
          const rootChain = () => chainDiagnosticMessages(
            /*details*/
            void 0,
            Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2,
            symbolToString(declaredProp),
            typeToString(typeWithThis),
            typeToString(baseWithThis)
          );
          if (!checkTypeAssignableTo(
            getTypeOfSymbol(prop),
            getTypeOfSymbol(baseProp),
            member.name || member,
            /*headMessage*/
            void 0,
            rootChain
          )) {
            issuedMemberError = true;
          }
        }
      }
    }
    if (!issuedMemberError) {
      checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
    }
  }
  function checkBaseTypeAccessibility(type, node) {
    const signatures = getSignaturesOfType(type, 1 /* Construct */);
    if (signatures.length) {
      const declaration = signatures[0].declaration;
      if (declaration && hasEffectiveModifier(declaration, 2 /* Private */)) {
        const typeClassDeclaration = getClassLikeDeclarationOfSymbol(type.symbol);
        if (!isNodeWithinClass(node, typeClassDeclaration)) {
          error(node, Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
        }
      }
    }
  }
  function getMemberOverrideModifierStatus(node, member, memberSymbol) {
    if (!member.name) {
      return 0 /* Ok */;
    }
    const classSymbol = getSymbolOfDeclaration(node);
    const type = getDeclaredTypeOfSymbol(classSymbol);
    const typeWithThis = getTypeWithThisArgument(type);
    const staticType = getTypeOfSymbol(classSymbol);
    const baseTypeNode = getEffectiveBaseTypeNode(node);
    const baseTypes = baseTypeNode && getBaseTypes(type);
    const baseWithThis = (baseTypes == null ? void 0 : baseTypes.length) ? getTypeWithThisArgument(first(baseTypes), type.thisType) : void 0;
    const baseStaticType = getBaseConstructorTypeOfClass(type);
    const memberHasOverrideModifier = member.parent ? hasOverrideModifier(member) : hasSyntacticModifier(member, 16 /* Override */);
    return checkMemberForOverrideModifier(
      node,
      staticType,
      baseStaticType,
      baseWithThis,
      type,
      typeWithThis,
      memberHasOverrideModifier,
      hasAbstractModifier(member),
      isStatic(member),
      /*memberIsParameterProperty*/
      false,
      memberSymbol
    );
  }
  function getTargetSymbol(s) {
    return getCheckFlags(s) & 1 /* Instantiated */ ? s.links.target : s;
  }
  function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
    return filter(symbol.declarations, (d) => d.kind === 263 /* ClassDeclaration */ || d.kind === 264 /* InterfaceDeclaration */);
  }
  function checkKindsOfPropertyMemberOverrides(type, baseType) {
    var _a, _b, _c, _d, _e;
    const baseProperties = getPropertiesOfType(baseType);
    const notImplementedInfo = /* @__PURE__ */ new Map();
    basePropertyCheck: for (const baseProperty of baseProperties) {
      const base = getTargetSymbol(baseProperty);
      if (base.flags & 4194304 /* Prototype */) {
        continue;
      }
      const baseSymbol = getPropertyOfObjectType(type, base.escapedName);
      if (!baseSymbol) {
        continue;
      }
      const derived = getTargetSymbol(baseSymbol);
      const baseDeclarationFlags = getDeclarationModifierFlagsFromSymbol(base);
      Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
      if (derived === base) {
        const derivedClassDecl = getClassLikeDeclarationOfSymbol(type.symbol);
        if (baseDeclarationFlags & 64 /* Abstract */ && (!derivedClassDecl || !hasSyntacticModifier(derivedClassDecl, 64 /* Abstract */))) {
          for (const otherBaseType of getBaseTypes(type)) {
            if (otherBaseType === baseType) continue;
            const baseSymbol2 = getPropertyOfObjectType(otherBaseType, base.escapedName);
            const derivedElsewhere = baseSymbol2 && getTargetSymbol(baseSymbol2);
            if (derivedElsewhere && derivedElsewhere !== base) {
              continue basePropertyCheck;
            }
          }
          const baseTypeName = typeToString(baseType);
          const typeName = typeToString(type);
          const basePropertyName = symbolToString(baseProperty);
          const missedProperties = append((_a = notImplementedInfo.get(derivedClassDecl)) == null ? void 0 : _a.missedProperties, basePropertyName);
          notImplementedInfo.set(derivedClassDecl, { baseTypeName, typeName, missedProperties });
        }
      } else {
        const derivedDeclarationFlags = getDeclarationModifierFlagsFromSymbol(derived);
        if (baseDeclarationFlags & 2 /* Private */ || derivedDeclarationFlags & 2 /* Private */) {
          continue;
        }
        let errorMessage;
        const basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
        const derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
        if (basePropertyFlags && derivedPropertyFlags) {
          if ((getCheckFlags(base) & 6 /* Synthetic */ ? (_b = base.declarations) == null ? void 0 : _b.some((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags)) : (_c = base.declarations) == null ? void 0 : _c.every((d) => isPropertyAbstractOrInterface(d, baseDeclarationFlags))) || getCheckFlags(base) & 262144 /* Mapped */ || derived.valueDeclaration && isBinaryExpression(derived.valueDeclaration)) {
            continue;
          }
          const overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
          const overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
          if (overriddenInstanceProperty || overriddenInstanceAccessor) {
            const errorMessage2 = overriddenInstanceProperty ? Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property : Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
            error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType), typeToString(type));
          } else if (useDefineForClassFields) {
            const uninitialized = (_d = derived.declarations) == null ? void 0 : _d.find((d) => d.kind === 172 /* PropertyDeclaration */ && !d.initializer);
            if (uninitialized && !(derived.flags & 33554432 /* Transient */) && !(baseDeclarationFlags & 64 /* Abstract */) && !(derivedDeclarationFlags & 64 /* Abstract */) && !((_e = derived.declarations) == null ? void 0 : _e.some((d) => !!(d.flags & 33554432 /* Ambient */)))) {
              const constructor = findConstructorDeclaration(getClassLikeDeclarationOfSymbol(type.symbol));
              const propName = uninitialized.name;
              if (uninitialized.exclamationToken || !constructor || !isIdentifier(propName) || !strictNullChecks || !isPropertyInitializedInConstructor(propName, type, constructor)) {
                const errorMessage2 = Diagnostics.Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration;
                error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage2, symbolToString(base), typeToString(baseType));
              }
            }
          }
          continue;
        } else if (isPrototypeProperty(base)) {
          if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
            continue;
          } else {
            Debug.assert(!!(derived.flags & 98304 /* Accessor */));
            errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
          }
        } else if (base.flags & 98304 /* Accessor */) {
          errorMessage = Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
        } else {
          errorMessage = Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
        }
        error(getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
      }
    }
    for (const [errorNode, memberInfo] of notImplementedInfo) {
      if (length(memberInfo.missedProperties) === 1) {
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, first(memberInfo.missedProperties), memberInfo.baseTypeName);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, memberInfo.typeName, first(memberInfo.missedProperties), memberInfo.baseTypeName);
        }
      } else if (length(memberInfo.missedProperties) > 5) {
        const missedProperties = map(memberInfo.missedProperties.slice(0, 4), (prop) => `'${prop}'`).join(", ");
        const remainingMissedProperties = length(memberInfo.missedProperties) - 4;
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1_and_2_more, memberInfo.baseTypeName, missedProperties, remainingMissedProperties);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2_and_3_more, memberInfo.typeName, memberInfo.baseTypeName, missedProperties, remainingMissedProperties);
        }
      } else {
        const missedProperties = map(memberInfo.missedProperties, (prop) => `'${prop}'`).join(", ");
        if (isClassExpression(errorNode)) {
          error(errorNode, Diagnostics.Non_abstract_class_expression_is_missing_implementations_for_the_following_members_of_0_Colon_1, memberInfo.baseTypeName, missedProperties);
        } else {
          error(errorNode, Diagnostics.Non_abstract_class_0_is_missing_implementations_for_the_following_members_of_1_Colon_2, memberInfo.typeName, memberInfo.baseTypeName, missedProperties);
        }
      }
    }
  }
  function isPropertyAbstractOrInterface(declaration, baseDeclarationFlags) {
    return baseDeclarationFlags & 64 /* Abstract */ && (!isPropertyDeclaration(declaration) || !declaration.initializer) || isInterfaceDeclaration(declaration.parent);
  }
  function getNonInheritedProperties(type, baseTypes, properties) {
    if (!length(baseTypes)) {
      return properties;
    }
    const seen = /* @__PURE__ */ new Map();
    forEach(properties, (p) => {
      seen.set(p.escapedName, p);
    });
    for (const base of baseTypes) {
      const properties2 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
      for (const prop of properties2) {
        const existing = seen.get(prop.escapedName);
        if (existing && prop.parent === existing.parent) {
          seen.delete(prop.escapedName);
        }
      }
    }
    return arrayFrom(seen.values());
  }
  function checkInheritedPropertiesAreIdentical(type, typeNode) {
    const baseTypes = getBaseTypes(type);
    if (baseTypes.length < 2) {
      return true;
    }
    const seen = /* @__PURE__ */ new Map();
    forEach(resolveDeclaredMembers(type).declaredProperties, (p) => {
      seen.set(p.escapedName, { prop: p, containingType: type });
    });
    let ok = true;
    for (const base of baseTypes) {
      const properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
      for (const prop of properties) {
        const existing = seen.get(prop.escapedName);
        if (!existing) {
          seen.set(prop.escapedName, { prop, containingType: base });
        } else {
          const isInheritedProperty = existing.containingType !== type;
          if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
            ok = false;
            const typeName1 = typeToString(existing.containingType);
            const typeName2 = typeToString(base);
            let errorInfo = chainDiagnosticMessages(
              /*details*/
              void 0,
              Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical,
              symbolToString(prop),
              typeName1,
              typeName2
            );
            errorInfo = chainDiagnosticMessages(errorInfo, Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
            diagnostics.add(createDiagnosticForNodeFromMessageChain(getSourceFileOfNode(typeNode), typeNode, errorInfo));
          }
        }
      }
    }
    return ok;
  }
  function checkPropertyInitialization(node) {
    if (!strictNullChecks || !strictPropertyInitialization || node.flags & 33554432 /* Ambient */) {
      return;
    }
    const constructor = findConstructorDeclaration(node);
    for (const member of node.members) {
      if (getEffectiveModifierFlags(member) & 128 /* Ambient */) {
        continue;
      }
      if (!isStatic(member) && isPropertyWithoutInitializer(member)) {
        const propName = member.name;
        if (isIdentifier(propName) || isPrivateIdentifier(propName) || isComputedPropertyName(propName)) {
          const type = getTypeOfSymbol(getSymbolOfDeclaration(member));
          if (!(type.flags & 3 /* AnyOrUnknown */ || containsUndefinedType(type))) {
            if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
              error(member.name, Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, declarationNameToString(propName));
            }
          }
        }
      }
    }
  }
  function isPropertyWithoutInitializer(node) {
    return node.kind === 172 /* PropertyDeclaration */ && !hasAbstractModifier(node) && !node.exclamationToken && !node.initializer;
  }
  function isPropertyInitializedInStaticBlocks(propName, propType, staticBlocks, startPos, endPos) {
    for (const staticBlock of staticBlocks) {
      if (staticBlock.pos >= startPos && staticBlock.pos <= endPos) {
        const reference = factory.createPropertyAccessExpression(factory.createThis(), propName);
        setParent(reference.expression, reference);
        setParent(reference, staticBlock);
        reference.flowNode = staticBlock.returnFlowNode;
        const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
        if (!containsUndefinedType(flowType)) {
          return true;
        }
      }
    }
    return false;
  }
  function isPropertyInitializedInConstructor(propName, propType, constructor) {
    const reference = isComputedPropertyName(propName) ? factory.createElementAccessExpression(factory.createThis(), propName.expression) : factory.createPropertyAccessExpression(factory.createThis(), propName);
    setParent(reference.expression, reference);
    setParent(reference, constructor);
    reference.flowNode = constructor.returnFlowNode;
    const flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
    return !containsUndefinedType(flowType);
  }
  function checkInterfaceDeclaration(node) {
    if (!checkGrammarModifiers(node)) checkGrammarInterfaceDeclaration(node);
    if (!allowBlockDeclarations(node.parent)) {
      grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "interface");
    }
    checkTypeParameters(node.typeParameters);
    addLazyDiagnostic(() => {
      checkTypeNameIsReserved(node.name, Diagnostics.Interface_name_cannot_be_0);
      checkExportsOnMergedDeclarations(node);
      const symbol = getSymbolOfDeclaration(node);
      checkTypeParameterListsIdentical(symbol);
      const firstInterfaceDecl = getDeclarationOfKind(symbol, 264 /* InterfaceDeclaration */);
      if (node === firstInterfaceDecl) {
        const type = getDeclaredTypeOfSymbol(symbol);
        const typeWithThis = getTypeWithThisArgument(type);
        if (checkInheritedPropertiesAreIdentical(type, node.name)) {
          for (const baseType of getBaseTypes(type)) {
            checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, Diagnostics.Interface_0_incorrectly_extends_interface_1);
          }
          checkIndexConstraints(type, symbol);
        }
      }
      checkObjectTypeForDuplicateDeclarations(node);
    });
    forEach(getInterfaceBaseTypeNodes(node), (heritageElement) => {
      if (!isEntityNameExpression(heritageElement.expression) || isOptionalChain(heritageElement.expression)) {
        error(heritageElement.expression, Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
      }
      checkTypeReferenceNode(heritageElement);
    });
    forEach(node.members, checkSourceElement);
    addLazyDiagnostic(() => {
      checkTypeForDuplicateIndexSignatures(node);
      registerForUnusedIdentifiersCheck(node);
    });
  }
  function checkTypeAliasDeclaration(node) {
    checkGrammarModifiers(node);
    checkTypeNameIsReserved(node.name, Diagnostics.Type_alias_name_cannot_be_0);
    if (!allowBlockDeclarations(node.parent)) {
      grammarErrorOnNode(node, Diagnostics._0_declarations_can_only_be_declared_inside_a_block, "type");
    }
    checkExportsOnMergedDeclarations(node);
    checkTypeParameters(node.typeParameters);
    if (node.type.kind === 141 /* IntrinsicKeyword */) {
      const typeParameterCount = length(node.typeParameters);
      const valid = typeParameterCount === 0 ? node.name.escapedText === "BuiltinIteratorReturn" : typeParameterCount === 1 && intrinsicTypeKinds.has(node.name.escapedText);
      if (!valid) {
        error(node.type, Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types);
      }
    } else {
      checkSourceElement(node.type);
      registerForUnusedIdentifiersCheck(node);
    }
  }
  function computeEnumMemberValues(node) {
    const nodeLinks2 = getNodeLinks(node);
    if (!(nodeLinks2.flags & 1024 /* EnumValuesComputed */)) {
      nodeLinks2.flags |= 1024 /* EnumValuesComputed */;
      let autoValue = 0;
      let previous;
      for (const member of node.members) {
        const result = computeEnumMemberValue(member, autoValue, previous);
        getNodeLinks(member).enumMemberValue = result;
        autoValue = typeof result.value === "number" ? result.value + 1 : void 0;
        previous = member;
      }
    }
  }
  function computeEnumMemberValue(member, autoValue, previous) {
    if (isComputedNonLiteralName(member.name)) {
      error(member.name, Diagnostics.Computed_property_names_are_not_allowed_in_enums);
    } else {
      const text = getTextOfPropertyName(member.name);
      if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
        error(member.name, Diagnostics.An_enum_member_cannot_have_a_numeric_name);
      }
    }
    if (member.initializer) {
      return computeConstantEnumMemberValue(member);
    }
    if (member.parent.flags & 33554432 /* Ambient */ && !isEnumConst(member.parent)) {
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (autoValue === void 0) {
      error(member.name, Diagnostics.Enum_member_must_have_initializer);
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (getIsolatedModules(compilerOptions) && (previous == null ? void 0 : previous.initializer)) {
      const prevValue = getEnumMemberValue(previous);
      if (!(typeof prevValue.value === "number" && !prevValue.resolvedOtherFiles)) {
        error(
          member.name,
          Diagnostics.Enum_member_following_a_non_literal_numeric_member_must_have_an_initializer_when_isolatedModules_is_enabled
        );
      }
    }
    return evaluatorResult(autoValue);
  }
  function computeConstantEnumMemberValue(member) {
    const isConstEnum = isEnumConst(member.parent);
    const initializer = member.initializer;
    const result = evaluate(initializer, member);
    if (result.value !== void 0) {
      if (isConstEnum && typeof result.value === "number" && !isFinite(result.value)) {
        error(
          initializer,
          isNaN(result.value) ? Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN : Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value
        );
      } else if (getIsolatedModules(compilerOptions) && typeof result.value === "string" && !result.isSyntacticallyString) {
        error(
          initializer,
          Diagnostics._0_has_a_string_type_but_must_have_syntactically_recognizable_string_syntax_when_isolatedModules_is_enabled,
          `${idText(member.parent.name)}.${getTextOfPropertyName(member.name)}`
        );
      }
    } else if (isConstEnum) {
      error(initializer, Diagnostics.const_enum_member_initializers_must_be_constant_expressions);
    } else if (member.parent.flags & 33554432 /* Ambient */) {
      error(initializer, Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
    } else {
      checkTypeAssignableTo(checkExpression(initializer), numberType, initializer, Diagnostics.Type_0_is_not_assignable_to_type_1_as_required_for_computed_enum_member_values);
    }
    return result;
  }
  function evaluateEntityNameExpression(expr, location) {
    const symbol = resolveEntityName(
      expr,
      111551 /* Value */,
      /*ignoreErrors*/
      true
    );
    if (!symbol) return evaluatorResult(
      /*value*/
      void 0
    );
    if (expr.kind === 80 /* Identifier */) {
      const identifier = expr;
      if (isInfinityOrNaNString(identifier.escapedText) && symbol === getGlobalSymbol(
        identifier.escapedText,
        111551 /* Value */,
        /*diagnostic*/
        void 0
      )) {
        return evaluatorResult(
          +identifier.escapedText,
          /*isSyntacticallyString*/
          false
        );
      }
    }
    if (symbol.flags & 8 /* EnumMember */) {
      return location ? evaluateEnumMember(expr, symbol, location) : getEnumMemberValue(symbol.valueDeclaration);
    }
    if (isConstantVariable(symbol)) {
      const declaration = symbol.valueDeclaration;
      if (declaration && isVariableDeclaration(declaration) && !declaration.type && declaration.initializer && (!location || declaration !== location && isBlockScopedNameDeclaredBeforeUse(declaration, location))) {
        const result = evaluate(declaration.initializer, declaration);
        if (location && getSourceFileOfNode(location) !== getSourceFileOfNode(declaration)) {
          return evaluatorResult(
            result.value,
            /*isSyntacticallyString*/
            false,
            /*resolvedOtherFiles*/
            true,
            /*hasExternalReferences*/
            true
          );
        }
        return evaluatorResult(
          result.value,
          result.isSyntacticallyString,
          result.resolvedOtherFiles,
          /*hasExternalReferences*/
          true
        );
      }
    }
    return evaluatorResult(
      /*value*/
      void 0
    );
  }
  function evaluateElementAccessExpression(expr, location) {
    const root = expr.expression;
    if (isEntityNameExpression(root) && isStringLiteralLike(expr.argumentExpression)) {
      const rootSymbol = resolveEntityName(
        root,
        111551 /* Value */,
        /*ignoreErrors*/
        true
      );
      if (rootSymbol && rootSymbol.flags & 384 /* Enum */) {
        const name = escapeLeadingUnderscores(expr.argumentExpression.text);
        const member = rootSymbol.exports.get(name);
        if (member) {
          Debug.assert(getSourceFileOfNode(member.valueDeclaration) === getSourceFileOfNode(rootSymbol.valueDeclaration));
          return location ? evaluateEnumMember(expr, member, location) : getEnumMemberValue(member.valueDeclaration);
        }
      }
    }
    return evaluatorResult(
      /*value*/
      void 0
    );
  }
  function evaluateEnumMember(expr, symbol, location) {
    const declaration = symbol.valueDeclaration;
    if (!declaration || declaration === location) {
      error(expr, Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(symbol));
      return evaluatorResult(
        /*value*/
        void 0
      );
    }
    if (!isBlockScopedNameDeclaredBeforeUse(declaration, location)) {
      error(expr, Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
      return evaluatorResult(
        /*value*/
        0
      );
    }
    const value = getEnumMemberValue(declaration);
    if (location.parent !== declaration.parent) {
      return evaluatorResult(
        value.value,
        value.isSyntacticallyString,
        value.resolvedOtherFiles,
        /*hasExternalReferences*/
        true
      );
    }
    return value;
  }
  function checkEnumDeclaration(node) {
    addLazyDiagnostic(() => checkEnumDeclarationWorker(node));
  }
  function checkEnumDeclarationWorker(node) {
    checkGrammarModifiers(node);
    checkCollisionsForDeclarationName(node, node.name);
    checkExportsOnMergedDeclarations(node);
    node.members.forEach(checkEnumMember);
    computeEnumMemberValues(node);
    const enumSymbol = getSymbolOfDeclaration(node);
    const firstDeclaration = getDeclarationOfKind(enumSymbol, node.kind);
    if (node === firstDeclaration) {
      if (enumSymbol.declarations && enumSymbol.declarations.length > 1) {
        const enumIsConst = isEnumConst(node);
        forEach(enumSymbol.declarations, (decl) => {
          if (isEnumDeclaration(decl) && isEnumConst(decl) !== enumIsConst) {
            error(getNameOfDeclaration(decl), Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
          }
        });
      }
      let seenEnumMissingInitialInitializer = false;
      forEach(enumSymbol.declarations, (declaration) => {
        if (declaration.kind !== 266 /* EnumDeclaration */) {
          return false;
        }
        const enumDeclaration = declaration;
        if (!enumDeclaration.members.length) {
          return false;
        }
        const firstEnumMember = enumDeclaration.members[0];
        if (!firstEnumMember.initializer) {
          if (seenEnumMissingInitialInitializer) {
            error(firstEnumMember.name, Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
          } else {
            seenEnumMissingInitialInitializer = true;
          }
        }
      });
    }
  }
  function checkEnumMember(node) {
    if (isPrivateIdentifier(node.name)) {
      error(node, Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
    }
    if (node.initializer) {
      checkExpression(node.initializer);
    }
  }
  function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
    const declarations = symbol.declarations;
    if (declarations) {
      for (const declaration of declarations) {
        if ((declaration.kind === 263 /* ClassDeclaration */ || declaration.kind === 262 /* FunctionDeclaration */ && nodeIsPresent(declaration.body)) && !(declaration.flags & 33554432 /* Ambient */)) {
          return declaration;
        }
      }
    }
    return void 0;
  }
  function inSameLexicalScope(node1, node2) {
    const container1 = getEnclosingBlockScopeContainer(node1);
    const container2 = getEnclosingBlockScopeContainer(node2);
    if (isGlobalSourceFile(container1)) {
      return isGlobalSourceFile(container2);
    } else if (isGlobalSourceFile(container2)) {
      return false;
    } else {
      return container1 === container2;
    }
  }
  function checkModuleDeclaration(node) {
    if (node.body) {
      checkSourceElement(node.body);
      if (!isGlobalScopeAugmentation(node)) {
        registerForUnusedIdentifiersCheck(node);
      }
    }
    addLazyDiagnostic(checkModuleDeclarationDiagnostics);
    function checkModuleDeclarationDiagnostics() {
      var _a, _b;
      const isGlobalAugmentation = isGlobalScopeAugmentation(node);
      const inAmbientContext = node.flags & 33554432 /* Ambient */;
      if (isGlobalAugmentation && !inAmbientContext) {
        error(node.name, Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
      }
      const isAmbientExternalModule = isAmbientModule(node);
      const contextErrorMessage = isAmbientExternalModule ? Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file : Diagnostics.A_namespace_declaration_is_only_allowed_at_the_top_level_of_a_namespace_or_module;
      if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
        return;
      }
      if (!checkGrammarModifiers(node)) {
        if (!inAmbientContext && node.name.kind === 11 /* StringLiteral */) {
          grammarErrorOnNode(node.name, Diagnostics.Only_ambient_modules_can_use_quoted_names);
        }
      }
      if (isIdentifier(node.name)) {
        checkCollisionsForDeclarationName(node, node.name);
        if (!(node.flags & (32 /* Namespace */ | 2048 /* GlobalAugmentation */))) {
          const sourceFile = getSourceFileOfNode(node);
          const pos = getNonModifierTokenPosOfNode(node);
          const span = getSpanOfTokenAtPosition(sourceFile, pos);
          suggestionDiagnostics.add(
            createFileDiagnostic(sourceFile, span.start, span.length, Diagnostics.A_namespace_declaration_should_not_be_declared_using_the_module_keyword_Please_use_the_namespace_keyword_instead)
          );
        }
      }
      checkExportsOnMergedDeclarations(node);
      const symbol = getSymbolOfDeclaration(node);
      if (symbol.flags & 512 /* ValueModule */ && !inAmbientContext && isInstantiatedModule(node, shouldPreserveConstEnums(compilerOptions))) {
        if (getIsolatedModules(compilerOptions) && !getSourceFileOfNode(node).externalModuleIndicator) {
          error(node.name, Diagnostics.Namespaces_are_not_allowed_in_global_script_files_when_0_is_enabled_If_this_file_is_not_intended_to_be_a_global_script_set_moduleDetection_to_force_or_add_an_empty_export_statement, isolatedModulesLikeFlagName);
        }
        if (((_a = symbol.declarations) == null ? void 0 : _a.length) > 1) {
          const firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
          if (firstNonAmbientClassOrFunc) {
            if (getSourceFileOfNode(node) !== getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
              error(node.name, Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
            } else if (node.pos < firstNonAmbientClassOrFunc.pos) {
              error(node.name, Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
            }
          }
          const mergedClass = getDeclarationOfKind(symbol, 263 /* ClassDeclaration */);
          if (mergedClass && inSameLexicalScope(node, mergedClass)) {
            getNodeLinks(node).flags |= 2048 /* LexicalModuleMergesWithClass */;
          }
        }
        if (compilerOptions.verbatimModuleSyntax && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(node.parent) === 1 /* CommonJS */) {
          const exportModifier = (_b = node.modifiers) == null ? void 0 : _b.find((m) => m.kind === 95 /* ExportKeyword */);
          if (exportModifier) {
            error(exportModifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
          }
        }
      }
      if (isAmbientExternalModule) {
        if (isExternalModuleAugmentation(node)) {
          const checkBody = isGlobalAugmentation || getSymbolOfDeclaration(node).flags & 33554432 /* Transient */;
          if (checkBody && node.body) {
            for (const statement of node.body.statements) {
              checkModuleAugmentationElement(statement, isGlobalAugmentation);
            }
          }
        } else if (isGlobalSourceFile(node.parent)) {
          if (isGlobalAugmentation) {
            error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
          } else if (isExternalModuleNameRelative(getTextOfIdentifierOrLiteral(node.name))) {
            error(node.name, Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
          }
        } else {
          if (isGlobalAugmentation) {
            error(node.name, Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
          } else {
            error(node.name, Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
          }
        }
      }
    }
  }
  function checkModuleAugmentationElement(node, isGlobalAugmentation) {
    switch (node.kind) {
      case 243 /* VariableStatement */:
        for (const decl of node.declarationList.declarations) {
          checkModuleAugmentationElement(decl, isGlobalAugmentation);
        }
        break;
      case 277 /* ExportAssignment */:
      case 278 /* ExportDeclaration */:
        grammarErrorOnFirstToken(node, Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
        break;
      case 271 /* ImportEqualsDeclaration */:
        if (isInternalModuleImportEqualsDeclaration(node)) break;
      // falls through
      case 272 /* ImportDeclaration */:
        grammarErrorOnFirstToken(node, Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
        break;
      case 208 /* BindingElement */:
      case 260 /* VariableDeclaration */:
        const name = node.name;
        if (isBindingPattern(name)) {
          for (const el of name.elements) {
            checkModuleAugmentationElement(el, isGlobalAugmentation);
          }
          break;
        }
      // falls through
      case 263 /* ClassDeclaration */:
      case 266 /* EnumDeclaration */:
      case 262 /* FunctionDeclaration */:
      case 264 /* InterfaceDeclaration */:
      case 267 /* ModuleDeclaration */:
      case 265 /* TypeAliasDeclaration */:
        if (isGlobalAugmentation) {
          return;
        }
        break;
    }
  }
  function getFirstNonModuleExportsIdentifier(node) {
    switch (node.kind) {
      case 80 /* Identifier */:
        return node;
      case 166 /* QualifiedName */:
        do {
          node = node.left;
        } while (node.kind !== 80 /* Identifier */);
        return node;
      case 211 /* PropertyAccessExpression */:
        do {
          if (isModuleExportsAccessExpression(node.expression) && !isPrivateIdentifier(node.name)) {
            return node.name;
          }
          node = node.expression;
        } while (node.kind !== 80 /* Identifier */);
        return node;
    }
  }
  function checkExternalImportOrExportDeclaration(node) {
    const moduleName = getExternalModuleName(node);
    if (!moduleName || nodeIsMissing(moduleName)) {
      return false;
    }
    if (!isStringLiteral(moduleName)) {
      error(moduleName, Diagnostics.String_literal_expected);
      return false;
    }
    const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent);
    if (node.parent.kind !== 307 /* SourceFile */ && !inAmbientExternalModule) {
      error(
        moduleName,
        node.kind === 278 /* ExportDeclaration */ ? Diagnostics.Export_declarations_are_not_permitted_in_a_namespace : Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module
      );
      return false;
    }
    if (inAmbientExternalModule && isExternalModuleNameRelative(moduleName.text)) {
      if (!isTopLevelInExternalModuleAugmentation(node)) {
        error(node, Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
        return false;
      }
    }
    if (!isImportEqualsDeclaration(node) && node.attributes) {
      const diagnostic = node.attributes.token === 118 /* WithKeyword */ ? Diagnostics.Import_attribute_values_must_be_string_literal_expressions : Diagnostics.Import_assertion_values_must_be_string_literal_expressions;
      let hasError = false;
      for (const attr of node.attributes.elements) {
        if (!isStringLiteral(attr.value)) {
          hasError = true;
          error(attr.value, diagnostic);
        }
      }
      return !hasError;
    }
    return true;
  }
  function checkModuleExportName(name, allowStringLiteral = true) {
    if (name === void 0 || name.kind !== 11 /* StringLiteral */) {
      return;
    }
    if (!allowStringLiteral) {
      grammarErrorOnNode(name, Diagnostics.Identifier_expected);
    } else if (moduleKind === 5 /* ES2015 */ || moduleKind === 6 /* ES2020 */) {
      grammarErrorOnNode(name, Diagnostics.String_literal_import_and_export_names_are_not_supported_when_the_module_flag_is_set_to_es2015_or_es2020);
    }
  }
  function checkAliasSymbol(node) {
    var _a, _b, _c, _d;
    let symbol = getSymbolOfDeclaration(node);
    const target = resolveAlias(symbol);
    if (target !== unknownSymbol) {
      symbol = getMergedSymbol(symbol.exportSymbol || symbol);
      if (isInJSFile(node) && !(target.flags & 111551 /* Value */) && !isTypeOnlyImportOrExportDeclaration(node)) {
        const errorNode = isImportOrExportSpecifier(node) ? node.propertyName || node.name : isNamedDeclaration(node) ? node.name : node;
        Debug.assert(node.kind !== 280 /* NamespaceExport */);
        if (node.kind === 281 /* ExportSpecifier */) {
          const diag2 = error(errorNode, Diagnostics.Types_cannot_appear_in_export_declarations_in_JavaScript_files);
          const alreadyExportedSymbol = (_b = (_a = getSourceFileOfNode(node).symbol) == null ? void 0 : _a.exports) == null ? void 0 : _b.get(moduleExportNameTextEscaped(node.propertyName || node.name));
          if (alreadyExportedSymbol === target) {
            const exportingDeclaration = (_c = alreadyExportedSymbol.declarations) == null ? void 0 : _c.find(isJSDocNode);
            if (exportingDeclaration) {
              addRelatedInfo(
                diag2,
                createDiagnosticForNode(
                  exportingDeclaration,
                  Diagnostics._0_is_automatically_exported_here,
                  unescapeLeadingUnderscores(alreadyExportedSymbol.escapedName)
                )
              );
            }
          }
        } else {
          Debug.assert(node.kind !== 260 /* VariableDeclaration */);
          const importDeclaration = findAncestor(node, or(isImportDeclaration, isImportEqualsDeclaration));
          const moduleSpecifier = (importDeclaration && ((_d = tryGetModuleSpecifierFromDeclaration(importDeclaration)) == null ? void 0 : _d.text)) ?? "...";
          const importedIdentifier = unescapeLeadingUnderscores(isIdentifier(errorNode) ? errorNode.escapedText : symbol.escapedName);
          error(
            errorNode,
            Diagnostics._0_is_a_type_and_cannot_be_imported_in_JavaScript_files_Use_1_in_a_JSDoc_type_annotation,
            importedIdentifier,
            `import("${moduleSpecifier}").${importedIdentifier}`
          );
        }
        return;
      }
      const targetFlags = getSymbolFlags(target);
      const excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) | (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) | (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
      if (targetFlags & excludedMeanings) {
        const message = node.kind === 281 /* ExportSpecifier */ ? Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 : Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
        error(node, message, symbolToString(symbol));
      } else if (node.kind !== 281 /* ExportSpecifier */) {
        const appearsValueyToTranspiler = compilerOptions.isolatedModules && !findAncestor(node, isTypeOnlyImportOrExportDeclaration);
        if (appearsValueyToTranspiler && symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */)) {
          error(
            node,
            Diagnostics.Import_0_conflicts_with_local_value_so_must_be_declared_with_a_type_only_import_when_isolatedModules_is_enabled,
            symbolToString(symbol),
            isolatedModulesLikeFlagName
          );
        }
      }
      if (getIsolatedModules(compilerOptions) && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */)) {
        const typeOnlyAlias = getTypeOnlyAliasDeclaration(symbol);
        const isType = !(targetFlags & 111551 /* Value */);
        if (isType || typeOnlyAlias) {
          switch (node.kind) {
            case 273 /* ImportClause */:
            case 276 /* ImportSpecifier */:
            case 271 /* ImportEqualsDeclaration */: {
              if (compilerOptions.verbatimModuleSyntax) {
                Debug.assertIsDefined(node.name, "An ImportClause with a symbol should have a name");
                const message = compilerOptions.verbatimModuleSyntax && isInternalModuleImportEqualsDeclaration(node) ? Diagnostics.An_import_alias_cannot_resolve_to_a_type_or_type_only_declaration_when_verbatimModuleSyntax_is_enabled : isType ? Diagnostics._0_is_a_type_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_imported_using_a_type_only_import_when_verbatimModuleSyntax_is_enabled;
                const name = moduleExportNameTextUnescaped(node.kind === 276 /* ImportSpecifier */ ? node.propertyName || node.name : node.name);
                addTypeOnlyDeclarationRelatedInfo(
                  error(node, message, name),
                  isType ? void 0 : typeOnlyAlias,
                  name
                );
              }
              if (isType && node.kind === 271 /* ImportEqualsDeclaration */ && hasEffectiveModifier(node, 32 /* Export */)) {
                error(node, Diagnostics.Cannot_use_export_import_on_a_type_or_type_only_namespace_when_0_is_enabled, isolatedModulesLikeFlagName);
              }
              break;
            }
            case 281 /* ExportSpecifier */: {
              if (compilerOptions.verbatimModuleSyntax || getSourceFileOfNode(typeOnlyAlias) !== getSourceFileOfNode(node)) {
                const name = moduleExportNameTextUnescaped(node.propertyName || node.name);
                const diagnostic = isType ? error(node, Diagnostics.Re_exporting_a_type_when_0_is_enabled_requires_using_export_type, isolatedModulesLikeFlagName) : error(node, Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_re_exported_using_a_type_only_re_export_when_1_is_enabled, name, isolatedModulesLikeFlagName);
                addTypeOnlyDeclarationRelatedInfo(diagnostic, isType ? void 0 : typeOnlyAlias, name);
                break;
              }
            }
          }
        }
        if (compilerOptions.verbatimModuleSyntax && node.kind !== 271 /* ImportEqualsDeclaration */ && !isInJSFile(node) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) {
          error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
        } else if (moduleKind === 200 /* Preserve */ && node.kind !== 271 /* ImportEqualsDeclaration */ && node.kind !== 260 /* VariableDeclaration */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) {
          error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_module_is_set_to_preserve);
        }
        if (compilerOptions.verbatimModuleSyntax && !isTypeOnlyImportOrExportDeclaration(node) && !(node.flags & 33554432 /* Ambient */) && targetFlags & 128 /* ConstEnum */) {
          const constEnumDeclaration = target.valueDeclaration;
          const redirect = host.getRedirectReferenceForResolutionFromSourceOfProject(getSourceFileOfNode(constEnumDeclaration).resolvedPath);
          if (constEnumDeclaration.flags & 33554432 /* Ambient */ && (!redirect || !shouldPreserveConstEnums(redirect.commandLine.options))) {
            error(node, Diagnostics.Cannot_access_ambient_const_enums_when_0_is_enabled, isolatedModulesLikeFlagName);
          }
        }
      }
      if (isImportSpecifier(node)) {
        const targetSymbol = resolveAliasWithDeprecationCheck(symbol, node);
        if (isDeprecatedSymbol(targetSymbol) && targetSymbol.declarations) {
          addDeprecatedSuggestion(node, targetSymbol.declarations, targetSymbol.escapedName);
        }
      }
    }
  }
  function resolveAliasWithDeprecationCheck(symbol, location) {
    if (!(symbol.flags & 2097152 /* Alias */) || isDeprecatedSymbol(symbol) || !getDeclarationOfAliasSymbol(symbol)) {
      return symbol;
    }
    const targetSymbol = resolveAlias(symbol);
    if (targetSymbol === unknownSymbol) return targetSymbol;
    while (symbol.flags & 2097152 /* Alias */) {
      const target = getImmediateAliasedSymbol(symbol);
      if (target) {
        if (target === targetSymbol) break;
        if (target.declarations && length(target.declarations)) {
          if (isDeprecatedSymbol(target)) {
            addDeprecatedSuggestion(location, target.declarations, target.escapedName);
            break;
          } else {
            if (symbol === targetSymbol) break;
            symbol = target;
          }
        }
      } else {
        break;
      }
    }
    return targetSymbol;
  }
  function checkImportBinding(node) {
    checkCollisionsForDeclarationName(node, node.name);
    checkAliasSymbol(node);
    if (node.kind === 276 /* ImportSpecifier */) {
      checkModuleExportName(node.propertyName);
      if (moduleExportNameIsDefault(node.propertyName || node.name) && getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) {
        checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
      }
    }
  }
  function checkImportAttributes(declaration) {
    var _a;
    const node = declaration.attributes;
    if (node) {
      const importAttributesType = getGlobalImportAttributesType(
        /*reportErrors*/
        true
      );
      if (importAttributesType !== emptyObjectType) {
        checkTypeAssignableTo(getTypeFromImportAttributes(node), getNullableType(importAttributesType, 32768 /* Undefined */), node);
      }
      const validForTypeAttributes = isExclusivelyTypeOnlyImportOrExport(declaration);
      const override = getResolutionModeOverride(node, validForTypeAttributes ? grammarErrorOnNode : void 0);
      const isImportAttributes2 = declaration.attributes.token === 118 /* WithKeyword */;
      if (validForTypeAttributes && override) {
        return;
      }
      const mode = moduleKind === 199 /* NodeNext */ && declaration.moduleSpecifier && getEmitSyntaxForModuleSpecifierExpression(declaration.moduleSpecifier);
      if (mode !== 99 /* ESNext */ && moduleKind !== 99 /* ESNext */ && moduleKind !== 200 /* Preserve */) {
        const message = isImportAttributes2 ? moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_attributes_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_attributes_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve : moduleKind === 199 /* NodeNext */ ? Diagnostics.Import_assertions_are_not_allowed_on_statements_that_compile_to_CommonJS_require_calls : Diagnostics.Import_assertions_are_only_supported_when_the_module_option_is_set_to_esnext_nodenext_or_preserve;
        return grammarErrorOnNode(node, message);
      }
      const isTypeOnly = isJSDocImportTag(declaration) || (isImportDeclaration(declaration) ? (_a = declaration.importClause) == null ? void 0 : _a.isTypeOnly : declaration.isTypeOnly);
      if (isTypeOnly) {
        return grammarErrorOnNode(node, isImportAttributes2 ? Diagnostics.Import_attributes_cannot_be_used_with_type_only_imports_or_exports : Diagnostics.Import_assertions_cannot_be_used_with_type_only_imports_or_exports);
      }
      if (override) {
        return grammarErrorOnNode(node, Diagnostics.resolution_mode_can_only_be_set_for_type_only_imports);
      }
    }
  }
  function checkImportAttribute(node) {
    return getRegularTypeOfLiteralType(checkExpressionCached(node.value));
  }
  function checkImportDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    if (!checkGrammarModifiers(node) && node.modifiers) {
      grammarErrorOnFirstToken(node, Diagnostics.An_import_declaration_cannot_have_modifiers);
    }
    if (checkExternalImportOrExportDeclaration(node)) {
      let resolvedModule;
      const importClause = node.importClause;
      if (importClause && !checkGrammarImportClause(importClause)) {
        if (importClause.name) {
          checkImportBinding(importClause);
        }
        if (importClause.namedBindings) {
          if (importClause.namedBindings.kind === 274 /* NamespaceImport */) {
            checkImportBinding(importClause.namedBindings);
            if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && getESModuleInterop(compilerOptions)) {
              checkExternalEmitHelpers(node, 65536 /* ImportStar */);
            }
          } else {
            resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
            if (resolvedModule) {
              forEach(importClause.namedBindings.elements, checkImportBinding);
            }
          }
        }
        if (!importClause.isTypeOnly && moduleKind === 199 /* NodeNext */ && isOnlyImportableAsDefault(node.moduleSpecifier, resolvedModule) && !hasTypeJsonImportAttribute(node)) {
          error(node.moduleSpecifier, Diagnostics.Importing_a_JSON_file_into_an_ECMAScript_module_requires_a_type_Colon_json_import_attribute_when_module_is_set_to_0, ModuleKind[moduleKind]);
        }
      } else if (noUncheckedSideEffectImports && !importClause) {
        void resolveExternalModuleName(node, node.moduleSpecifier);
      }
    }
    checkImportAttributes(node);
  }
  function hasTypeJsonImportAttribute(node) {
    return !!node.attributes && node.attributes.elements.some((attr) => {
      var _a;
      return getTextOfIdentifierOrLiteral(attr.name) === "type" && ((_a = tryCast(attr.value, isStringLiteralLike)) == null ? void 0 : _a.text) === "json";
    });
  }
  function checkImportEqualsDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_import_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    checkGrammarModifiers(node);
    if (isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
      checkImportBinding(node);
      markLinkedReferences(node, 6 /* ExportImportEquals */);
      if (node.moduleReference.kind !== 283 /* ExternalModuleReference */) {
        const target = resolveAlias(getSymbolOfDeclaration(node));
        if (target !== unknownSymbol) {
          const targetFlags = getSymbolFlags(target);
          if (targetFlags & 111551 /* Value */) {
            const moduleName = getFirstIdentifier(node.moduleReference);
            if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
              error(moduleName, Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, declarationNameToString(moduleName));
            }
          }
          if (targetFlags & 788968 /* Type */) {
            checkTypeNameIsReserved(node.name, Diagnostics.Import_name_cannot_be_0);
          }
        }
        if (node.isTypeOnly) {
          grammarErrorOnNode(node, Diagnostics.An_import_alias_cannot_use_import_type);
        }
      } else {
        if (5 /* ES2015 */ <= moduleKind && moduleKind <= 99 /* ESNext */ && !node.isTypeOnly && !(node.flags & 33554432 /* Ambient */)) {
          grammarErrorOnNode(node, Diagnostics.Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_ns_from_mod_import_a_from_mod_import_d_from_mod_or_another_module_format_instead);
        }
      }
    }
  }
  function checkExportDeclaration(node) {
    if (checkGrammarModuleElementContext(node, isInJSFile(node) ? Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_module : Diagnostics.An_export_declaration_can_only_be_used_at_the_top_level_of_a_namespace_or_module)) {
      return;
    }
    if (!checkGrammarModifiers(node) && hasSyntacticModifiers(node)) {
      grammarErrorOnFirstToken(node, Diagnostics.An_export_declaration_cannot_have_modifiers);
    }
    checkGrammarExportDeclaration(node);
    if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
      if (node.exportClause && !isNamespaceExport(node.exportClause)) {
        forEach(node.exportClause.elements, checkExportSpecifier);
        const inAmbientExternalModule = node.parent.kind === 268 /* ModuleBlock */ && isAmbientModule(node.parent.parent);
        const inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 268 /* ModuleBlock */ && !node.moduleSpecifier && node.flags & 33554432 /* Ambient */;
        if (node.parent.kind !== 307 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
          error(node, Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
        }
      } else {
        const moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
        if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
          error(node.moduleSpecifier, Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
        } else if (node.exportClause) {
          checkAliasSymbol(node.exportClause);
          checkModuleExportName(node.exportClause.name);
        }
        if (host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */) {
          if (node.exportClause) {
            if (getESModuleInterop(compilerOptions)) {
              checkExternalEmitHelpers(node, 65536 /* ImportStar */);
            }
          } else {
            checkExternalEmitHelpers(node, 32768 /* ExportStar */);
          }
        }
      }
    }
    checkImportAttributes(node);
  }
  function checkGrammarExportDeclaration(node) {
    var _a;
    if (node.isTypeOnly && ((_a = node.exportClause) == null ? void 0 : _a.kind) === 279 /* NamedExports */) {
      return checkGrammarNamedImportsOrExports(node.exportClause);
    }
    return false;
  }
  function checkGrammarModuleElementContext(node, errorMessage) {
    const isInAppropriateContext = node.parent.kind === 307 /* SourceFile */ || node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 267 /* ModuleDeclaration */;
    if (!isInAppropriateContext) {
      grammarErrorOnFirstToken(node, errorMessage);
    }
    return !isInAppropriateContext;
  }
  function checkExportSpecifier(node) {
    checkAliasSymbol(node);
    const hasModuleSpecifier = node.parent.parent.moduleSpecifier !== void 0;
    checkModuleExportName(node.propertyName, hasModuleSpecifier);
    checkModuleExportName(node.name);
    if (getEmitDeclarations(compilerOptions)) {
      collectLinkedAliases(
        node.propertyName || node.name,
        /*setVisibility*/
        true
      );
    }
    if (!hasModuleSpecifier) {
      const exportedName = node.propertyName || node.name;
      if (exportedName.kind === 11 /* StringLiteral */) {
        return;
      }
      const symbol = resolveName(
        exportedName,
        exportedName.escapedText,
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
        /*nameNotFoundMessage*/
        void 0,
        /*isUse*/
        true
      );
      if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || symbol.declarations && isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
        error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName));
      } else {
        markLinkedReferences(node, 7 /* ExportSpecifier */);
      }
    } else {
      if (getESModuleInterop(compilerOptions) && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) < 4 /* System */ && moduleExportNameIsDefault(node.propertyName || node.name)) {
        checkExternalEmitHelpers(node, 131072 /* ImportDefault */);
      }
    }
  }
  function checkExportAssignment(node) {
    const illegalContextMessage = node.isExportEquals ? Diagnostics.An_export_assignment_must_be_at_the_top_level_of_a_file_or_module_declaration : Diagnostics.A_default_export_must_be_at_the_top_level_of_a_file_or_module_declaration;
    if (checkGrammarModuleElementContext(node, illegalContextMessage)) {
      return;
    }
    const container = node.parent.kind === 307 /* SourceFile */ ? node.parent : node.parent.parent;
    if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) {
      if (node.isExportEquals) {
        error(node, Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
      } else {
        error(node, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
      }
      return;
    }
    if (!checkGrammarModifiers(node) && hasEffectiveModifiers(node)) {
      grammarErrorOnFirstToken(node, Diagnostics.An_export_assignment_cannot_have_modifiers);
    }
    const typeAnnotationNode = getEffectiveTypeAnnotationNode(node);
    if (typeAnnotationNode) {
      checkTypeAssignableTo(checkExpressionCached(node.expression), getTypeFromTypeNode(typeAnnotationNode), node.expression);
    }
    const isIllegalExportDefaultInCJS = !node.isExportEquals && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */;
    if (node.expression.kind === 80 /* Identifier */) {
      const id = node.expression;
      const sym = getExportSymbolOfValueSymbolIfExported(resolveEntityName(
        id,
        -1 /* All */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        node
      ));
      if (sym) {
        markLinkedReferences(node, 3 /* ExportAssignment */);
        const typeOnlyDeclaration = getTypeOnlyAliasDeclaration(sym, 111551 /* Value */);
        if (getSymbolFlags(sym) & 111551 /* Value */) {
          checkExpressionCached(id);
          if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax && typeOnlyDeclaration) {
            error(
              id,
              node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration : Diagnostics.An_export_default_must_reference_a_real_value_when_verbatimModuleSyntax_is_enabled_but_0_resolves_to_a_type_only_declaration,
              idText(id)
            );
          }
        } else if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && compilerOptions.verbatimModuleSyntax) {
          error(
            id,
            node.isExportEquals ? Diagnostics.An_export_declaration_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type : Diagnostics.An_export_default_must_reference_a_value_when_verbatimModuleSyntax_is_enabled_but_0_only_refers_to_a_type,
            idText(id)
          );
        }
        if (!isIllegalExportDefaultInCJS && !(node.flags & 33554432 /* Ambient */) && getIsolatedModules(compilerOptions) && !(sym.flags & 111551 /* Value */)) {
          const nonLocalMeanings = getSymbolFlags(
            sym,
            /*excludeTypeOnlyMeanings*/
            false,
            /*excludeLocalMeanings*/
            true
          );
          if (sym.flags & 2097152 /* Alias */ && nonLocalMeanings & 788968 /* Type */ && !(nonLocalMeanings & 111551 /* Value */) && (!typeOnlyDeclaration || getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node))) {
            error(
              id,
              node.isExportEquals ? Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default,
              idText(id),
              isolatedModulesLikeFlagName
            );
          } else if (typeOnlyDeclaration && getSourceFileOfNode(typeOnlyDeclaration) !== getSourceFileOfNode(node)) {
            addTypeOnlyDeclarationRelatedInfo(
              error(
                id,
                node.isExportEquals ? Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_import_type_where_0_is_imported : Diagnostics._0_resolves_to_a_type_only_declaration_and_must_be_marked_type_only_in_this_file_before_re_exporting_when_1_is_enabled_Consider_using_export_type_0_as_default,
                idText(id),
                isolatedModulesLikeFlagName
              ),
              typeOnlyDeclaration,
              idText(id)
            );
          }
        }
      } else {
        checkExpressionCached(id);
      }
      if (getEmitDeclarations(compilerOptions)) {
        collectLinkedAliases(
          id,
          /*setVisibility*/
          true
        );
      }
    } else {
      checkExpressionCached(node.expression);
    }
    if (isIllegalExportDefaultInCJS) {
      error(node, Diagnostics.ESM_syntax_is_not_allowed_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
    }
    checkExternalModuleExports(container);
    if (node.flags & 33554432 /* Ambient */ && !isEntityNameExpression(node.expression)) {
      grammarErrorOnNode(node.expression, Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
    }
    if (node.isExportEquals) {
      if (moduleKind >= 5 /* ES2015 */ && moduleKind !== 200 /* Preserve */ && (node.flags & 33554432 /* Ambient */ && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) === 99 /* ESNext */ || !(node.flags & 33554432 /* Ambient */) && host.getImpliedNodeFormatForEmit(getSourceFileOfNode(node)) !== 1 /* CommonJS */)) {
        grammarErrorOnNode(node, Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
      } else if (moduleKind === 4 /* System */ && !(node.flags & 33554432 /* Ambient */)) {
        grammarErrorOnNode(node, Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
      }
    }
  }
  function hasExportedMembers(moduleSymbol) {
    return forEachEntry(moduleSymbol.exports, (_, id) => id !== "export=");
  }
  function checkExternalModuleExports(node) {
    const moduleSymbol = getSymbolOfDeclaration(node);
    const links = getSymbolLinks(moduleSymbol);
    if (!links.exportsChecked) {
      const exportEqualsSymbol = moduleSymbol.exports.get("export=");
      if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
        const declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
        if (declaration && !isTopLevelInExternalModuleAugmentation(declaration) && !isInJSFile(declaration)) {
          error(declaration, Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
        }
      }
      const exports2 = getExportsOfModule(moduleSymbol);
      if (exports2) {
        exports2.forEach(({ declarations, flags }, id) => {
          if (id === "__export") {
            return;
          }
          if (flags & (1920 /* Namespace */ | 384 /* Enum */)) {
            return;
          }
          const exportedDeclarationsCount = countWhere(declarations, and(isNotOverloadAndNotAccessor, not(isInterfaceDeclaration)));
          if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
            return;
          }
          if (exportedDeclarationsCount > 1) {
            if (!isDuplicatedCommonJSExport(declarations)) {
              for (const declaration of declarations) {
                if (isNotOverload(declaration)) {
                  diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Cannot_redeclare_exported_variable_0, unescapeLeadingUnderscores(id)));
                }
              }
            }
          }
        });
      }
      links.exportsChecked = true;
    }
  }
  function isDuplicatedCommonJSExport(declarations) {
    return declarations && declarations.length > 1 && declarations.every((d) => isInJSFile(d) && isAccessExpression(d) && (isExportsIdentifier(d.expression) || isModuleExportsAccessExpression(d.expression)));
  }
  function checkSourceElement(node) {
    if (node) {
      const saveCurrentNode = currentNode;
      currentNode = node;
      instantiationCount = 0;
      checkSourceElementWorker(node);
      currentNode = saveCurrentNode;
    }
  }
  function checkSourceElementWorker(node) {
    if (getNodeCheckFlags(node) & 8388608 /* PartiallyTypeChecked */) {
      return;
    }
    if (canHaveJSDoc(node)) {
      forEach(node.jsDoc, ({ comment, tags }) => {
        checkJSDocCommentWorker(comment);
        forEach(tags, (tag) => {
          checkJSDocCommentWorker(tag.comment);
          if (isInJSFile(node)) {
            checkSourceElement(tag);
          }
        });
      });
    }
    const kind = node.kind;
    if (cancellationToken) {
      switch (kind) {
        case 267 /* ModuleDeclaration */:
        case 263 /* ClassDeclaration */:
        case 264 /* InterfaceDeclaration */:
        case 262 /* FunctionDeclaration */:
          cancellationToken.throwIfCancellationRequested();
      }
    }
    if (kind >= 243 /* FirstStatement */ && kind <= 259 /* LastStatement */ && canHaveFlowNode(node) && node.flowNode && !isReachableFlowNode(node.flowNode)) {
      errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, Diagnostics.Unreachable_code_detected);
    }
    switch (kind) {
      case 168 /* TypeParameter */:
        return checkTypeParameter(node);
      case 169 /* Parameter */:
        return checkParameter(node);
      case 172 /* PropertyDeclaration */:
        return checkPropertyDeclaration(node);
      case 171 /* PropertySignature */:
        return checkPropertySignature(node);
      case 185 /* ConstructorType */:
      case 184 /* FunctionType */:
      case 179 /* CallSignature */:
      case 180 /* ConstructSignature */:
      case 181 /* IndexSignature */:
        return checkSignatureDeclaration(node);
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        return checkMethodDeclaration(node);
      case 175 /* ClassStaticBlockDeclaration */:
        return checkClassStaticBlockDeclaration(node);
      case 176 /* Constructor */:
        return checkConstructorDeclaration(node);
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        return checkAccessorDeclaration(node);
      case 183 /* TypeReference */:
        return checkTypeReferenceNode(node);
      case 182 /* TypePredicate */:
        return checkTypePredicate(node);
      case 186 /* TypeQuery */:
        return checkTypeQuery(node);
      case 187 /* TypeLiteral */:
        return checkTypeLiteral(node);
      case 188 /* ArrayType */:
        return checkArrayType(node);
      case 189 /* TupleType */:
        return checkTupleType(node);
      case 192 /* UnionType */:
      case 193 /* IntersectionType */:
        return checkUnionOrIntersectionType(node);
      case 196 /* ParenthesizedType */:
      case 190 /* OptionalType */:
      case 191 /* RestType */:
        return checkSourceElement(node.type);
      case 197 /* ThisType */:
        return checkThisType(node);
      case 198 /* TypeOperator */:
        return checkTypeOperator(node);
      case 194 /* ConditionalType */:
        return checkConditionalType(node);
      case 195 /* InferType */:
        return checkInferType(node);
      case 203 /* TemplateLiteralType */:
        return checkTemplateLiteralType(node);
      case 205 /* ImportType */:
        return checkImportType(node);
      case 202 /* NamedTupleMember */:
        return checkNamedTupleMember(node);
      case 328 /* JSDocAugmentsTag */:
        return checkJSDocAugmentsTag(node);
      case 329 /* JSDocImplementsTag */:
        return checkJSDocImplementsTag(node);
      case 346 /* JSDocTypedefTag */:
      case 338 /* JSDocCallbackTag */:
      case 340 /* JSDocEnumTag */:
        return checkJSDocTypeAliasTag(node);
      case 345 /* JSDocTemplateTag */:
        return checkJSDocTemplateTag(node);
      case 344 /* JSDocTypeTag */:
        return checkJSDocTypeTag(node);
      case 324 /* JSDocLink */:
      case 325 /* JSDocLinkCode */:
      case 326 /* JSDocLinkPlain */:
        return checkJSDocLinkLikeTag(node);
      case 341 /* JSDocParameterTag */:
        return checkJSDocParameterTag(node);
      case 348 /* JSDocPropertyTag */:
        return checkJSDocPropertyTag(node);
      case 317 /* JSDocFunctionType */:
        checkJSDocFunctionType(node);
      // falls through
      case 315 /* JSDocNonNullableType */:
      case 314 /* JSDocNullableType */:
      case 312 /* JSDocAllType */:
      case 313 /* JSDocUnknownType */:
      case 322 /* JSDocTypeLiteral */:
        checkJSDocTypeIsInJsFile(node);
        forEachChild(node, checkSourceElement);
        return;
      case 318 /* JSDocVariadicType */:
        checkJSDocVariadicType(node);
        return;
      case 309 /* JSDocTypeExpression */:
        return checkSourceElement(node.type);
      case 333 /* JSDocPublicTag */:
      case 335 /* JSDocProtectedTag */:
      case 334 /* JSDocPrivateTag */:
        return checkJSDocAccessibilityModifiers(node);
      case 350 /* JSDocSatisfiesTag */:
        return checkJSDocSatisfiesTag(node);
      case 343 /* JSDocThisTag */:
        return checkJSDocThisTag(node);
      case 351 /* JSDocImportTag */:
        return checkJSDocImportTag(node);
      case 199 /* IndexedAccessType */:
        return checkIndexedAccessType(node);
      case 200 /* MappedType */:
        return checkMappedType(node);
      case 262 /* FunctionDeclaration */:
        return checkFunctionDeclaration(node);
      case 241 /* Block */:
      case 268 /* ModuleBlock */:
        return checkBlock(node);
      case 243 /* VariableStatement */:
        return checkVariableStatement(node);
      case 244 /* ExpressionStatement */:
        return checkExpressionStatement(node);
      case 245 /* IfStatement */:
        return checkIfStatement(node);
      case 246 /* DoStatement */:
        return checkDoStatement(node);
      case 247 /* WhileStatement */:
        return checkWhileStatement(node);
      case 248 /* ForStatement */:
        return checkForStatement(node);
      case 249 /* ForInStatement */:
        return checkForInStatement(node);
      case 250 /* ForOfStatement */:
        return checkForOfStatement(node);
      case 251 /* ContinueStatement */:
      case 252 /* BreakStatement */:
        return checkBreakOrContinueStatement(node);
      case 253 /* ReturnStatement */:
        return checkReturnStatement(node);
      case 254 /* WithStatement */:
        return checkWithStatement(node);
      case 255 /* SwitchStatement */:
        return checkSwitchStatement(node);
      case 256 /* LabeledStatement */:
        return checkLabeledStatement(node);
      case 257 /* ThrowStatement */:
        return checkThrowStatement(node);
      case 258 /* TryStatement */:
        return checkTryStatement(node);
      case 260 /* VariableDeclaration */:
        return checkVariableDeclaration(node);
      case 208 /* BindingElement */:
        return checkBindingElement(node);
      case 263 /* ClassDeclaration */:
        return checkClassDeclaration(node);
      case 264 /* InterfaceDeclaration */:
        return checkInterfaceDeclaration(node);
      case 265 /* TypeAliasDeclaration */:
        return checkTypeAliasDeclaration(node);
      case 266 /* EnumDeclaration */:
        return checkEnumDeclaration(node);
      case 267 /* ModuleDeclaration */:
        return checkModuleDeclaration(node);
      case 272 /* ImportDeclaration */:
        return checkImportDeclaration(node);
      case 271 /* ImportEqualsDeclaration */:
        return checkImportEqualsDeclaration(node);
      case 278 /* ExportDeclaration */:
        return checkExportDeclaration(node);
      case 277 /* ExportAssignment */:
        return checkExportAssignment(node);
      case 242 /* EmptyStatement */:
      case 259 /* DebuggerStatement */:
        checkGrammarStatementInAmbientContext(node);
        return;
      case 282 /* MissingDeclaration */:
        return checkMissingDeclaration(node);
    }
  }
  function checkJSDocCommentWorker(node) {
    if (isArray(node)) {
      forEach(node, (tag) => {
        if (isJSDocLinkLike(tag)) {
          checkSourceElement(tag);
        }
      });
    }
  }
  function checkJSDocTypeIsInJsFile(node) {
    if (!isInJSFile(node)) {
      if (isJSDocNonNullableType(node) || isJSDocNullableType(node)) {
        const token = tokenToString(isJSDocNonNullableType(node) ? 54 /* ExclamationToken */ : 58 /* QuestionToken */);
        const diagnostic = node.postfix ? Diagnostics._0_at_the_end_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1 : Diagnostics._0_at_the_start_of_a_type_is_not_valid_TypeScript_syntax_Did_you_mean_to_write_1;
        const typeNode = node.type;
        const type = getTypeFromTypeNode(typeNode);
        grammarErrorOnNode(
          node,
          diagnostic,
          token,
          typeToString(
            isJSDocNullableType(node) && !(type === neverType || type === voidType) ? getUnionType(append([type, undefinedType], node.postfix ? void 0 : nullType)) : type
          )
        );
      } else {
        grammarErrorOnNode(node, Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
      }
    }
  }
  function checkJSDocVariadicType(node) {
    checkJSDocTypeIsInJsFile(node);
    checkSourceElement(node.type);
    const { parent } = node;
    if (isParameter(parent) && isJSDocFunctionType(parent.parent)) {
      if (last(parent.parent.parameters) !== parent) {
        error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
      }
      return;
    }
    if (!isJSDocTypeExpression(parent)) {
      error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
    }
    const paramTag = node.parent.parent;
    if (!isJSDocParameterTag(paramTag)) {
      error(node, Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
      return;
    }
    const param = getParameterSymbolFromJSDoc(paramTag);
    if (!param) {
      return;
    }
    const host2 = getHostSignatureFromJSDoc(paramTag);
    if (!host2 || last(host2.parameters).symbol !== param) {
      error(node, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
    }
  }
  function getTypeFromJSDocVariadicType(node) {
    const type = getTypeFromTypeNode(node.type);
    const { parent } = node;
    const paramTag = node.parent.parent;
    if (isJSDocTypeExpression(node.parent) && isJSDocParameterTag(paramTag)) {
      const host2 = getHostSignatureFromJSDoc(paramTag);
      const isCallbackTag = isJSDocCallbackTag(paramTag.parent.parent);
      if (host2 || isCallbackTag) {
        const lastParamDeclaration = isCallbackTag ? lastOrUndefined(paramTag.parent.parent.typeExpression.parameters) : lastOrUndefined(host2.parameters);
        const symbol = getParameterSymbolFromJSDoc(paramTag);
        if (!lastParamDeclaration || symbol && lastParamDeclaration.symbol === symbol && isRestParameter(lastParamDeclaration)) {
          return createArrayType(type);
        }
      }
    }
    if (isParameter(parent) && isJSDocFunctionType(parent.parent)) {
      return createArrayType(type);
    }
    return addOptionality(type);
  }
  function checkNodeDeferred(node) {
    const enclosingFile = getSourceFileOfNode(node);
    const links = getNodeLinks(enclosingFile);
    if (!(links.flags & 1 /* TypeChecked */)) {
      links.deferredNodes || (links.deferredNodes = /* @__PURE__ */ new Set());
      links.deferredNodes.add(node);
    } else {
      Debug.assert(!links.deferredNodes, "A type-checked file should have no deferred nodes.");
    }
  }
  function checkDeferredNodes(context) {
    const links = getNodeLinks(context);
    if (links.deferredNodes) {
      links.deferredNodes.forEach(checkDeferredNode);
    }
    links.deferredNodes = void 0;
  }
  function checkDeferredNode(node) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(tracing.Phase.Check, "checkDeferredNode", { kind: node.kind, pos: node.pos, end: node.end, path: node.tracingPath });
    const saveCurrentNode = currentNode;
    currentNode = node;
    instantiationCount = 0;
    switch (node.kind) {
      case 213 /* CallExpression */:
      case 214 /* NewExpression */:
      case 215 /* TaggedTemplateExpression */:
      case 170 /* Decorator */:
      case 286 /* JsxOpeningElement */:
        resolveUntypedCall(node);
        break;
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
        checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
        break;
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
        checkAccessorDeclaration(node);
        break;
      case 231 /* ClassExpression */:
        checkClassExpressionDeferred(node);
        break;
      case 168 /* TypeParameter */:
        checkTypeParameterDeferred(node);
        break;
      case 285 /* JsxSelfClosingElement */:
        checkJsxSelfClosingElementDeferred(node);
        break;
      case 284 /* JsxElement */:
        checkJsxElementDeferred(node);
        break;
      case 216 /* TypeAssertionExpression */:
      case 234 /* AsExpression */:
      case 217 /* ParenthesizedExpression */:
        checkAssertionDeferred(node);
        break;
      case 222 /* VoidExpression */:
        checkExpression(node.expression);
        break;
      case 226 /* BinaryExpression */:
        if (isInstanceOfExpression(node)) {
          resolveUntypedCall(node);
        }
        break;
    }
    currentNode = saveCurrentNode;
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  function checkSourceFile(node, nodesToCheck) {
    var _a, _b;
    (_a = tracing) == null ? void 0 : _a.push(
      tracing.Phase.Check,
      nodesToCheck ? "checkSourceFileNodes" : "checkSourceFile",
      { path: node.path },
      /*separateBeginAndEnd*/
      true
    );
    const beforeMark = nodesToCheck ? "beforeCheckNodes" : "beforeCheck";
    const afterMark = nodesToCheck ? "afterCheckNodes" : "afterCheck";
    mark(beforeMark);
    nodesToCheck ? checkSourceFileNodesWorker(node, nodesToCheck) : checkSourceFileWorker(node);
    mark(afterMark);
    measure("Check", beforeMark, afterMark);
    (_b = tracing) == null ? void 0 : _b.pop();
  }
  function unusedIsError(kind, isAmbient) {
    if (isAmbient) {
      return false;
    }
    switch (kind) {
      case 0 /* Local */:
        return !!compilerOptions.noUnusedLocals;
      case 1 /* Parameter */:
        return !!compilerOptions.noUnusedParameters;
      default:
        return Debug.assertNever(kind);
    }
  }
  function getPotentiallyUnusedIdentifiers(sourceFile) {
    return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || emptyArray;
  }
  function checkSourceFileWorker(node) {
    const links = getNodeLinks(node);
    if (!(links.flags & 1 /* TypeChecked */)) {
      if (skipTypeChecking(node, compilerOptions, host)) {
        return;
      }
      checkGrammarSourceFile(node);
      clear(potentialThisCollisions);
      clear(potentialNewTargetCollisions);
      clear(potentialWeakMapSetCollisions);
      clear(potentialReflectCollisions);
      clear(potentialUnusedRenamedBindingElementsInTypes);
      if (links.flags & 8388608 /* PartiallyTypeChecked */) {
        potentialThisCollisions = links.potentialThisCollisions;
        potentialNewTargetCollisions = links.potentialNewTargetCollisions;
        potentialWeakMapSetCollisions = links.potentialWeakMapSetCollisions;
        potentialReflectCollisions = links.potentialReflectCollisions;
        potentialUnusedRenamedBindingElementsInTypes = links.potentialUnusedRenamedBindingElementsInTypes;
      }
      forEach(node.statements, checkSourceElement);
      checkSourceElement(node.endOfFileToken);
      checkDeferredNodes(node);
      if (isExternalOrCommonJsModule(node)) {
        registerForUnusedIdentifiersCheck(node);
      }
      addLazyDiagnostic(() => {
        if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
          checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), (containingNode, kind, diag2) => {
            if (!containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 33554432 /* Ambient */))) {
              diagnostics.add(diag2);
            }
          });
        }
        if (!node.isDeclarationFile) {
          checkPotentialUncheckedRenamedBindingElementsInTypes();
        }
      });
      if (isExternalOrCommonJsModule(node)) {
        checkExternalModuleExports(node);
      }
      if (potentialThisCollisions.length) {
        forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
        clear(potentialThisCollisions);
      }
      if (potentialNewTargetCollisions.length) {
        forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
        clear(potentialNewTargetCollisions);
      }
      if (potentialWeakMapSetCollisions.length) {
        forEach(potentialWeakMapSetCollisions, checkWeakMapSetCollision);
        clear(potentialWeakMapSetCollisions);
      }
      if (potentialReflectCollisions.length) {
        forEach(potentialReflectCollisions, checkReflectCollision);
        clear(potentialReflectCollisions);
      }
      links.flags |= 1 /* TypeChecked */;
    }
  }
  function checkSourceFileNodesWorker(file, nodes) {
    const links = getNodeLinks(file);
    if (!(links.flags & 1 /* TypeChecked */)) {
      if (skipTypeChecking(file, compilerOptions, host)) {
        return;
      }
      checkGrammarSourceFile(file);
      clear(potentialThisCollisions);
      clear(potentialNewTargetCollisions);
      clear(potentialWeakMapSetCollisions);
      clear(potentialReflectCollisions);
      clear(potentialUnusedRenamedBindingElementsInTypes);
      forEach(nodes, checkSourceElement);
      checkDeferredNodes(file);
      (links.potentialThisCollisions || (links.potentialThisCollisions = [])).push(...potentialThisCollisions);
      (links.potentialNewTargetCollisions || (links.potentialNewTargetCollisions = [])).push(...potentialNewTargetCollisions);
      (links.potentialWeakMapSetCollisions || (links.potentialWeakMapSetCollisions = [])).push(...potentialWeakMapSetCollisions);
      (links.potentialReflectCollisions || (links.potentialReflectCollisions = [])).push(...potentialReflectCollisions);
      (links.potentialUnusedRenamedBindingElementsInTypes || (links.potentialUnusedRenamedBindingElementsInTypes = [])).push(
        ...potentialUnusedRenamedBindingElementsInTypes
      );
      links.flags |= 8388608 /* PartiallyTypeChecked */;
      for (const node of nodes) {
        const nodeLinks2 = getNodeLinks(node);
        nodeLinks2.flags |= 8388608 /* PartiallyTypeChecked */;
      }
    }
  }
  function getDiagnostics(sourceFile, ct, nodesToCheck) {
    try {
      cancellationToken = ct;
      return getDiagnosticsWorker(sourceFile, nodesToCheck);
    } finally {
      cancellationToken = void 0;
    }
  }
  function ensurePendingDiagnosticWorkComplete() {
    for (const cb of deferredDiagnosticsCallbacks) {
      cb();
    }
    deferredDiagnosticsCallbacks = [];
  }
  function checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck) {
    ensurePendingDiagnosticWorkComplete();
    const oldAddLazyDiagnostics = addLazyDiagnostic;
    addLazyDiagnostic = (cb) => cb();
    checkSourceFile(sourceFile, nodesToCheck);
    addLazyDiagnostic = oldAddLazyDiagnostics;
  }
  function getDiagnosticsWorker(sourceFile, nodesToCheck) {
    if (sourceFile) {
      ensurePendingDiagnosticWorkComplete();
      const previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
      const previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
      checkSourceFileWithEagerDiagnostics(sourceFile, nodesToCheck);
      const semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
      if (nodesToCheck) {
        return semanticDiagnostics;
      }
      const currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
      if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
        const deferredGlobalDiagnostics = relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, compareDiagnostics);
        return concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
      } else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
        return concatenate(currentGlobalDiagnostics, semanticDiagnostics);
      }
      return semanticDiagnostics;
    }
    forEach(host.getSourceFiles(), (file) => checkSourceFileWithEagerDiagnostics(file));
    return diagnostics.getDiagnostics();
  }
  function getGlobalDiagnostics() {
    ensurePendingDiagnosticWorkComplete();
    return diagnostics.getGlobalDiagnostics();
  }
  function getSymbolsInScope(location, meaning) {
    if (location.flags & 67108864 /* InWithStatement */) {
      return [];
    }
    const symbols = createSymbolTable();
    let isStaticSymbol = false;
    populateSymbols();
    symbols.delete("this" /* This */);
    return symbolsToArray(symbols);
    function populateSymbols() {
      while (location) {
        if (canHaveLocals(location) && location.locals && !isGlobalSourceFile(location)) {
          copySymbols(location.locals, meaning);
        }
        switch (location.kind) {
          case 307 /* SourceFile */:
            if (!isExternalModule(location)) break;
          // falls through
          case 267 /* ModuleDeclaration */:
            copyLocallyVisibleExportSymbols(getSymbolOfDeclaration(location).exports, meaning & 2623475 /* ModuleMember */);
            break;
          case 266 /* EnumDeclaration */:
            copySymbols(getSymbolOfDeclaration(location).exports, meaning & 8 /* EnumMember */);
            break;
          case 231 /* ClassExpression */:
            const className = location.name;
            if (className) {
              copySymbol(location.symbol, meaning);
            }
          // this fall-through is necessary because we would like to handle
          // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
          // falls through
          case 263 /* ClassDeclaration */:
          case 264 /* InterfaceDeclaration */:
            if (!isStaticSymbol) {
              copySymbols(getMembersOfSymbol(getSymbolOfDeclaration(location)), meaning & 788968 /* Type */);
            }
            break;
          case 218 /* FunctionExpression */:
            const funcName = location.name;
            if (funcName) {
              copySymbol(location.symbol, meaning);
            }
            break;
        }
        if (introducesArgumentsExoticObject(location)) {
          copySymbol(argumentsSymbol, meaning);
        }
        isStaticSymbol = isStatic(location);
        location = location.parent;
      }
      copySymbols(globals, meaning);
    }
    function copySymbol(symbol, meaning2) {
      if (getCombinedLocalAndExportSymbolFlags(symbol) & meaning2) {
        const id = symbol.escapedName;
        if (!symbols.has(id)) {
          symbols.set(id, symbol);
        }
      }
    }
    function copySymbols(source, meaning2) {
      if (meaning2) {
        source.forEach((symbol) => {
          copySymbol(symbol, meaning2);
        });
      }
    }
    function copyLocallyVisibleExportSymbols(source, meaning2) {
      if (meaning2) {
        source.forEach((symbol) => {
          if (!getDeclarationOfKind(symbol, 281 /* ExportSpecifier */) && !getDeclarationOfKind(symbol, 280 /* NamespaceExport */) && symbol.escapedName !== "default" /* Default */) {
            copySymbol(symbol, meaning2);
          }
        });
      }
    }
  }
  function isTypeDeclarationName(name) {
    return name.kind === 80 /* Identifier */ && isTypeDeclaration(name.parent) && getNameOfDeclaration(name.parent) === name;
  }
  function isTypeReferenceIdentifier(node) {
    while (node.parent.kind === 166 /* QualifiedName */) {
      node = node.parent;
    }
    return node.parent.kind === 183 /* TypeReference */;
  }
  function isInNameOfExpressionWithTypeArguments(node) {
    while (node.parent.kind === 211 /* PropertyAccessExpression */) {
      node = node.parent;
    }
    return node.parent.kind === 233 /* ExpressionWithTypeArguments */;
  }
  function forEachEnclosingClass(node, callback) {
    let result;
    let containingClass = getContainingClass(node);
    while (containingClass) {
      if (result = callback(containingClass)) break;
      containingClass = getContainingClass(containingClass);
    }
    return result;
  }
  function isNodeUsedDuringClassInitialization(node) {
    return !!findAncestor(node, (element) => {
      if (isConstructorDeclaration(element) && nodeIsPresent(element.body) || isPropertyDeclaration(element)) {
        return true;
      } else if (isClassLike(element) || isFunctionLikeDeclaration(element)) {
        return "quit";
      }
      return false;
    });
  }
  function isNodeWithinClass(node, classDeclaration) {
    return !!forEachEnclosingClass(node, (n) => n === classDeclaration);
  }
  function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
    while (nodeOnRightSide.parent.kind === 166 /* QualifiedName */) {
      nodeOnRightSide = nodeOnRightSide.parent;
    }
    if (nodeOnRightSide.parent.kind === 271 /* ImportEqualsDeclaration */) {
      return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : void 0;
    }
    if (nodeOnRightSide.parent.kind === 277 /* ExportAssignment */) {
      return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : void 0;
    }
    return void 0;
  }
  function isInRightSideOfImportOrExportAssignment(node) {
    return getLeftSideOfImportEqualsOrExportAssignment(node) !== void 0;
  }
  function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
    const specialPropertyAssignmentKind = getAssignmentDeclarationKind(entityName.parent.parent);
    switch (specialPropertyAssignmentKind) {
      case 1 /* ExportsProperty */:
      case 3 /* PrototypeProperty */:
        return getSymbolOfNode(entityName.parent);
      case 5 /* Property */:
        if (isPropertyAccessExpression(entityName.parent) && getLeftmostAccessExpression(entityName.parent) === entityName) {
          return void 0;
        }
      // falls through
      case 4 /* ThisProperty */:
      case 2 /* ModuleExports */:
        return getSymbolOfDeclaration(entityName.parent.parent);
    }
  }
  function isImportTypeQualifierPart(node) {
    let parent = node.parent;
    while (isQualifiedName(parent)) {
      node = parent;
      parent = parent.parent;
    }
    if (parent && parent.kind === 205 /* ImportType */ && parent.qualifier === node) {
      return parent;
    }
    return void 0;
  }
  function isThisPropertyAndThisTyped(node) {
    if (node.expression.kind === 110 /* ThisKeyword */) {
      const container = getThisContainer(
        node,
        /*includeArrowFunctions*/
        false,
        /*includeClassComputedPropertyName*/
        false
      );
      if (isFunctionLike(container)) {
        const containingLiteral = getContainingObjectLiteral(container);
        if (containingLiteral) {
          const contextualType = getApparentTypeOfContextualType(
            containingLiteral,
            /*contextFlags*/
            void 0
          );
          const type = getThisTypeOfObjectLiteralFromContextualType(containingLiteral, contextualType);
          return type && !isTypeAny(type);
        }
      }
    }
  }
  function getSymbolOfNameOrPropertyAccessExpression(name) {
    if (isDeclarationName(name)) {
      return getSymbolOfNode(name.parent);
    }
    if (isInJSFile(name) && name.parent.kind === 211 /* PropertyAccessExpression */ && name.parent === name.parent.parent.left) {
      if (!isPrivateIdentifier(name) && !isJSDocMemberName(name) && !isThisPropertyAndThisTyped(name.parent)) {
        const specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
        if (specialPropertyAssignmentSymbol) {
          return specialPropertyAssignmentSymbol;
        }
      }
    }
    if (name.parent.kind === 277 /* ExportAssignment */ && isEntityNameExpression(name)) {
      const success = resolveEntityName(
        name,
        /*all meanings*/
        111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */,
        /*ignoreErrors*/
        true
      );
      if (success && success !== unknownSymbol) {
        return success;
      }
    } else if (isEntityName(name) && isInRightSideOfImportOrExportAssignment(name)) {
      const importEqualsDeclaration = getAncestor(name, 271 /* ImportEqualsDeclaration */);
      Debug.assert(importEqualsDeclaration !== void 0);
      return getSymbolOfPartOfRightHandSideOfImportEquals(
        name,
        /*dontResolveAlias*/
        true
      );
    }
    if (isEntityName(name)) {
      const possibleImportNode = isImportTypeQualifierPart(name);
      if (possibleImportNode) {
        getTypeFromTypeNode(possibleImportNode);
        const sym = getNodeLinks(name).resolvedSymbol;
        return sym === unknownSymbol ? void 0 : sym;
      }
    }
    while (isRightSideOfQualifiedNameOrPropertyAccessOrJSDocMemberName(name)) {
      name = name.parent;
    }
    if (isInNameOfExpressionWithTypeArguments(name)) {
      let meaning = 0 /* None */;
      if (name.parent.kind === 233 /* ExpressionWithTypeArguments */) {
        meaning = isPartOfTypeNode(name) ? 788968 /* Type */ : 111551 /* Value */;
        if (isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
          meaning |= 111551 /* Value */;
        }
      } else {
        meaning = 1920 /* Namespace */;
      }
      meaning |= 2097152 /* Alias */;
      const entityNameSymbol = isEntityNameExpression(name) ? resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        true
      ) : void 0;
      if (entityNameSymbol) {
        return entityNameSymbol;
      }
    }
    if (name.parent.kind === 341 /* JSDocParameterTag */) {
      return getParameterSymbolFromJSDoc(name.parent);
    }
    if (name.parent.kind === 168 /* TypeParameter */ && name.parent.parent.kind === 345 /* JSDocTemplateTag */) {
      Debug.assert(!isInJSFile(name));
      const typeParameter = getTypeParameterFromJsDoc(name.parent);
      return typeParameter && typeParameter.symbol;
    }
    if (isExpressionNode(name)) {
      if (nodeIsMissing(name)) {
        return void 0;
      }
      const isJSDoc2 = findAncestor(name, or(isJSDocLinkLike, isJSDocNameReference, isJSDocMemberName));
      const meaning = isJSDoc2 ? 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */ : 111551 /* Value */;
      if (name.kind === 80 /* Identifier */) {
        if (isJSXTagName(name) && isJsxIntrinsicTagName(name)) {
          const symbol = getIntrinsicTagSymbol(name.parent);
          return symbol === unknownSymbol ? void 0 : symbol;
        }
        const result = resolveEntityName(
          name,
          meaning,
          /*ignoreErrors*/
          true,
          /*dontResolveAlias*/
          true,
          getHostSignatureFromJSDoc(name)
        );
        if (!result && isJSDoc2) {
          const container = findAncestor(name, or(isClassLike, isInterfaceDeclaration));
          if (container) {
            return resolveJSDocMemberName(
              name,
              /*ignoreErrors*/
              true,
              getSymbolOfDeclaration(container)
            );
          }
        }
        if (result && isJSDoc2) {
          const container = getJSDocHost(name);
          if (container && isEnumMember(container) && container === result.valueDeclaration) {
            return resolveEntityName(
              name,
              meaning,
              /*ignoreErrors*/
              true,
              /*dontResolveAlias*/
              true,
              getSourceFileOfNode(container)
            ) || result;
          }
        }
        return result;
      } else if (isPrivateIdentifier(name)) {
        return getSymbolForPrivateIdentifierExpression(name);
      } else if (name.kind === 211 /* PropertyAccessExpression */ || name.kind === 166 /* QualifiedName */) {
        const links = getNodeLinks(name);
        if (links.resolvedSymbol) {
          return links.resolvedSymbol;
        }
        if (name.kind === 211 /* PropertyAccessExpression */) {
          checkPropertyAccessExpression(name, 0 /* Normal */);
          if (!links.resolvedSymbol) {
            links.resolvedSymbol = getApplicableIndexSymbol(checkExpressionCached(name.expression), getLiteralTypeFromPropertyName(name.name));
          }
        } else {
          checkQualifiedName(name, 0 /* Normal */);
        }
        if (!links.resolvedSymbol && isJSDoc2 && isQualifiedName(name)) {
          return resolveJSDocMemberName(name);
        }
        return links.resolvedSymbol;
      } else if (isJSDocMemberName(name)) {
        return resolveJSDocMemberName(name);
      }
    } else if (isEntityName(name) && isTypeReferenceIdentifier(name)) {
      const meaning = name.parent.kind === 183 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
      const symbol = resolveEntityName(
        name,
        meaning,
        /*ignoreErrors*/
        false,
        /*dontResolveAlias*/
        true
      );
      return symbol && symbol !== unknownSymbol ? symbol : getUnresolvedSymbolForEntityName(name);
    }
    if (name.parent.kind === 182 /* TypePredicate */) {
      return resolveEntityName(
        name,
        /*meaning*/
        1 /* FunctionScopedVariable */
      );
    }
    return void 0;
  }
  function getApplicableIndexSymbol(type, keyType) {
    const infos = getApplicableIndexInfos(type, keyType);
    if (infos.length && type.members) {
      const symbol = getIndexSymbolFromSymbolTable(resolveStructuredTypeMembers(type).members);
      if (infos === getIndexInfosOfType(type)) {
        return symbol;
      } else if (symbol) {
        const symbolLinks2 = getSymbolLinks(symbol);
        const declarationList = mapDefined(infos, (i) => i.declaration);
        const nodeListId = map(declarationList, getNodeId).join(",");
        if (!symbolLinks2.filteredIndexSymbolCache) {
          symbolLinks2.filteredIndexSymbolCache = /* @__PURE__ */ new Map();
        }
        if (symbolLinks2.filteredIndexSymbolCache.has(nodeListId)) {
          return symbolLinks2.filteredIndexSymbolCache.get(nodeListId);
        } else {
          const copy = createSymbol(131072 /* Signature */, "__index" /* Index */);
          copy.declarations = mapDefined(infos, (i) => i.declaration);
          copy.parent = type.aliasSymbol ? type.aliasSymbol : type.symbol ? type.symbol : getSymbolAtLocation(copy.declarations[0].parent);
          symbolLinks2.filteredIndexSymbolCache.set(nodeListId, copy);
          return copy;
        }
      }
    }
  }
  function resolveJSDocMemberName(name, ignoreErrors, container) {
    if (isEntityName(name)) {
      const meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */;
      let symbol = resolveEntityName(
        name,
        meaning,
        ignoreErrors,
        /*dontResolveAlias*/
        true,
        getHostSignatureFromJSDoc(name)
      );
      if (!symbol && isIdentifier(name) && container) {
        symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(container), name.escapedText, meaning));
      }
      if (symbol) {
        return symbol;
      }
    }
    const left = isIdentifier(name) ? container : resolveJSDocMemberName(name.left, ignoreErrors, container);
    const right = isIdentifier(name) ? name.escapedText : name.right.escapedText;
    if (left) {
      const proto = left.flags & 111551 /* Value */ && getPropertyOfType(getTypeOfSymbol(left), "prototype");
      const t = proto ? getTypeOfSymbol(proto) : getDeclaredTypeOfSymbol(left);
      return getPropertyOfType(t, right);
    }
  }
  function getSymbolAtLocation(node, ignoreErrors) {
    if (isSourceFile(node)) {
      return isExternalModule(node) ? getMergedSymbol(node.symbol) : void 0;
    }
    const { parent } = node;
    const grandParent = parent.parent;
    if (node.flags & 67108864 /* InWithStatement */) {
      return void 0;
    }
    if (isDeclarationNameOrImportPropertyName(node)) {
      const parentSymbol = getSymbolOfDeclaration(parent);
      return isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node ? getImmediateAliasedSymbol(parentSymbol) : parentSymbol;
    } else if (isLiteralComputedPropertyDeclarationName(node)) {
      return getSymbolOfDeclaration(parent.parent);
    }
    if (node.kind === 80 /* Identifier */) {
      if (isInRightSideOfImportOrExportAssignment(node)) {
        return getSymbolOfNameOrPropertyAccessExpression(node);
      } else if (parent.kind === 208 /* BindingElement */ && grandParent.kind === 206 /* ObjectBindingPattern */ && node === parent.propertyName) {
        const typeOfPattern = getTypeOfNode(grandParent);
        const propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
        if (propertyDeclaration) {
          return propertyDeclaration;
        }
      } else if (isMetaProperty(parent) && parent.name === node) {
        if (parent.keywordToken === 105 /* NewKeyword */ && idText(node) === "target") {
          return checkNewTargetMetaProperty(parent).symbol;
        }
        if (parent.keywordToken === 102 /* ImportKeyword */ && idText(node) === "meta") {
          return getGlobalImportMetaExpressionType().members.get("meta");
        }
        return void 0;
      }
    }
    switch (node.kind) {
      case 80 /* Identifier */:
      case 81 /* PrivateIdentifier */:
      case 211 /* PropertyAccessExpression */:
      case 166 /* QualifiedName */:
        if (!isThisInTypeQuery(node)) {
          return getSymbolOfNameOrPropertyAccessExpression(node);
        }
      // falls through
      case 110 /* ThisKeyword */:
        const container = getThisContainer(
          node,
          /*includeArrowFunctions*/
          false,
          /*includeClassComputedPropertyName*/
          false
        );
        if (isFunctionLike(container)) {
          const sig = getSignatureFromDeclaration(container);
          if (sig.thisParameter) {
            return sig.thisParameter;
          }
        }
        if (isInExpressionContext(node)) {
          return checkExpression(node).symbol;
        }
      // falls through
      case 197 /* ThisType */:
        return getTypeFromThisTypeNode(node).symbol;
      case 108 /* SuperKeyword */:
        return checkExpression(node).symbol;
      case 137 /* ConstructorKeyword */:
        const constructorDeclaration = node.parent;
        if (constructorDeclaration && constructorDeclaration.kind === 176 /* Constructor */) {
          return constructorDeclaration.parent.symbol;
        }
        return void 0;
      case 11 /* StringLiteral */:
      case 15 /* NoSubstitutionTemplateLiteral */:
        if (isExternalModuleImportEqualsDeclaration(node.parent.parent) && getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node || (node.parent.kind === 272 /* ImportDeclaration */ || node.parent.kind === 278 /* ExportDeclaration */) && node.parent.moduleSpecifier === node || isInJSFile(node) && isJSDocImportTag(node.parent) && node.parent.moduleSpecifier === node || (isInJSFile(node) && isRequireCall(
          node.parent,
          /*requireStringLiteralLikeArgument*/
          false
        ) || isImportCall(node.parent)) || isLiteralTypeNode(node.parent) && isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent) {
          return resolveExternalModuleName(node, node, ignoreErrors);
        }
        if (isCallExpression(parent) && isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
          return getSymbolOfDeclaration(parent);
        }
      // falls through
      case 9 /* NumericLiteral */:
        const objectType = isElementAccessExpression(parent) ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : void 0 : isLiteralTypeNode(parent) && isIndexedAccessTypeNode(grandParent) ? getTypeFromTypeNode(grandParent.objectType) : void 0;
        return objectType && getPropertyOfType(objectType, escapeLeadingUnderscores(node.text));
      case 90 /* DefaultKeyword */:
      case 100 /* FunctionKeyword */:
      case 39 /* EqualsGreaterThanToken */:
      case 86 /* ClassKeyword */:
        return getSymbolOfNode(node.parent);
      case 205 /* ImportType */:
        return isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : void 0;
      case 95 /* ExportKeyword */:
        return isExportAssignment(node.parent) ? Debug.checkDefined(node.parent.symbol) : void 0;
      case 102 /* ImportKeyword */:
      case 105 /* NewKeyword */:
        return isMetaProperty(node.parent) ? checkMetaPropertyKeyword(node.parent).symbol : void 0;
      case 104 /* InstanceOfKeyword */:
        if (isBinaryExpression(node.parent)) {
          const type = getTypeOfExpression(node.parent.right);
          const hasInstanceMethodType = getSymbolHasInstanceMethodOfObjectType(type);
          return (hasInstanceMethodType == null ? void 0 : hasInstanceMethodType.symbol) ?? type.symbol;
        }
        return void 0;
      case 236 /* MetaProperty */:
        return checkExpression(node).symbol;
      case 295 /* JsxNamespacedName */:
        if (isJSXTagName(node) && isJsxIntrinsicTagName(node)) {
          const symbol = getIntrinsicTagSymbol(node.parent);
          return symbol === unknownSymbol ? void 0 : symbol;
        }
      // falls through
      default:
        return void 0;
    }
  }
  function getIndexInfosAtLocation(node) {
    if (isIdentifier(node) && isPropertyAccessExpression(node.parent) && node.parent.name === node) {
      const keyType = getLiteralTypeFromPropertyName(node);
      const objectType = getTypeOfExpression(node.parent.expression);
      const objectTypes = objectType.flags & 1048576 /* Union */ ? objectType.types : [objectType];
      return flatMap(objectTypes, (t) => filter(getIndexInfosOfType(t), (info) => isApplicableIndexType(keyType, info.keyType)));
    }
    return void 0;
  }
  function getShorthandAssignmentValueSymbol(location) {
    if (location && location.kind === 304 /* ShorthandPropertyAssignment */) {
      return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
    }
    return void 0;
  }
  function getExportSpecifierLocalTargetSymbol(node) {
    if (isExportSpecifier(node)) {
      const name = node.propertyName || node.name;
      return node.parent.parent.moduleSpecifier ? getExternalModuleMember(node.parent.parent, node) : name.kind === 11 /* StringLiteral */ ? void 0 : (
        // Skip for invalid syntax like this: export { "x" }
        resolveEntityName(name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)
      );
    } else {
      return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
    }
  }
  function getTypeOfNode(node) {
    if (isSourceFile(node) && !isExternalModule(node)) {
      return errorType;
    }
    if (node.flags & 67108864 /* InWithStatement */) {
      return errorType;
    }
    const classDecl = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
    const classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfDeclaration(classDecl.class));
    if (isPartOfTypeNode(node)) {
      const typeFromTypeNode = getTypeFromTypeNode(node);
      return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
    }
    if (isExpressionNode(node)) {
      return getRegularTypeOfExpression(node);
    }
    if (classType && !classDecl.isImplements) {
      const baseType = firstOrUndefined(getBaseTypes(classType));
      return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
    }
    if (isTypeDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      return getDeclaredTypeOfSymbol(symbol);
    }
    if (isTypeDeclarationName(node)) {
      const symbol = getSymbolAtLocation(node);
      return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
    }
    if (isBindingElement(node)) {
      return getTypeForVariableLikeDeclaration(
        node,
        /*includeOptionality*/
        true,
        0 /* Normal */
      ) || errorType;
    }
    if (isDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      return symbol ? getTypeOfSymbol(symbol) : errorType;
    }
    if (isDeclarationNameOrImportPropertyName(node)) {
      const symbol = getSymbolAtLocation(node);
      if (symbol) {
        return getTypeOfSymbol(symbol);
      }
      return errorType;
    }
    if (isBindingPattern(node)) {
      return getTypeForVariableLikeDeclaration(
        node.parent,
        /*includeOptionality*/
        true,
        0 /* Normal */
      ) || errorType;
    }
    if (isInRightSideOfImportOrExportAssignment(node)) {
      const symbol = getSymbolAtLocation(node);
      if (symbol) {
        const declaredType = getDeclaredTypeOfSymbol(symbol);
        return !isErrorType(declaredType) ? declaredType : getTypeOfSymbol(symbol);
      }
    }
    if (isMetaProperty(node.parent) && node.parent.keywordToken === node.kind) {
      return checkMetaPropertyKeyword(node.parent);
    }
    if (isImportAttributes(node)) {
      return getGlobalImportAttributesType(
        /*reportErrors*/
        false
      );
    }
    return errorType;
  }
  function getTypeOfAssignmentPattern(expr) {
    Debug.assert(expr.kind === 210 /* ObjectLiteralExpression */ || expr.kind === 209 /* ArrayLiteralExpression */);
    if (expr.parent.kind === 250 /* ForOfStatement */) {
      const iteratedType = checkRightHandSideOfForOf(expr.parent);
      return checkDestructuringAssignment(expr, iteratedType || errorType);
    }
    if (expr.parent.kind === 226 /* BinaryExpression */) {
      const iteratedType = getTypeOfExpression(expr.parent.right);
      return checkDestructuringAssignment(expr, iteratedType || errorType);
    }
    if (expr.parent.kind === 303 /* PropertyAssignment */) {
      const node2 = cast(expr.parent.parent, isObjectLiteralExpression);
      const typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node2) || errorType;
      const propertyIndex = indexOfNode(node2.properties, expr.parent);
      return checkObjectLiteralDestructuringPropertyAssignment(node2, typeOfParentObjectLiteral, propertyIndex);
    }
    const node = cast(expr.parent, isArrayLiteralExpression);
    const typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
    const elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
    return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
  }
  function getPropertySymbolOfDestructuringAssignment(location) {
    const typeOfObjectLiteral = getTypeOfAssignmentPattern(cast(location.parent.parent, isAssignmentPattern));
    return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
  }
  function getRegularTypeOfExpression(expr) {
    if (isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
      expr = expr.parent;
    }
    return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
  }
  function getParentTypeOfClassElement(node) {
    const classSymbol = getSymbolOfNode(node.parent);
    return isStatic(node) ? getTypeOfSymbol(classSymbol) : getDeclaredTypeOfSymbol(classSymbol);
  }
  function getClassElementPropertyKeyType(element) {
    const name = element.name;
    switch (name.kind) {
      case 80 /* Identifier */:
        return getStringLiteralType(idText(name));
      case 9 /* NumericLiteral */:
      case 11 /* StringLiteral */:
        return getStringLiteralType(name.text);
      case 167 /* ComputedPropertyName */:
        const nameType = checkComputedPropertyName(name);
        return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
      default:
        return Debug.fail("Unsupported property name.");
    }
  }
  function getAugmentedPropertiesOfType(type) {
    type = getApparentType(type);
    const propsByName = createSymbolTable(getPropertiesOfType(type));
    const functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType : getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType : void 0;
    if (functionType) {
      forEach(getPropertiesOfType(functionType), (p) => {
        if (!propsByName.has(p.escapedName)) {
          propsByName.set(p.escapedName, p);
        }
      });
    }
    return getNamedMembers(propsByName);
  }
  function typeHasCallOrConstructSignatures(type) {
    return getSignaturesOfType(type, 0 /* Call */).length !== 0 || getSignaturesOfType(type, 1 /* Construct */).length !== 0;
  }
  function getRootSymbols(symbol) {
    const roots = getImmediateRootSymbols(symbol);
    return roots ? flatMap(roots, getRootSymbols) : [symbol];
  }
  function getImmediateRootSymbols(symbol) {
    if (getCheckFlags(symbol) & 6 /* Synthetic */) {
      return mapDefined(getSymbolLinks(symbol).containingType.types, (type) => getPropertyOfType(type, symbol.escapedName));
    } else if (symbol.flags & 33554432 /* Transient */) {
      const { links: { leftSpread, rightSpread, syntheticOrigin } } = symbol;
      return leftSpread ? [leftSpread, rightSpread] : syntheticOrigin ? [syntheticOrigin] : singleElementArray(tryGetTarget(symbol));
    }
    return void 0;
  }
  function tryGetTarget(symbol) {
    let target;
    let next = symbol;
    while (next = getSymbolLinks(next).target) {
      target = next;
    }
    return target;
  }
  function isArgumentsLocalBinding(nodeIn) {
    if (isGeneratedIdentifier(nodeIn)) return false;
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (!node) return false;
    const parent = node.parent;
    if (!parent) return false;
    const isPropertyName2 = (isPropertyAccessExpression(parent) || isPropertyAssignment(parent)) && parent.name === node;
    return !isPropertyName2 && getReferencedValueSymbol(node) === argumentsSymbol;
  }
  function isNameOfModuleOrEnumDeclaration(node) {
    return isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
  }
  function getReferencedExportContainer(nodeIn, prefixLocals) {
    var _a;
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (node) {
      let symbol = getReferencedValueSymbol(
        node,
        /*startInDeclarationContainer*/
        isNameOfModuleOrEnumDeclaration(node)
      );
      if (symbol) {
        if (symbol.flags & 1048576 /* ExportValue */) {
          const exportSymbol = getMergedSymbol(symbol.exportSymbol);
          if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
            return void 0;
          }
          symbol = exportSymbol;
        }
        const parentSymbol = getParentOfSymbol(symbol);
        if (parentSymbol) {
          if (parentSymbol.flags & 512 /* ValueModule */ && ((_a = parentSymbol.valueDeclaration) == null ? void 0 : _a.kind) === 307 /* SourceFile */) {
            const symbolFile = parentSymbol.valueDeclaration;
            const referenceFile = getSourceFileOfNode(node);
            const symbolIsUmdExport = symbolFile !== referenceFile;
            return symbolIsUmdExport ? void 0 : symbolFile;
          }
          return findAncestor(node.parent, (n) => isModuleOrEnumDeclaration(n) && getSymbolOfDeclaration(n) === parentSymbol);
        }
      }
    }
  }
  function getReferencedImportDeclaration(nodeIn) {
    const specifier = getIdentifierGeneratedImportReference(nodeIn);
    if (specifier) {
      return specifier;
    }
    const node = getParseTreeNode(nodeIn, isIdentifier);
    if (node) {
      const symbol = getReferencedValueOrAliasSymbol(node);
      if (isNonLocalAlias(
        symbol,
        /*excludes*/
        111551 /* Value */
      ) && !getTypeOnlyAliasDeclaration(symbol, 111551 /* Value */)) {
        return getDeclarationOfAliasSymbol(symbol);
      }
    }
    return void 0;
  }
  function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
    return symbol.valueDeclaration && isBindingElement(symbol.valueDeclaration) && walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 299 /* CatchClause */;
  }
  function isSymbolOfDeclarationWithCollidingName(symbol) {
    if (symbol.flags & 418 /* BlockScoped */ && symbol.valueDeclaration && !isSourceFile(symbol.valueDeclaration)) {
      const links = getSymbolLinks(symbol);
      if (links.isDeclarationWithCollidingName === void 0) {
        const container = getEnclosingBlockScopeContainer(symbol.valueDeclaration);
        if (isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
          if (resolveName(
            container.parent,
            symbol.escapedName,
            111551 /* Value */,
            /*nameNotFoundMessage*/
            void 0,
            /*isUse*/
            false
          )) {
            links.isDeclarationWithCollidingName = true;
          } else if (hasNodeCheckFlag(symbol.valueDeclaration, 16384 /* CapturedBlockScopedBinding */)) {
            const isDeclaredInLoop = hasNodeCheckFlag(symbol.valueDeclaration, 32768 /* BlockScopedBindingInLoop */);
            const inLoopInitializer = isIterationStatement(
              container,
              /*lookInLabeledStatements*/
              false
            );
            const inLoopBodyBlock = container.kind === 241 /* Block */ && isIterationStatement(
              container.parent,
              /*lookInLabeledStatements*/
              false
            );
            links.isDeclarationWithCollidingName = !isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || !inLoopInitializer && !inLoopBodyBlock);
          } else {
            links.isDeclarationWithCollidingName = false;
          }
        }
      }
      return links.isDeclarationWithCollidingName;
    }
    return false;
  }
  function getReferencedDeclarationWithCollidingName(nodeIn) {
    if (!isGeneratedIdentifier(nodeIn)) {
      const node = getParseTreeNode(nodeIn, isIdentifier);
      if (node) {
        const symbol = getReferencedValueSymbol(node);
        if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
          return symbol.valueDeclaration;
        }
      }
    }
    return void 0;
  }
  function isDeclarationWithCollidingName(nodeIn) {
    const node = getParseTreeNode(nodeIn, isDeclaration);
    if (node) {
      const symbol = getSymbolOfDeclaration(node);
      if (symbol) {
        return isSymbolOfDeclarationWithCollidingName(symbol);
      }
    }
    return false;
  }
  function isValueAliasDeclaration(node) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    switch (node.kind) {
      case 271 /* ImportEqualsDeclaration */:
        return isAliasResolvedToValue(getSymbolOfDeclaration(node));
      case 273 /* ImportClause */:
      case 274 /* NamespaceImport */:
      case 276 /* ImportSpecifier */:
      case 281 /* ExportSpecifier */:
        const symbol = getSymbolOfDeclaration(node);
        return !!symbol && isAliasResolvedToValue(
          symbol,
          /*excludeTypeOnlyValues*/
          true
        );
      case 278 /* ExportDeclaration */:
        const exportClause = node.exportClause;
        return !!exportClause && (isNamespaceExport(exportClause) || some(exportClause.elements, isValueAliasDeclaration));
      case 277 /* ExportAssignment */:
        return node.expression && node.expression.kind === 80 /* Identifier */ ? isAliasResolvedToValue(
          getSymbolOfDeclaration(node),
          /*excludeTypeOnlyValues*/
          true
        ) : true;
    }
    return false;
  }
  function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
    const node = getParseTreeNode(nodeIn, isImportEqualsDeclaration);
    if (node === void 0 || node.parent.kind !== 307 /* SourceFile */ || !isInternalModuleImportEqualsDeclaration(node)) {
      return false;
    }
    const isValue = isAliasResolvedToValue(getSymbolOfDeclaration(node));
    return isValue && node.moduleReference && !nodeIsMissing(node.moduleReference);
  }
  function isAliasResolvedToValue(symbol, excludeTypeOnlyValues) {
    if (!symbol) {
      return false;
    }
    const container = getSourceFileOfNode(symbol.valueDeclaration);
    const fileSymbol = container && getSymbolOfDeclaration(container);
    void resolveExternalModuleSymbol(fileSymbol);
    const target = getExportSymbolOfValueSymbolIfExported(resolveAlias(symbol));
    if (target === unknownSymbol) {
      return !excludeTypeOnlyValues || !getTypeOnlyAliasDeclaration(symbol);
    }
    return !!(getSymbolFlags(
      symbol,
      excludeTypeOnlyValues,
      /*excludeLocalMeanings*/
      true
    ) & 111551 /* Value */) && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target));
  }
  function isConstEnumOrConstEnumOnlyModule(s) {
    return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
  }
  function isReferencedAliasDeclaration(node, checkChildren) {
    Debug.assert(canCollectSymbolAliasAccessabilityData);
    if (isAliasSymbolDeclaration(node)) {
      const symbol = getSymbolOfDeclaration(node);
      const links = symbol && getSymbolLinks(symbol);
      if (links == null ? void 0 : links.referenced) {
        return true;
      }
      const target = getSymbolLinks(symbol).aliasTarget;
      if (target && getEffectiveModifierFlags(node) & 32 /* Export */ && getSymbolFlags(target) & 111551 /* Value */ && (shouldPreserveConstEnums(compilerOptions) || !isConstEnumOrConstEnumOnlyModule(target))) {
        return true;
      }
    }
    if (checkChildren) {
      return !!forEachChild(node, (node2) => isReferencedAliasDeclaration(node2, checkChildren));
    }
    return false;
  }
  function isImplementationOfOverload(node) {
    if (nodeIsPresent(node.body)) {
      if (isGetAccessor(node) || isSetAccessor(node)) return false;
      const symbol = getSymbolOfDeclaration(node);
      const signaturesOfSymbol = getSignaturesOfSymbol(symbol);
      return signaturesOfSymbol.length > 1 || // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
      // e.g.: function foo(a: string): string;
      //       function foo(a: any) { // This is implementation of the overloads
      //           return a;
      //       }
      signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node;
    }
    return false;
  }
  function declaredParameterTypeContainsUndefined(parameter) {
    const typeNode = getNonlocalEffectiveTypeAnnotationNode(parameter);
    if (!typeNode) return false;
    const type = getTypeFromTypeNode(typeNode);
    return isErrorType(type) || containsUndefinedType(type);
  }
  function requiresAddingImplicitUndefined(parameter, enclosingDeclaration) {
    return (isRequiredInitializedParameter(parameter, enclosingDeclaration) || isOptionalUninitializedParameterProperty(parameter)) && !declaredParameterTypeContainsUndefined(parameter);
  }
  function isRequiredInitializedParameter(parameter, enclosingDeclaration) {
    if (!strictNullChecks || isOptionalParameter(parameter) || isJSDocParameterTag(parameter) || !parameter.initializer) {
      return false;
    }
    if (hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */)) {
      return !!enclosingDeclaration && isFunctionLikeDeclaration(enclosingDeclaration);
    }
    return true;
  }
  function isOptionalUninitializedParameterProperty(parameter) {
    return strictNullChecks && isOptionalParameter(parameter) && (isJSDocParameterTag(parameter) || !parameter.initializer) && hasSyntacticModifier(parameter, 31 /* ParameterPropertyModifier */);
  }
  function isExpandoFunctionDeclaration(node) {
    const declaration = getParseTreeNode(node, (n) => isFunctionDeclaration(n) || isVariableDeclaration(n));
    if (!declaration) {
      return false;
    }
    let symbol;
    if (isVariableDeclaration(declaration)) {
      if (declaration.type || !isInJSFile(declaration) && !isVarConstLike2(declaration)) {
        return false;
      }
      const initializer = getDeclaredExpandoInitializer(declaration);
      if (!initializer || !canHaveSymbol(initializer)) {
        return false;
      }
      symbol = getSymbolOfDeclaration(initializer);
    } else {
      symbol = getSymbolOfDeclaration(declaration);
    }
    if (!symbol || !(symbol.flags & 16 /* Function */ | 3 /* Variable */)) {
      return false;
    }
    return !!forEachEntry(getExportsOfSymbol(symbol), (p) => p.flags & 111551 /* Value */ && isExpandoPropertyDeclaration(p.valueDeclaration));
  }
  function getPropertiesOfContainerFunction(node) {
    const declaration = getParseTreeNode(node, isFunctionDeclaration);
    if (!declaration) {
      return emptyArray;
    }
    const symbol = getSymbolOfDeclaration(declaration);
    return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || emptyArray;
  }
  function getNodeCheckFlags(node) {
    var _a;
    const nodeId = node.id || 0;
    if (nodeId < 0 || nodeId >= nodeLinks.length) return 0;
    return ((_a = nodeLinks[nodeId]) == null ? void 0 : _a.flags) || 0;
  }
  function hasNodeCheckFlag(node, flag) {
    calculateNodeCheckFlagWorker(node, flag);
    return !!(getNodeCheckFlags(node) & flag);
  }
  function calculateNodeCheckFlagWorker(node, flag) {
    if (!compilerOptions.noCheck && canIncludeBindAndCheckDiagnostics(getSourceFileOfNode(node), compilerOptions)) {
      return;
    }
    const links = getNodeLinks(node);
    if (links.calculatedFlags & flag) {
      return;
    }
    switch (flag) {
      case 16 /* SuperInstance */:
      case 32 /* SuperStatic */:
        return checkSingleSuperExpression(node);
      case 128 /* MethodWithSuperPropertyAccessInAsync */:
      case 256 /* MethodWithSuperPropertyAssignmentInAsync */:
      case 2097152 /* ContainsSuperPropertyInStaticInitializer */:
        return checkChildSuperExpressions(node);
      case 512 /* CaptureArguments */:
      case 8192 /* ContainsCapturedBlockScopeBinding */:
      case 65536 /* NeedsLoopOutParameter */:
      case 262144 /* ContainsConstructorReference */:
        return checkChildIdentifiers(node);
      case 536870912 /* ConstructorReference */:
        return checkSingleIdentifier(node);
      case 4096 /* LoopWithCapturedBlockScopedBinding */:
      case 32768 /* BlockScopedBindingInLoop */:
      case 16384 /* CapturedBlockScopedBinding */:
        return checkContainingBlockScopeBindingUses(node);
      default:
        return Debug.assertNever(flag, `Unhandled node check flag calculation: ${Debug.formatNodeCheckFlags(flag)}`);
    }
    function forEachNodeRecursively(root, cb) {
      const rootResult = cb(root, root.parent);
      if (rootResult === "skip") return void 0;
      if (rootResult) return rootResult;
      return forEachChildRecursively(root, cb);
    }
    function checkSuperExpressions(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= 128 /* MethodWithSuperPropertyAccessInAsync */ | 256 /* MethodWithSuperPropertyAssignmentInAsync */ | 2097152 /* ContainsSuperPropertyInStaticInitializer */;
      checkSingleSuperExpression(node2);
      return void 0;
    }
    function checkChildSuperExpressions(node2) {
      forEachNodeRecursively(node2, checkSuperExpressions);
    }
    function checkSingleSuperExpression(node2) {
      const nodeLinks2 = getNodeLinks(node2);
      nodeLinks2.calculatedFlags |= 16 /* SuperInstance */ | 32 /* SuperStatic */;
      if (node2.kind === 108 /* SuperKeyword */) {
        checkSuperExpression(node2);
      }
    }
    function checkIdentifiers(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= 512 /* CaptureArguments */ | 8192 /* ContainsCapturedBlockScopeBinding */ | 65536 /* NeedsLoopOutParameter */ | 262144 /* ContainsConstructorReference */;
      checkSingleIdentifier(node2);
      return void 0;
    }
    function checkChildIdentifiers(node2) {
      forEachNodeRecursively(node2, checkIdentifiers);
    }
    function isExpressionNodeOrShorthandPropertyAssignmentName(node2) {
      return isExpressionNode(node2) || isShorthandPropertyAssignment(node2.parent) && (node2.parent.objectAssignmentInitializer ?? node2.parent.name) === node2;
    }
    function checkSingleIdentifier(node2) {
      const nodeLinks2 = getNodeLinks(node2);
      nodeLinks2.calculatedFlags |= 536870912 /* ConstructorReference */;
      if (isIdentifier(node2)) {
        nodeLinks2.calculatedFlags |= 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */;
        if (isExpressionNodeOrShorthandPropertyAssignmentName(node2) && !(isPropertyAccessExpression(node2.parent) && node2.parent.name === node2)) {
          const s = getResolvedSymbol(node2);
          if (s && s !== unknownSymbol) {
            checkIdentifierCalculateNodeCheckFlags(node2, s);
          }
        }
      }
    }
    function checkBlockScopeBindings(node2) {
      const links2 = getNodeLinks(node2);
      if (links2.calculatedFlags & flag) return "skip";
      links2.calculatedFlags |= 4096 /* LoopWithCapturedBlockScopedBinding */ | 32768 /* BlockScopedBindingInLoop */ | 16384 /* CapturedBlockScopedBinding */;
      checkSingleBlockScopeBinding(node2);
      return void 0;
    }
    function checkContainingBlockScopeBindingUses(node2) {
      const scope = getEnclosingBlockScopeContainer(isDeclarationName(node2) ? node2.parent : node2);
      forEachNodeRecursively(scope, checkBlockScopeBindings);
    }
    function checkSingleBlockScopeBinding(node2) {
      checkSingleIdentifier(node2);
      if (isComputedPropertyName(node2)) {
        checkComputedPropertyName(node2);
      }
      if (isPrivateIdentifier(node2) && isClassElement(node2.parent)) {
        setNodeLinksForPrivateIdentifierScope(node2.parent);
      }
    }
  }
  function getEnumMemberValue(node) {
    computeEnumMemberValues(node.parent);
    return getNodeLinks(node).enumMemberValue ?? evaluatorResult(
      /*value*/
      void 0
    );
  }
  function canHaveConstantValue(node) {
    switch (node.kind) {
      case 306 /* EnumMember */:
      case 211 /* PropertyAccessExpression */:
      case 212 /* ElementAccessExpression */:
        return true;
    }
    return false;
  }
  function getConstantValue2(node) {
    if (node.kind === 306 /* EnumMember */) {
      return getEnumMemberValue(node).value;
    }
    if (!getNodeLinks(node).resolvedSymbol) {
      void checkExpressionCached(node);
    }
    const symbol = getNodeLinks(node).resolvedSymbol || (isEntityNameExpression(node) ? resolveEntityName(
      node,
      111551 /* Value */,
      /*ignoreErrors*/
      true
    ) : void 0);
    if (symbol && symbol.flags & 8 /* EnumMember */) {
      const member = symbol.valueDeclaration;
      if (isEnumConst(member.parent)) {
        return getEnumMemberValue(member).value;
      }
    }
    return void 0;
  }
  function isFunctionType(type) {
    return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
  }
  function getTypeReferenceSerializationKind(typeNameIn, location) {
    var _a;
    const typeName = getParseTreeNode(typeNameIn, isEntityName);
    if (!typeName) return 0 /* Unknown */;
    if (location) {
      location = getParseTreeNode(location);
      if (!location) return 0 /* Unknown */;
    }
    let isTypeOnly = false;
    if (isQualifiedName(typeName)) {
      const rootValueSymbol = resolveEntityName(
        getFirstIdentifier(typeName),
        111551 /* Value */,
        /*ignoreErrors*/
        true,
        /*dontResolveAlias*/
        true,
        location
      );
      isTypeOnly = !!((_a = rootValueSymbol == null ? void 0 : rootValueSymbol.declarations) == null ? void 0 : _a.every(isTypeOnlyImportOrExportDeclaration));
    }
    const valueSymbol = resolveEntityName(
      typeName,
      111551 /* Value */,
      /*ignoreErrors*/
      true,
      /*dontResolveAlias*/
      true,
      location
    );
    const resolvedValueSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol;
    isTypeOnly || (isTypeOnly = !!(valueSymbol && getTypeOnlyAliasDeclaration(valueSymbol, 111551 /* Value */)));
    const typeSymbol = resolveEntityName(
      typeName,
      788968 /* Type */,
      /*ignoreErrors*/
      true,
      /*dontResolveAlias*/
      true,
      location
    );
    const resolvedTypeSymbol = typeSymbol && typeSymbol.flags & 2097152 /* Alias */ ? resolveAlias(typeSymbol) : typeSymbol;
    if (!valueSymbol) {
      isTypeOnly || (isTypeOnly = !!(typeSymbol && getTypeOnlyAliasDeclaration(typeSymbol, 788968 /* Type */)));
    }
    if (resolvedValueSymbol && resolvedValueSymbol === resolvedTypeSymbol) {
      const globalPromiseSymbol = getGlobalPromiseConstructorSymbol(
        /*reportErrors*/
        false
      );
      if (globalPromiseSymbol && resolvedValueSymbol === globalPromiseSymbol) {
        return 9 /* Promise */;
      }
      const constructorType = getTypeOfSymbol(resolvedValueSymbol);
      if (constructorType && isConstructorType(constructorType)) {
        return isTypeOnly ? 10 /* TypeWithCallSignature */ : 1 /* TypeWithConstructSignatureAndValue */;
      }
    }
    if (!resolvedTypeSymbol) {
      return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */;
    }
    const type = getDeclaredTypeOfSymbol(resolvedTypeSymbol);
    if (isErrorType(type)) {
      return isTypeOnly ? 11 /* ObjectType */ : 0 /* Unknown */;
    } else if (type.flags & 3 /* AnyOrUnknown */) {
      return 11 /* ObjectType */;
    } else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
      return 2 /* VoidNullableOrNeverType */;
    } else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
      return 6 /* BooleanType */;
    } else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
      return 3 /* NumberLikeType */;
    } else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
      return 4 /* BigIntLikeType */;
    } else if (isTypeAssignableToKind(type, 402653316 /* StringLike */)) {
      return 5 /* StringLikeType */;
    } else if (isTupleType(type)) {
      return 7 /* ArrayLikeType */;
    } else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
      return 8 /* ESSymbolType */;
    } else if (isFunctionType(type)) {
      return 10 /* TypeWithCallSignature */;
    } else if (isArrayType(type)) {
      return 7 /* ArrayLikeType */;
    } else {
      return 11 /* ObjectType */;
    }
  }
  function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const declaration = getParseTreeNode(declarationIn, hasInferredType);
    if (!declaration) {
      return factory.createToken(133 /* AnyKeyword */);
    }
    const symbol = getSymbolOfDeclaration(declaration);
    return nodeBuilder.serializeTypeForDeclaration(declaration, symbol, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker);
  }
  function getAllAccessorDeclarationsForDeclaration(accessor) {
    accessor = getParseTreeNode(accessor, isGetOrSetAccessorDeclaration);
    const otherKind = accessor.kind === 178 /* SetAccessor */ ? 177 /* GetAccessor */ : 178 /* SetAccessor */;
    const otherAccessor = getDeclarationOfKind(getSymbolOfDeclaration(accessor), otherKind);
    const firstAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? otherAccessor : accessor;
    const secondAccessor = otherAccessor && otherAccessor.pos < accessor.pos ? accessor : otherAccessor;
    const setAccessor = accessor.kind === 178 /* SetAccessor */ ? accessor : otherAccessor;
    const getAccessor = accessor.kind === 177 /* GetAccessor */ ? accessor : otherAccessor;
    return {
      firstAccessor,
      secondAccessor,
      setAccessor,
      getAccessor
    };
  }
  function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const signatureDeclaration = getParseTreeNode(signatureDeclarationIn, isFunctionLike);
    if (!signatureDeclaration) {
      return factory.createToken(133 /* AnyKeyword */);
    }
    return nodeBuilder.serializeReturnTypeForSignature(signatureDeclaration, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker);
  }
  function createTypeOfExpression(exprIn, enclosingDeclaration, flags, internalFlags, tracker) {
    const expr = getParseTreeNode(exprIn, isExpression);
    if (!expr) {
      return factory.createToken(133 /* AnyKeyword */);
    }
    return nodeBuilder.serializeTypeForExpression(expr, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, internalFlags, tracker);
  }
  function hasGlobalName(name) {
    return globals.has(escapeLeadingUnderscores(name));
  }
  function getReferencedValueSymbol(reference, startInDeclarationContainer) {
    const resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
    if (resolvedSymbol) {
      return resolvedSymbol;
    }
    let location = reference;
    if (startInDeclarationContainer) {
      const parent = reference.parent;
      if (isDeclaration(parent) && reference === parent.name) {
        location = getDeclarationContainer(parent);
      }
    }
    return resolveName(
      location,
      reference.escapedText,
      111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true
    );
  }
  function getReferencedValueOrAliasSymbol(reference) {
    const resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
    if (resolvedSymbol && resolvedSymbol !== unknownSymbol) {
      return resolvedSymbol;
    }
    return resolveName(
      reference,
      reference.escapedText,
      111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */,
      /*nameNotFoundMessage*/
      void 0,
      /*isUse*/
      true,
      /*excludeGlobals*/
      void 0
    );
  }
  function getReferencedValueDeclaration(referenceIn) {
    if (!isGeneratedIdentifier(referenceIn)) {
      const reference = getParseTreeNode(referenceIn, isIdentifier);
      if (reference) {
        const symbol = getReferencedValueSymbol(reference);
        if (symbol) {
          return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
        }
      }
    }
    return void 0;
  }
  function getReferencedValueDeclarations(referenceIn) {
    if (!isGeneratedIdentifier(referenceIn)) {
      const reference = getParseTreeNode(referenceIn, isIdentifier);
      if (reference) {
        const symbol = getReferencedValueSymbol(reference);
        if (symbol) {
          return filter(getExportSymbolOfValueSymbolIfExported(symbol).declarations, (declaration) => {
            switch (declaration.kind) {
              case 260 /* VariableDeclaration */:
              case 169 /* Parameter */:
              case 208 /* BindingElement */:
              case 172 /* PropertyDeclaration */:
              case 303 /* PropertyAssignment */:
              case 304 /* ShorthandPropertyAssignment */:
              case 306 /* EnumMember */:
              case 210 /* ObjectLiteralExpression */:
              case 262 /* FunctionDeclaration */:
              case 218 /* FunctionExpression */:
              case 219 /* ArrowFunction */:
              case 263 /* ClassDeclaration */:
              case 231 /* ClassExpression */:
              case 266 /* EnumDeclaration */:
              case 174 /* MethodDeclaration */:
              case 177 /* GetAccessor */:
              case 178 /* SetAccessor */:
              case 267 /* ModuleDeclaration */:
                return true;
            }
            return false;
          });
        }
      }
    }
    return void 0;
  }
  function isLiteralConstDeclaration(node) {
    if (isDeclarationReadonly(node) || isVariableDeclaration(node) && isVarConstLike2(node)) {
      return isFreshLiteralType(getTypeOfSymbol(getSymbolOfDeclaration(node)));
    }
    return false;
  }
  function literalTypeToNode(type, enclosing, tracker) {
    const enumResult = type.flags & 1056 /* EnumLike */ ? nodeBuilder.symbolToExpression(
      type.symbol,
      111551 /* Value */,
      enclosing,
      /*flags*/
      void 0,
      /*internalFlags*/
      void 0,
      tracker
    ) : type === trueType ? factory.createTrue() : type === falseType && factory.createFalse();
    if (enumResult) return enumResult;
    const literalValue = type.value;
    return typeof literalValue === "object" ? factory.createBigIntLiteral(literalValue) : typeof literalValue === "string" ? factory.createStringLiteral(literalValue) : literalValue < 0 ? factory.createPrefixUnaryExpression(41 /* MinusToken */, factory.createNumericLiteral(-literalValue)) : factory.createNumericLiteral(literalValue);
  }
  function createLiteralConstValue(node, tracker) {
    const type = getTypeOfSymbol(getSymbolOfDeclaration(node));
    return literalTypeToNode(type, node, tracker);
  }
  function getJsxFactoryEntity(location) {
    return location ? (getJsxNamespace(location), getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity) : _jsxFactoryEntity;
  }
  function getJsxFragmentFactoryEntity(location) {
    if (location) {
      const file = getSourceFileOfNode(location);
      if (file) {
        if (file.localJsxFragmentFactory) {
          return file.localJsxFragmentFactory;
        }
        const jsxFragPragmas = file.pragmas.get("jsxfrag");
        const jsxFragPragma = isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
        if (jsxFragPragma) {
          file.localJsxFragmentFactory = parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
          return file.localJsxFragmentFactory;
        }
      }
    }
    if (compilerOptions.jsxFragmentFactory) {
      return parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
    }
  }
  function getNonlocalEffectiveTypeAnnotationNode(node) {
    const direct = getEffectiveTypeAnnotationNode(node);
    if (direct) {
      return direct;
    }
    if (node.kind === 169 /* Parameter */ && node.parent.kind === 178 /* SetAccessor */) {
      const other = getAllAccessorDeclarationsForDeclaration(node.parent).getAccessor;
      if (other) {
        return getEffectiveReturnTypeNode(other);
      }
    }
    return void 0;
  }
  function createResolver() {
    return {
      getReferencedExportContainer,
      getReferencedImportDeclaration,
      getReferencedDeclarationWithCollidingName,
      isDeclarationWithCollidingName,
      isValueAliasDeclaration: (nodeIn) => {
        const node = getParseTreeNode(nodeIn);
        return node && canCollectSymbolAliasAccessabilityData ? isValueAliasDeclaration(node) : true;
      },
      hasGlobalName,
      isReferencedAliasDeclaration: (nodeIn, checkChildren) => {
        const node = getParseTreeNode(nodeIn);
        return node && canCollectSymbolAliasAccessabilityData ? isReferencedAliasDeclaration(node, checkChildren) : true;
      },
      hasNodeCheckFlag: (nodeIn, flag) => {
        const node = getParseTreeNode(nodeIn);
        if (!node) return false;
        return hasNodeCheckFlag(node, flag);
      },
      isTopLevelValueImportEqualsWithEntityName,
      isDeclarationVisible,
      isImplementationOfOverload,
      requiresAddingImplicitUndefined,
      isExpandoFunctionDeclaration,
      getPropertiesOfContainerFunction,
      createTypeOfDeclaration,
      createReturnTypeOfSignatureDeclaration,
      createTypeOfExpression,
      createLiteralConstValue,
      isSymbolAccessible,
      isEntityNameVisible,
      getConstantValue: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, canHaveConstantValue);
        return node ? getConstantValue2(node) : void 0;
      },
      getEnumMemberValue: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, isEnumMember);
        return node ? getEnumMemberValue(node) : void 0;
      },
      collectLinkedAliases,
      markLinkedReferences: (nodeIn) => {
        const node = getParseTreeNode(nodeIn);
        return node && markLinkedReferences(node, 0 /* Unspecified */);
      },
      getReferencedValueDeclaration,
      getReferencedValueDeclarations,
      getTypeReferenceSerializationKind,
      isOptionalParameter,
      isArgumentsLocalBinding,
      getExternalModuleFileFromDeclaration: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, hasPossibleExternalModuleReference);
        return node && getExternalModuleFileFromDeclaration(node);
      },
      isLiteralConstDeclaration,
      isLateBound: (nodeIn) => {
        const node = getParseTreeNode(nodeIn, isDeclaration);
        const symbol = node && getSymbolOfDeclaration(node);
        return !!(symbol && getCheckFlags(symbol) & 4096 /* Late */);
      },
      getJsxFactoryEntity,
      getJsxFragmentFactoryEntity,
      isBindingCapturedByNode: (node, decl) => {
        const parseNode = getParseTreeNode(node);
        const parseDecl = getParseTreeNode(decl);
        return !!parseNode && !!parseDecl && (isVariableDeclaration(parseDecl) || isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
      },
      getDeclarationStatementsForSourceFile: (node, flags, internalFlags, tracker) => {
        const n = getParseTreeNode(node);
        Debug.assert(n && n.kind === 307 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
        const sym = getSymbolOfDeclaration(node);
        if (!sym) {
          return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, internalFlags, tracker);
        }
        resolveExternalModuleSymbol(sym);
        return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, internalFlags, tracker);
      },
      isImportRequiredByAugmentation,
      isDefinitelyReferenceToGlobalSymbolObject,
      createLateBoundIndexSignatures: (cls, enclosing, flags, internalFlags, tracker) => {
        const sym = cls.symbol;
        const staticInfos = getIndexInfosOfType(getTypeOfSymbol(sym));
        const instanceIndexSymbol = getIndexSymbol(sym);
        const instanceInfos = instanceIndexSymbol && getIndexInfosOfIndexSymbol(instanceIndexSymbol, arrayFrom(getMembersOfSymbol(sym).values()));
        let result;
        for (const infoList of [staticInfos, instanceInfos]) {
          if (!length(infoList)) continue;
          result || (result = []);
          for (const info of infoList) {
            if (info.declaration) continue;
            if (info === anyBaseTypeIndexInfo) continue;
            const node = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, enclosing, flags, internalFlags, tracker);
            if (node && infoList === staticInfos) {
              (node.modifiers || (node.modifiers = factory.createNodeArray())).unshift(factory.createModifier(126 /* StaticKeyword */));
            }
            if (node) {
              result.push(node);
            }
          }
        }
        return result;
      }
    };
    function isImportRequiredByAugmentation(node) {
      const file = getSourceFileOfNode(node);
      if (!file.symbol) return false;
      const importTarget = getExternalModuleFileFromDeclaration(node);
      if (!importTarget) return false;
      if (importTarget === file) return false;
      const exports2 = getExportsOfModule(file.symbol);
      for (const s of arrayFrom(exports2.values())) {
        if (s.mergeId) {
          const merged = getMergedSymbol(s);
          if (merged.declarations) {
            for (const d of merged.declarations) {
              const declFile = getSourceFileOfNode(d);
              if (declFile === importTarget) {
                return true;
              }
            }
          }
        }
      }
      return false;
    }
  }
  function getExternalModuleFileFromDeclaration(declaration) {
    const specifier = declaration.kind === 267 /* ModuleDeclaration */ ? tryCast(declaration.name, isStringLiteral) : getExternalModuleName(declaration);
    const moduleSymbol = resolveExternalModuleNameWorker(
      specifier,
      specifier,
      /*moduleNotFoundError*/
      void 0
    );
    if (!moduleSymbol) {
      return void 0;
    }
    return getDeclarationOfKind(moduleSymbol, 307 /* SourceFile */);
  }
  function initializeTypeChecker() {
    for (const file of host.getSourceFiles()) {
      bindSourceFile(file, compilerOptions);
    }
    amalgamatedDuplicates = /* @__PURE__ */ new Map();
    let augmentations;
    for (const file of host.getSourceFiles()) {
      if (file.redirectInfo) {
        continue;
      }
      if (!isExternalOrCommonJsModule(file)) {
        const fileGlobalThisSymbol = file.locals.get("globalThis");
        if (fileGlobalThisSymbol == null ? void 0 : fileGlobalThisSymbol.declarations) {
          for (const declaration of fileGlobalThisSymbol.declarations) {
            diagnostics.add(createDiagnosticForNode(declaration, Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
          }
        }
        mergeSymbolTable(globals, file.locals);
      }
      if (file.jsGlobalAugmentations) {
        mergeSymbolTable(globals, file.jsGlobalAugmentations);
      }
      if (file.patternAmbientModules && file.patternAmbientModules.length) {
        patternAmbientModules = concatenate(patternAmbientModules, file.patternAmbientModules);
      }
      if (file.moduleAugmentations.length) {
        (augmentations || (augmentations = [])).push(file.moduleAugmentations);
      }
      if (file.symbol && file.symbol.globalExports) {
        const source = file.symbol.globalExports;
        source.forEach((sourceSymbol, id) => {
          if (!globals.has(id)) {
            globals.set(id, sourceSymbol);
          }
        });
      }
    }
    if (augmentations) {
      for (const list of augmentations) {
        for (const augmentation of list) {
          if (!isGlobalScopeAugmentation(augmentation.parent)) continue;
          mergeModuleAugmentation(augmentation);
        }
      }
    }
    addUndefinedToGlobalsOrErrorOnRedeclaration();
    getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
    getSymbolLinks(argumentsSymbol).type = getGlobalType(
      "IArguments",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    getSymbolLinks(unknownSymbol).type = errorType;
    getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
    globalArrayType = getGlobalType(
      "Array",
      /*arity*/
      1,
      /*reportErrors*/
      true
    );
    globalObjectType = getGlobalType(
      "Object",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalFunctionType = getGlobalType(
      "Function",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalCallableFunctionType = strictBindCallApply && getGlobalType(
      "CallableFunction",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || globalFunctionType;
    globalNewableFunctionType = strictBindCallApply && getGlobalType(
      "NewableFunction",
      /*arity*/
      0,
      /*reportErrors*/
      true
    ) || globalFunctionType;
    globalStringType = getGlobalType(
      "String",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalNumberType = getGlobalType(
      "Number",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalBooleanType = getGlobalType(
      "Boolean",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    globalRegExpType = getGlobalType(
      "RegExp",
      /*arity*/
      0,
      /*reportErrors*/
      true
    );
    anyArrayType = createArrayType(anyType);
    autoArrayType = createArrayType(autoType);
    if (autoArrayType === emptyObjectType) {
      autoArrayType = createAnonymousType(
        /*symbol*/
        void 0,
        emptySymbols,
        emptyArray,
        emptyArray,
        emptyArray
      );
    }
    globalReadonlyArrayType = getGlobalTypeOrUndefined(
      "ReadonlyArray",
      /*arity*/
      1
    ) || globalArrayType;
    anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
    globalThisType = getGlobalTypeOrUndefined(
      "ThisType",
      /*arity*/
      1
    );
    if (augmentations) {
      for (const list of augmentations) {
        for (const augmentation of list) {
          if (isGlobalScopeAugmentation(augmentation.parent)) continue;
          mergeModuleAugmentation(augmentation);
        }
      }
    }
    amalgamatedDuplicates.forEach(({ firstFile, secondFile, conflictingSymbols }) => {
      if (conflictingSymbols.size < 8) {
        conflictingSymbols.forEach(({ isBlockScoped, firstFileLocations, secondFileLocations }, symbolName2) => {
          const message = isBlockScoped ? Diagnostics.Cannot_redeclare_block_scoped_variable_0 : Diagnostics.Duplicate_identifier_0;
          for (const node of firstFileLocations) {
            addDuplicateDeclarationError(node, message, symbolName2, secondFileLocations);
          }
          for (const node of secondFileLocations) {
            addDuplicateDeclarationError(node, message, symbolName2, firstFileLocations);
          }
        });
      } else {
        const list = arrayFrom(conflictingSymbols.keys()).join(", ");
        diagnostics.add(addRelatedInfo(
          createDiagnosticForNode(firstFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list),
          createDiagnosticForNode(secondFile, Diagnostics.Conflicts_are_in_this_file)
        ));
        diagnostics.add(addRelatedInfo(
          createDiagnosticForNode(secondFile, Diagnostics.Definitions_of_the_following_identifiers_conflict_with_those_in_another_file_Colon_0, list),
          createDiagnosticForNode(firstFile, Diagnostics.Conflicts_are_in_this_file)
        ));
      }
    });
    amalgamatedDuplicates = void 0;
  }
  function checkExternalEmitHelpers(location, helpers) {
    if (compilerOptions.importHelpers) {
      const sourceFile = getSourceFileOfNode(location);
      if (isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 33554432 /* Ambient */)) {
        const helpersModule = resolveHelpersModule(sourceFile, location);
        if (helpersModule !== unknownSymbol) {
          const links = getSymbolLinks(helpersModule);
          links.requestedExternalEmitHelpers ?? (links.requestedExternalEmitHelpers = 0);
          if ((links.requestedExternalEmitHelpers & helpers) !== helpers) {
            const uncheckedHelpers = helpers & ~links.requestedExternalEmitHelpers;
            for (let helper = 1 /* FirstEmitHelper */; helper <= 16777216 /* LastEmitHelper */; helper <<= 1) {
              if (uncheckedHelpers & helper) {
                for (const name of getHelperNames(helper)) {
                  const symbol = resolveSymbol(getSymbol(getExportsOfModule(helpersModule), escapeLeadingUnderscores(name), 111551 /* Value */));
                  if (!symbol) {
                    error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_which_does_not_exist_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name);
                  } else if (helper & 524288 /* ClassPrivateFieldGet */) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 3)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 4);
                    }
                  } else if (helper & 1048576 /* ClassPrivateFieldSet */) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 4)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 5);
                    }
                  } else if (helper & 1024 /* SpreadArray */) {
                    if (!some(getSignaturesOfSymbol(symbol), (signature) => getParameterCount(signature) > 2)) {
                      error(location, Diagnostics.This_syntax_requires_an_imported_helper_named_1_with_2_parameters_which_is_not_compatible_with_the_one_in_0_Consider_upgrading_your_version_of_0, externalHelpersModuleNameText, name, 3);
                    }
                  }
                }
              }
            }
          }
          links.requestedExternalEmitHelpers |= helpers;
        }
      }
    }
  }
  function getHelperNames(helper) {
    switch (helper) {
      case 1 /* Extends */:
        return ["__extends"];
      case 2 /* Assign */:
        return ["__assign"];
      case 4 /* Rest */:
        return ["__rest"];
      case 8 /* Decorate */:
        return legacyDecorators ? ["__decorate"] : ["__esDecorate", "__runInitializers"];
      case 16 /* Metadata */:
        return ["__metadata"];
      case 32 /* Param */:
        return ["__param"];
      case 64 /* Awaiter */:
        return ["__awaiter"];
      case 128 /* Generator */:
        return ["__generator"];
      case 256 /* Values */:
        return ["__values"];
      case 512 /* Read */:
        return ["__read"];
      case 1024 /* SpreadArray */:
        return ["__spreadArray"];
      case 2048 /* Await */:
        return ["__await"];
      case 4096 /* AsyncGenerator */:
        return ["__asyncGenerator"];
      case 8192 /* AsyncDelegator */:
        return ["__asyncDelegator"];
      case 16384 /* AsyncValues */:
        return ["__asyncValues"];
      case 32768 /* ExportStar */:
        return ["__exportStar"];
      case 65536 /* ImportStar */:
        return ["__importStar"];
      case 131072 /* ImportDefault */:
        return ["__importDefault"];
      case 262144 /* MakeTemplateObject */:
        return ["__makeTemplateObject"];
      case 524288 /* ClassPrivateFieldGet */:
        return ["__classPrivateFieldGet"];
      case 1048576 /* ClassPrivateFieldSet */:
        return ["__classPrivateFieldSet"];
      case 2097152 /* ClassPrivateFieldIn */:
        return ["__classPrivateFieldIn"];
      case 4194304 /* SetFunctionName */:
        return ["__setFunctionName"];
      case 8388608 /* PropKey */:
        return ["__propKey"];
      case 16777216 /* AddDisposableResourceAndDisposeResources */:
        return ["__addDisposableResource", "__disposeResources"];
      case 33554432 /* RewriteRelativeImportExtension */:
        return ["__rewriteRelativeImportExtension"];
      default:
        return Debug.fail("Unrecognized helper");
    }
  }
  function resolveHelpersModule(file, errorNode) {
    const links = getNodeLinks(file);
    if (!links.externalHelpersModule) {
      links.externalHelpersModule = resolveExternalModule(getImportHelpersImportSpecifier(file), externalHelpersModuleNameText, Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
    }
    return links.externalHelpersModule;
  }
  function checkGrammarModifiers(node) {
    var _a;
    const quickResult = reportObviousDecoratorErrors(node) || reportObviousModifierErrors(node);
    if (quickResult !== void 0) {
      return quickResult;
    }
    if (isParameter(node) && parameterIsThisKeyword(node)) {
      return grammarErrorOnFirstToken(node, Diagnostics.Neither_decorators_nor_modifiers_may_be_applied_to_this_parameters);
    }
    const blockScopeKind = isVariableStatement(node) ? node.declarationList.flags & 7 /* BlockScoped */ : 0 /* None */;
    let lastStatic, lastDeclare, lastAsync, lastOverride, firstDecorator;
    let flags = 0 /* None */;
    let sawExportBeforeDecorators = false;
    let hasLeadingDecorators = false;
    for (const modifier of node.modifiers) {
      if (isDecorator(modifier)) {
        if (!nodeCanBeDecorated(legacyDecorators, node, node.parent, node.parent.parent)) {
          if (node.kind === 174 /* MethodDeclaration */ && !nodeIsPresent(node.body)) {
            return grammarErrorOnFirstToken(node, Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
          } else {
            return grammarErrorOnFirstToken(node, Diagnostics.Decorators_are_not_valid_here);
          }
        } else if (legacyDecorators && (node.kind === 177 /* GetAccessor */ || node.kind === 178 /* SetAccessor */)) {
          const accessors = getAllAccessorDeclarationsForDeclaration(node);
          if (hasDecorators(accessors.firstAccessor) && node === accessors.secondAccessor) {
            return grammarErrorOnFirstToken(node, Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
          }
        }
        if (flags & ~(2080 /* ExportDefault */ | 32768 /* Decorator */)) {
          return grammarErrorOnNode(modifier, Diagnostics.Decorators_are_not_valid_here);
        }
        if (hasLeadingDecorators && flags & 98303 /* Modifier */) {
          Debug.assertIsDefined(firstDecorator);
          const sourceFile = getSourceFileOfNode(modifier);
          if (!hasParseDiagnostics(sourceFile)) {
            addRelatedInfo(
              error(modifier, Diagnostics.Decorators_may_not_appear_after_export_or_export_default_if_they_also_appear_before_export),
              createDiagnosticForNode(firstDecorator, Diagnostics.Decorator_used_before_export_here)
            );
            return true;
          }
          return false;
        }
        flags |= 32768 /* Decorator */;
        if (!(flags & 98303 /* Modifier */)) {
          hasLeadingDecorators = true;
        } else if (flags & 32 /* Export */) {
          sawExportBeforeDecorators = true;
        }
        firstDecorator ?? (firstDecorator = modifier);
      } else {
        if (modifier.kind !== 148 /* ReadonlyKeyword */) {
          if (node.kind === 171 /* PropertySignature */ || node.kind === 173 /* MethodSignature */) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_member, tokenToString(modifier.kind));
          }
          if (node.kind === 181 /* IndexSignature */ && (modifier.kind !== 126 /* StaticKeyword */ || !isClassLike(node.parent))) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_index_signature, tokenToString(modifier.kind));
          }
        }
        if (modifier.kind !== 103 /* InKeyword */ && modifier.kind !== 147 /* OutKeyword */ && modifier.kind !== 87 /* ConstKeyword */) {
          if (node.kind === 168 /* TypeParameter */) {
            return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_type_parameter, tokenToString(modifier.kind));
          }
        }
        switch (modifier.kind) {
          case 87 /* ConstKeyword */: {
            if (node.kind !== 266 /* EnumDeclaration */ && node.kind !== 168 /* TypeParameter */) {
              return grammarErrorOnNode(node, Diagnostics.A_class_member_cannot_have_the_0_keyword, tokenToString(87 /* ConstKeyword */));
            }
            const parent = isJSDocTemplateTag(node.parent) && getEffectiveJSDocHost(node.parent) || node.parent;
            if (node.kind === 168 /* TypeParameter */ && !(isFunctionLikeDeclaration(parent) || isClassLike(parent) || isFunctionTypeNode(parent) || isConstructorTypeNode(parent) || isCallSignatureDeclaration(parent) || isConstructSignatureDeclaration(parent) || isMethodSignature(parent))) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_function_method_or_class, tokenToString(modifier.kind));
            }
            break;
          }
          case 164 /* OverrideKeyword */:
            if (flags & 16 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "override");
            } else if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "override", "declare");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "readonly");
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "accessor");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "override", "async");
            }
            flags |= 16 /* Override */;
            lastOverride = modifier;
            break;
          case 125 /* PublicKeyword */:
          case 124 /* ProtectedKeyword */:
          case 123 /* PrivateKeyword */:
            const text = visibilityToString(modifierToFlag(modifier.kind));
            if (flags & 7 /* AccessibilityModifier */) {
              return grammarErrorOnNode(modifier, Diagnostics.Accessibility_modifier_already_seen);
            } else if (flags & 16 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "override");
            } else if (flags & 256 /* Static */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "accessor");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
            } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
            } else if (flags & 64 /* Abstract */) {
              if (modifier.kind === 123 /* PrivateKeyword */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
              } else {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
              }
            } else if (isPrivateIdentifierClassElementDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
            }
            flags |= modifierToFlag(modifier.kind);
            break;
          case 126 /* StaticKeyword */:
            if (flags & 256 /* Static */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "static");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "accessor");
            } else if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
            } else if (node.kind === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
            } else if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
            } else if (flags & 16 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "static", "override");
            }
            flags |= 256 /* Static */;
            lastStatic = modifier;
            break;
          case 129 /* AccessorKeyword */:
            if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "accessor");
            } else if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "readonly");
            } else if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "accessor", "declare");
            } else if (node.kind !== 172 /* PropertyDeclaration */) {
              return grammarErrorOnNode(modifier, Diagnostics.accessor_modifier_can_only_appear_on_a_property_declaration);
            }
            flags |= 512 /* Accessor */;
            break;
          case 148 /* ReadonlyKeyword */:
            if (flags & 8 /* Readonly */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "readonly");
            } else if (node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 171 /* PropertySignature */ && node.kind !== 181 /* IndexSignature */ && node.kind !== 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "readonly", "accessor");
            }
            flags |= 8 /* Readonly */;
            break;
          case 95 /* ExportKeyword */:
            if (compilerOptions.verbatimModuleSyntax && !(node.flags & 33554432 /* Ambient */) && node.kind !== 265 /* TypeAliasDeclaration */ && node.kind !== 264 /* InterfaceDeclaration */ && // ModuleDeclaration needs to be checked that it is uninstantiated later
            node.kind !== 267 /* ModuleDeclaration */ && node.parent.kind === 307 /* SourceFile */ && host.getEmitModuleFormatOfFile(getSourceFileOfNode(node)) === 1 /* CommonJS */) {
              return grammarErrorOnNode(modifier, Diagnostics.A_top_level_export_modifier_cannot_be_used_on_value_declarations_in_a_CommonJS_module_when_verbatimModuleSyntax_is_enabled);
            }
            if (flags & 32 /* Export */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "export");
            } else if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
            } else if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
            } else if (isClassLike(node.parent)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export");
            } else if (node.kind === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
            } else if (blockScopeKind === 4 /* Using */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "export");
            } else if (blockScopeKind === 6 /* AwaitUsing */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "export");
            }
            flags |= 32 /* Export */;
            break;
          case 90 /* DefaultKeyword */:
            const container = node.parent.kind === 307 /* SourceFile */ ? node.parent : node.parent.parent;
            if (container.kind === 267 /* ModuleDeclaration */ && !isAmbientModule(container)) {
              return grammarErrorOnNode(modifier, Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
            } else if (blockScopeKind === 4 /* Using */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "default");
            } else if (blockScopeKind === 6 /* AwaitUsing */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "default");
            } else if (!(flags & 32 /* Export */)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "export", "default");
            } else if (sawExportBeforeDecorators) {
              return grammarErrorOnNode(firstDecorator, Diagnostics.Decorators_are_not_valid_here);
            }
            flags |= 2048 /* Default */;
            break;
          case 138 /* DeclareKeyword */:
            if (flags & 128 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "declare");
            } else if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (flags & 16 /* Override */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "override");
            } else if (isClassLike(node.parent) && !isPropertyDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare");
            } else if (node.kind === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
            } else if (blockScopeKind === 4 /* Using */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_using_declaration, "declare");
            } else if (blockScopeKind === 6 /* AwaitUsing */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_an_await_using_declaration, "declare");
            } else if (node.parent.flags & 33554432 /* Ambient */ && node.parent.kind === 268 /* ModuleBlock */) {
              return grammarErrorOnNode(modifier, Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
            } else if (isPrivateIdentifierClassElementDeclaration(node)) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
            } else if (flags & 512 /* Accessor */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "declare", "accessor");
            }
            flags |= 128 /* Ambient */;
            lastDeclare = modifier;
            break;
          case 128 /* AbstractKeyword */:
            if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "abstract");
            }
            if (node.kind !== 263 /* ClassDeclaration */ && node.kind !== 185 /* ConstructorType */) {
              if (node.kind !== 174 /* MethodDeclaration */ && node.kind !== 172 /* PropertyDeclaration */ && node.kind !== 177 /* GetAccessor */ && node.kind !== 178 /* SetAccessor */) {
                return grammarErrorOnNode(modifier, Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
              }
              if (!(node.parent.kind === 263 /* ClassDeclaration */ && hasSyntacticModifier(node.parent, 64 /* Abstract */))) {
                const message = node.kind === 172 /* PropertyDeclaration */ ? Diagnostics.Abstract_properties_can_only_appear_within_an_abstract_class : Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class;
                return grammarErrorOnNode(modifier, message);
              }
              if (flags & 256 /* Static */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
              }
              if (flags & 2 /* Private */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
              }
              if (flags & 1024 /* Async */ && lastAsync) {
                return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
              }
              if (flags & 16 /* Override */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "override");
              }
              if (flags & 512 /* Accessor */) {
                return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "abstract", "accessor");
              }
            }
            if (isNamedDeclaration(node) && node.name.kind === 81 /* PrivateIdentifier */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
            }
            flags |= 64 /* Abstract */;
            break;
          case 134 /* AsyncKeyword */:
            if (flags & 1024 /* Async */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, "async");
            } else if (flags & 128 /* Ambient */ || node.parent.flags & 33554432 /* Ambient */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
            } else if (node.kind === 169 /* Parameter */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
            }
            if (flags & 64 /* Abstract */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
            }
            flags |= 1024 /* Async */;
            lastAsync = modifier;
            break;
          case 103 /* InKeyword */:
          case 147 /* OutKeyword */: {
            const inOutFlag = modifier.kind === 103 /* InKeyword */ ? 8192 /* In */ : 16384 /* Out */;
            const inOutText = modifier.kind === 103 /* InKeyword */ ? "in" : "out";
            const parent = isJSDocTemplateTag(node.parent) && (getEffectiveJSDocHost(node.parent) || find((_a = getJSDocRoot(node.parent)) == null ? void 0 : _a.tags, isJSDocTypedefTag)) || node.parent;
            if (node.kind !== 168 /* TypeParameter */ || parent && !(isInterfaceDeclaration(parent) || isClassLike(parent) || isTypeAliasDeclaration(parent) || isJSDocTypedefTag(parent))) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_can_only_appear_on_a_type_parameter_of_a_class_interface_or_type_alias, inOutText);
            }
            if (flags & inOutFlag) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_already_seen, inOutText);
            }
            if (inOutFlag & 8192 /* In */ && flags & 16384 /* Out */) {
              return grammarErrorOnNode(modifier, Diagnostics._0_modifier_must_precede_1_modifier, "in", "out");
            }
            flags |= inOutFlag;
            break;
          }
        }
      }
    }
    if (node.kind === 176 /* Constructor */) {
      if (flags & 256 /* Static */) {
        return grammarErrorOnNode(lastStatic, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
      }
      if (flags & 16 /* Override */) {
        return grammarErrorOnNode(lastOverride, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "override");
      }
      if (flags & 1024 /* Async */) {
        return grammarErrorOnNode(lastAsync, Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
      }
      return false;
    } else if ((node.kind === 272 /* ImportDeclaration */ || node.kind === 271 /* ImportEqualsDeclaration */) && flags & 128 /* Ambient */) {
      return grammarErrorOnNode(lastDeclare, Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
    } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && isBindingPattern(node.name)) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
    } else if (node.kind === 169 /* Parameter */ && flags & 31 /* ParameterPropertyModifier */ && node.dotDotDotToken) {
      return grammarErrorOnNode(node, Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
    }
    if (flags & 1024 /* Async */) {
      return checkGrammarAsyncModifier(node, lastAsync);
    }
    return false;
  }
  function reportObviousModifierErrors(node) {
    if (!node.modifiers) return false;
    const modifier = findFirstIllegalModifier(node);
    return modifier && grammarErrorOnFirstToken(modifier, Diagnostics.Modifiers_cannot_appear_here);
  }
  function findFirstModifierExcept(node, allowedModifier) {
    const modifier = find(node.modifiers, isModifier);
    return modifier && modifier.kind !== allowedModifier ? modifier : void 0;
  }
  function findFirstIllegalModifier(node) {
    switch (node.kind) {
      case 177 /* GetAccessor */:
      case 178 /* SetAccessor */:
      case 176 /* Constructor */:
      case 172 /* PropertyDeclaration */:
      case 171 /* PropertySignature */:
      case 174 /* MethodDeclaration */:
      case 173 /* MethodSignature */:
      case 181 /* IndexSignature */:
      case 267 /* ModuleDeclaration */:
      case 272 /* ImportDeclaration */:
      case 271 /* ImportEqualsDeclaration */:
      case 278 /* ExportDeclaration */:
      case 277 /* ExportAssignment */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
      case 169 /* Parameter */:
      case 168 /* TypeParameter */:
        return void 0;
      case 175 /* ClassStaticBlockDeclaration */:
      case 303 /* PropertyAssignment */:
      case 304 /* ShorthandPropertyAssignment */:
      case 270 /* NamespaceExportDeclaration */:
      case 282 /* MissingDeclaration */:
        return find(node.modifiers, isModifier);
      default:
        if (node.parent.kind === 268 /* ModuleBlock */ || node.parent.kind === 307 /* SourceFile */) {
          return void 0;
        }
        switch (node.kind) {
          case 262 /* FunctionDeclaration */:
            return findFirstModifierExcept(node, 134 /* AsyncKeyword */);
          case 263 /* ClassDeclaration */:
          case 185 /* ConstructorType */:
            return findFirstModifierExcept(node, 128 /* AbstractKeyword */);
          case 231 /* ClassExpression */:
          case 264 /* InterfaceDeclaration */:
          case 265 /* TypeAliasDeclaration */:
            return find(node.modifiers, isModifier);
          case 243 /* VariableStatement */:
            return node.declarationList.flags & 4 /* Using */ ? findFirstModifierExcept(node, 135 /* AwaitKeyword */) : find(node.modifiers, isModifier);
          case 266 /* EnumDeclaration */:
            return findFirstModifierExcept(node, 87 /* ConstKeyword */);
          default:
            Debug.assertNever(node);
        }
    }
  }
  function reportObviousDecoratorErrors(node) {
    const decorator = findFirstIllegalDecorator(node);
    return decorator && grammarErrorOnFirstToken(decorator, Diagnostics.Decorators_are_not_valid_here);
  }
  function findFirstIllegalDecorator(node) {
    return canHaveIllegalDecorators(node) ? find(node.modifiers, isDecorator) : void 0;
  }
  function checkGrammarAsyncModifier(node, asyncModifier) {
    switch (node.kind) {
      case 174 /* MethodDeclaration */:
      case 262 /* FunctionDeclaration */:
      case 218 /* FunctionExpression */:
      case 219 /* ArrowFunction */:
        return false;
    }
    return grammarErrorOnNode(asyncModifier, Diagnostics._0_modifier_cannot_be_used_here, "async");
  }
  function checkGrammarForDisallowedTrailingComma(list, diag2 = Diagnostics.Trailing_comma_not_allowed) {
    if (list && list.hasTrailingComma) {
      return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag2);
    }
    return false;
  }
  function checkGrammarTypeParameterList(typeParameters, file) {
    if (typeParameters && typeParameters.length === 0) {
      const start = typeParameters.pos - "<".length;
      const end = skipTrivia(file.text, typeParameters.end) + ">".length;
      return grammarErrorAtPos(file, start, end - start, Diagnostics.Type_parameter_list_cannot_be_empty);
    }
    return false;
  }
  function checkGrammarParameterList(parameters) {
    let seenOptionalParameter = false;
    const parameterCount = parameters.length;
    for (let i = 0; i < parameterCount; i++) {
      const parameter = parameters[i];
      if (parameter.dotDotDotToken) {
        if (i !== parameterCount - 1) {
          return grammarErrorOnNode(parameter.dotDotDotToken, Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
        }
        if (!(parameter.flags & 33554432 /* Ambient */)) {
          checkGrammarForDisallowedTrailingComma(parameters, Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
        }
        if (parameter.questionToken) {
          return grammarErrorOnNode(parameter.questionToken, Diagnostics.A_rest_parameter_cannot_be_optional);
        }
        if (parameter.initializer) {
          return grammarErrorOnNode(parameter.name, Diagnostics.A_rest_parameter_cannot_have_an_initializer);
        }
      } else if (hasEffectiveQuestionToken(parameter)) {
        seenOptionalParameter = true;
        if (parameter.questionToken && parameter.initializer) {
          return grammarErrorOnNode(parameter.name, Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
        }
      } else if (seenOptionalParameter && !parameter.initializer) {
        return grammarErrorOnNode(parameter.name, Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
      }
    }
  }
  function getNonSimpleParameters(parameters) {
    return filter(parameters, (parameter) => !!parameter.initializer || isBindingPattern(parameter.name) || isRestParameter(parameter));
  }
  function checkGrammarForUseStrictSimpleParameterList(node) {
    if (languageVersion >= 3 /* ES2016 */) {
      const useStrictDirective = node.body && isBlock(node.body) && findUseStrictPrologue(node.body.statements);
      if (useStrictDirective) {
        const nonSimpleParameters = getNonSimpleParameters(node.parameters);
        if (length(nonSimpleParameters)) {
          forEach(nonSimpleParameters, (parameter) => {
            addRelatedInfo(
              error(parameter, Diagnostics.This_parameter_is_not_allowed_with_use_strict_directive),
              createDiagnosticForNode(useStrictDirective, Diagnostics.use_strict_directive_used_here)
            );
          });
          const diagnostics2 = nonSimpleParameters.map((parameter, index) => index === 0 ? createDiagnosticForNode(parameter, Diagnostics.Non_simple_parameter_declared_here) : createDiagnosticForNode(parameter, Diagnostics.and_here));
          addRelatedInfo(error(useStrictDirective, Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list), ...diagnostics2);
          return true;
        }
      }
    }
    return false;
  }
  function checkGrammarFunctionLikeDeclaration(node) {
    const file = getSourceFileOfNode(node);
    return checkGrammarModifiers(node) || checkGrammarTypeParameterList(node.typeParameters, file) || checkGrammarParameterList(node.parameters) || checkGrammarArrowFunction(node, file) || isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node);
  }
  function checkGrammarClassLikeDeclaration(node) {
    const file = getSourceFileOfNode(node);
    return checkGrammarClassDeclarationHeritageClauses(node) || checkGrammarTypeParameterList(node.typeParameters, file);
  }
  function checkGrammar