text:
//===--- Linking.cpp - Name mangling for IRGen entities -------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//  This file implements name mangling for IRGen entities with linkage.
//
//===----------------------------------------------------------------------===//

#include "swift/IRGen/Linking.h"
#include "IRGenMangler.h"
#include "IRGenModule.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/SIL/SILGlobalVariable.h"
#include "swift/SIL/FormalLinkage.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/raw_ostream.h"

#include "MetadataRequest.h"

using namespace swift;
using namespace irgen;
using namespace Mangle;

const IRLinkage IRLinkage::InternalLinkOnceODR = {
  llvm::GlobalValue::LinkOnceODRLinkage,
  llvm::GlobalValue::HiddenVisibility,
  llvm::GlobalValue::DefaultStorageClass,
};

const IRLinkage IRLinkage::InternalWeakODR = {
  llvm::GlobalValue::WeakODRLinkage,
  llvm::GlobalValue::HiddenVisibility,
  llvm::GlobalValue::DefaultStorageClass,
};

const IRLinkage IRLinkage::Internal = {
  llvm::GlobalValue::InternalLinkage,
  llvm::GlobalValue::DefaultVisibility,
  llvm::GlobalValue::DefaultStorageClass,
};

const IRLinkage IRLinkage::ExternalCommon = {
  llvm::GlobalValue::CommonLinkage,
  llvm::GlobalValue::DefaultVisibility,
  llvm::GlobalValue::DLLExportStorageClass,
};

const IRLinkage IRLinkage::ExternalImport = {
  llvm::GlobalValue::ExternalLinkage,
  llvm::GlobalValue::DefaultVisibility,
  llvm::GlobalValue::DLLImportStorageClass,
};

const IRLinkage IRLinkage::ExternalWeakImport = {
  llvm::GlobalValue::ExternalWeakLinkage,
  llvm::GlobalValue::DefaultVisibility,
  llvm::GlobalValue::DLLImportStorageClass,
};

const IRLinkage IRLinkage::ExternalExport = {
  llvm::GlobalValue::ExternalLinkage,
  llvm::GlobalValue::DefaultVisibility,
  llvm::GlobalValue::DLLExportStorageClass,
};

bool swift::irgen::useDllStorage(const llvm::Triple &triple) {
  return triple.isOSBinFormatCOFF() && !triple.isOSCygMing();
}

UniversalLinkageInfo::UniversalLinkageInfo(IRGenModule &IGM)
    : UniversalLinkageInfo(IGM.Triple, IGM.IRGen.hasMultipleIGMs(),
                           IGM.IRGen.Opts.ForcePublicLinkage,
                           IGM.IRGen.Opts.InternalizeSymbols) {}

UniversalLinkageInfo::UniversalLinkageInfo(const llvm::Triple &triple,
                                           bool hasMultipleIGMs,
                                           bool forcePublicDecls,
                                           bool isStaticLibrary)
    : IsELFObject(triple.isOSBinFormatELF()),
      UseDLLStorage(useDllStorage(triple)), Internalize(isStaticLibrary),
      HasMultipleIGMs(hasMultipleIGMs), ForcePublicDecls(forcePublicDecls) {}

LinkEntity LinkEntity::forSILGlobalVariable(SILGlobalVariable *G,
                                            IRGenModule &IGM) {
  LinkEntity entity;
  entity.Pointer = G;
  entity.SecondaryPointer = nullptr;
  auto kind = (G->isInitializedObject() && IGM.canMakeStaticObjectsReadOnly() ?
                Kind::ReadOnlyGlobalObject : Kind::SILGlobalVariable);
  entity.Data = unsigned(kind) << KindShift;
  return entity;
}

/// Mangle this entity into the given buffer.
void LinkEntity::mangle(SmallVectorImpl<char> &buffer) const {
  llvm::raw_svector_ostream stream(buffer);
  mangle(stream);
}

/// Mangle this entity into the given stream.
void LinkEntity::mangle(raw_ostream &buffer) const {
  std::string Result = mangleAsString();
  buffer.write(Result.data(), Result.size());
}

/// Mangle this entity as a std::string.
std::string LinkEntity::mangleAsString() const {
  IRGenMangler mangler;
  switch (getKind()) {
  case Kind::DispatchThunk: {
    auto *func = cast<FuncDecl>(getDecl());
    return mangler.mangleDispatchThunk(func);
  }

  case Kind::DispatchThunkDerivative: {
    auto *func = cast<AbstractFunctionDecl>(getDecl());
    auto *derivativeId = getAutoDiffDerivativeFunctionIdentifier();
    return mangler.mangleDerivativeDispatchThunk(func, derivativeId);
  }

  case Kind::DispatchThunkInitializer: {
    auto *ctor = cast<ConstructorDecl>(getDecl());
    return mangler.mangleConstructorDispatchThunk(ctor,
                                                  /*isAllocating=*/false);
  }

  case Kind::DispatchThunkAllocator: {
    auto *ctor = cast<ConstructorDecl>(getDecl());
    return mangler.mangleConstructorDispatchThunk(ctor,
                                                  /*isAllocating=*/true);
  }

  case Kind::MethodDescriptor: {
    auto *func = cast<FuncDecl>(getDecl());
    return mangler.mangleMethodDescriptor(func);
  }

  case Kind::MethodDescriptorDerivative: {
    auto *func = cast<AbstractFunctionDecl>(getDecl());
    auto *derivativeId = getAutoDiffDerivativeFunctionIdentifier();
    return mangler.mangleDerivativeMethodDescriptor(func, derivativeId);
  }

  case Kind::MethodDescriptorInitializer: {
    auto *ctor = cast<ConstructorDecl>(getDecl());
    return mangler.mangleConstructorMethodDescriptor(ctor,
                                                     /*isAllocating=*/false);
  }

  case Kind::MethodDescriptorAllocator: {
    auto *ctor = cast<ConstructorDecl>(getDecl());
    return mangler.mangleConstructorMethodDescriptor(ctor,
                                                     /*isAllocating=*/true);
  }

  case Kind::MethodLookupFunction: {
    auto *classDecl = cast<ClassDecl>(getDecl());
    return mangler.mangleMethodLookupFunction(classDecl);
  }

  case Kind::ValueWitness:
    return mangler.mangleValueWitness(getType(), getValueWitness());

  case Kind::ValueWitnessTable:
    return mangler.mangleValueWitnessTable(getType());

  case Kind::TypeMetadataAccessFunction:
    return mangler.mangleTypeMetadataAccessFunction(getType());

  case Kind::CanonicalSpecializedGenericTypeMetadataAccessFunction:
    return mangler.mangleCanonicalSpecializedGenericTypeMetadataAccessFunction(
        getType());

  case Kind::TypeMetadataLazyCacheVariable:
    return mangler.mangleTypeMetadataLazyCacheVariable(getType());

  case Kind::TypeMetadataDemanglingCacheVariable:
    return mangler.mangleTypeMetadataDemanglingCacheVariable(getType());

  case Kind::TypeMetadataInstantiationCache:
    return mangler.mangleTypeMetadataInstantiationCache(
                                            cast<NominalTypeDecl>(getDecl()));

  case Kind::TypeMetadataInstantiationFunction:
    return mangler.mangleTypeMetadataInstantiationFunction(
                                            cast<NominalTypeDecl>(getDecl()));

  case Kind::TypeMetadataSingletonInitializationCache:
    return mangler.mangleTypeMetadataSingletonInitializationCache(
                                            cast<NominalTypeDecl>(getDecl()));

  case Kind::TypeMetadataCompletionFunction:
    return mangler.mangleTypeMetadataCompletionFunction(
                                            cast<NominalTypeDecl>(getDecl()));

  case Kind::TypeMetadata:
    switch (getMetadataAddress()) {
      case TypeMetadataAddress::FullMetadata:
        return mangler.mangleTypeFullMetadataFull(getType());
      case TypeMetadataAddress::AddressPoint:
        return mangler.mangleTypeMetadataFull(getType());
    }
    llvm_unreachable("invalid metadata address");

  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
    return mangler.mangleNoncanonicalTypeMetadata(getType());

  case Kind::CanonicalPrespecializedGenericTypeCachingOnceToken:
    return mangler.mangleCanonicalPrespecializedGenericTypeCachingOnceToken(
        cast<NominalTypeDecl>(getDecl()));

  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
    return mangler.mangleNoncanonicalSpecializedGenericTypeMetadataCache(getType());

  case Kind::TypeMetadataPattern:
    return mangler.mangleTypeMetadataPattern(
                                        cast<NominalTypeDecl>(getDecl()));

  case Kind::SwiftMetaclassStub:
    return mangler.mangleClassMetaClass(cast<ClassDecl>(getDecl()));

  case Kind::CanonicalSpecializedGenericSwiftMetaclassStub:
    return mangler.mangleSpecializedGenericClassMetaClass(getType());

  case Kind::ObjCMetadataUpdateFunction:
    return mangler.mangleObjCMetadataUpdateFunction(cast<ClassDecl>(getDecl()));

  case Kind::ObjCResilientClassStub:
    switch (getMetadataAddress()) {
    case TypeMetadataAddress::FullMetadata:
      return mangler.mangleFullObjCResilientClassStub(cast<ClassDecl>(getDecl()));
    case TypeMetadataAddress::AddressPoint:
      return mangler.mangleObjCResilientClassStub(cast<ClassDecl>(getDecl()));
    }
    llvm_unreachable("invalid metadata address");

  case Kind::ClassMetadataBaseOffset:               // class metadata base offset
    return mangler.mangleClassMetadataBaseOffset(cast<ClassDecl>(getDecl()));

  case Kind::NominalTypeDescriptor:
    return mangler.mangleNominalTypeDescriptor(
                                        cast<NominalTypeDecl>(getDecl()));

  case Kind::NominalTypeDescriptorRecord:
    return mangler.mangleNominalTypeDescriptorRecord(
                                        cast<NominalTypeDecl>(getDecl()));

  case Kind::OpaqueTypeDescriptor:
    return mangler.mangleOpaqueTypeDescriptor(cast<OpaqueTypeDecl>(getDecl()));

  case Kind::OpaqueTypeDescriptorRecord:
    return mangler.mangleOpaqueTypeDescriptorRecord(
        cast<OpaqueTypeDecl>(getDecl()));

  case Kind::OpaqueTypeDescriptorAccessor:
    return mangler.mangleOpaqueTypeDescriptorAccessor(
        cast<OpaqueTypeDecl>(getDecl()));

  case Kind::OpaqueTypeDescriptorAccessorImpl:
    return mangler.mangleOpaqueTypeDescriptorAccessorImpl(
        cast<OpaqueTypeDecl>(getDecl()));

  case Kind::OpaqueTypeDescriptorAccessorKey:
    return mangler.mangleOpaqueTypeDescriptorAccessorKey(
        cast<OpaqueTypeDecl>(getDecl()));

  case Kind::OpaqueTypeDescriptorAccessorVar:
    return mangler.mangleOpaqueTypeDescriptorAccessorVar(
        cast<OpaqueTypeDecl>(getDecl()));

  case Kind::PropertyDescriptor:
    return mangler.manglePropertyDescriptor(
                                        cast<AbstractStorageDecl>(getDecl()));

  case Kind::ModuleDescriptor:
    return mangler.mangleModuleDescriptor(cast<ModuleDecl>(getDecl()));

  case Kind::ExtensionDescriptor:
    return mangler.mangleExtensionDescriptor(getExtension());

  case Kind::AnonymousDescriptor:
    return mangler.mangleAnonymousDescriptor(getAnonymousDeclContext());

  case Kind::ProtocolDescriptor:
    return mangler.mangleProtocolDescriptor(cast<ProtocolDecl>(getDecl()));

  case Kind::ProtocolDescriptorRecord:
    return mangler.mangleProtocolDescriptorRecord(cast<ProtocolDecl>(getDecl()));

  case Kind::ProtocolRequirementsBaseDescriptor:
    return mangler.mangleProtocolRequirementsBaseDescriptor(
                                                 cast<ProtocolDecl>(getDecl()));

  case Kind::AssociatedTypeDescriptor:
    return mangler.mangleAssociatedTypeDescriptor(
                                          cast<AssociatedTypeDecl>(getDecl()));

  case Kind::AssociatedConformanceDescriptor: {
    auto assocConformance = getAssociatedConformance();
    return mangler.mangleAssociatedConformanceDescriptor(
             cast<ProtocolDecl>(getDecl()),
             assocConformance.first,
             assocConformance.second);
  }

  case Kind::BaseConformanceDescriptor: {
    auto assocConformance = getAssociatedConformance();
    return mangler.mangleBaseConformanceDescriptor(
             cast<ProtocolDecl>(getDecl()),
             assocConformance.second);
  }

  case Kind::DefaultAssociatedConformanceAccessor: {
    auto assocConformance = getAssociatedConformance();
    return mangler.mangleDefaultAssociatedConformanceAccessor(
             cast<ProtocolDecl>(getDecl()),
             assocConformance.first,
             assocConformance.second);
  }

  case Kind::ProtocolConformanceDescriptor:
    return mangler.mangleProtocolConformanceDescriptor(
                                                  getRootProtocolConformance());

  case Kind::ProtocolConformanceDescriptorRecord:
    return mangler.mangleProtocolConformanceDescriptorRecord(
                                                  getRootProtocolConformance());

  case Kind::EnumCase:
    return mangler.mangleEnumCase(getDecl());

  case Kind::FieldOffset:
    return mangler.mangleFieldOffset(getDecl());

  case Kind::ProtocolWitnessTable:
    return mangler.mangleWitnessTable(getRootProtocolConformance());

  case Kind::GenericProtocolWitnessTableInstantiationFunction:
    return mangler.mangleGenericProtocolWitnessTableInstantiationFunction(
                                                    getProtocolConformance());

  case Kind::ProtocolWitnessTablePattern:
    return mangler.mangleProtocolWitnessTablePattern(getProtocolConformance());

  case Kind::ProtocolWitnessTableLazyAccessFunction:
    return mangler.mangleProtocolWitnessTableLazyAccessFunction(getType(),
                                                    getProtocolConformance());

  case Kind::ProtocolWitnessTableLazyCacheVariable:
    return mangler.mangleProtocolWitnessTableLazyCacheVariable(getType(),
                                                    getProtocolConformance());

  case Kind::AssociatedTypeWitnessTableAccessFunction: {
    auto assocConf = getAssociatedConformance();
    if (isa<GenericTypeParamType>(assocConf.first)) {
      return mangler.mangleBaseWitnessTableAccessFunction(
                  getProtocolConformance(), assocConf.second);
    }

    return mangler.mangleAssociatedTypeWitnessTableAccessFunction(
                getProtocolConformance(), assocConf.first, assocConf.second);
  }

  case Kind::CoroutineContinuationPrototype:
    return mangler.mangleCoroutineContinuationPrototype(
                                            cast<SILFunctionType>(getType()));

    // An Objective-C class reference reference. The symbol is private, so
    // the mangling is unimportant; it should just be readable in LLVM IR.
  case Kind::ObjCClassRef: {
    llvm::SmallString<64> tempBuffer;
    StringRef name = cast<ClassDecl>(getDecl())->getObjCRuntimeName(tempBuffer);
    std::string Result("OBJC_CLASS_REF_$_");
    Result.append(name.data(), name.size());
    return Result;
  }

    // An Objective-C class reference;  not a swift mangling.
  case Kind::ObjCClass: {
    llvm::SmallString<64> TempBuffer;
    StringRef Name = cast<ClassDecl>(getDecl())->getObjCRuntimeName(TempBuffer);
    std::string Result("OBJC_CLASS_$_");
    Result.append(Name.data(), Name.size());
    return Result;
  }

    // An Objective-C metaclass reference;  not a swift mangling.
  case Kind::ObjCMetaclass: {
    llvm::SmallString<64> TempBuffer;
    StringRef Name = cast<ClassDecl>(getDecl())->getObjCRuntimeName(TempBuffer);
    std::string Result("OBJC_METACLASS_$_");
    Result.append(Name.data(), Name.size());
    return Result;
  }

  case Kind::SILFunction: {
    std::string Result(getSILFunction()->getName());
    if (isDynamicallyReplaceable()) {
      Result.append("TI");
    }
    return Result;
  }
  case Kind::DynamicallyReplaceableFunctionImpl: {
    assert(isa<AbstractFunctionDecl>(getDecl()));
    std::string Result;
    if (auto *Constructor = dyn_cast<ConstructorDecl>(getDecl())) {
      Result = mangler.mangleConstructorEntity(Constructor, isAllocator());
    } else  {
      Result = mangler.mangleEntity(getDecl());
    }
    Result.append("TI");
    return Result;
  }

  case Kind::DynamicallyReplaceableFunctionVariable: {
    std::string Result(getSILFunction()->getName());
    Result.append("TX");
    return Result;
  }

  case Kind::DynamicallyReplaceableFunctionKey: {
    std::string Result(getSILFunction()->getName());
    Result.append("Tx");
    return Result;
  }

  case Kind::DynamicallyReplaceableFunctionVariableAST: {
    assert(isa<AbstractFunctionDecl>(getDecl()));
    std::string Result;
    if (auto *Constructor = dyn_cast<ConstructorDecl>(getDecl())) {
      Result =
          mangler.mangleConstructorEntity(Constructor, isAllocator());
    } else  {
      Result = mangler.mangleEntity(getDecl());
    }
    Result.append("TX");
    return Result;
  }

  case Kind::DynamicallyReplaceableFunctionKeyAST: {
    assert(isa<AbstractFunctionDecl>(getDecl()));
    std::string Result;
    if (auto *Constructor = dyn_cast<ConstructorDecl>(getDecl())) {
      Result =
          mangler.mangleConstructorEntity(Constructor, isAllocator());
    } else  {
      Result = mangler.mangleEntity(getDecl());
    }
    Result.append("Tx");
    return Result;
  }

  case Kind::SILGlobalVariable:
    return getSILGlobalVariable()->getName().str();

  case Kind::ReadOnlyGlobalObject:
    return getSILGlobalVariable()->getName().str() + "r";

  case Kind::ReflectionBuiltinDescriptor:
    return mangler.mangleReflectionBuiltinDescriptor(getType());
  case Kind::ReflectionFieldDescriptor:
    return mangler.mangleReflectionFieldDescriptor(getType());
  case Kind::ReflectionAssociatedTypeDescriptor:
    return mangler.mangleReflectionAssociatedTypeDescriptor(
                                                    getProtocolConformance());
  case Kind::DifferentiabilityWitness:
    return mangler.mangleSILDifferentiabilityWitness(
        getSILDifferentiabilityWitness()->getOriginalFunction()->getName(),
        getSILDifferentiabilityWitness()->getKind(),
        getSILDifferentiabilityWitness()->getConfig());

  case Kind::AsyncFunctionPointer:
  case Kind::DispatchThunkAsyncFunctionPointer:
  case Kind::DispatchThunkInitializerAsyncFunctionPointer:
  case Kind::DispatchThunkAllocatorAsyncFunctionPointer:
  case Kind::PartialApplyForwarderAsyncFunctionPointer:
  case Kind::DistributedAccessorAsyncPointer: {
    std::string Result(getUnderlyingEntityForAsyncFunctionPointer()
        .mangleAsString());
    Result.append("Tu");
    return Result;
  }
  case Kind::DistributedThunkAsyncFunctionPointer: {
    std::string Result = getSILDeclRef().mangle();
    Result.append("TE");
    Result.append("Tu");
    return Result;
  }
  case Kind::KnownAsyncFunctionPointer: {
    std::string Result(static_cast<char *>(Pointer));
    Result.append("Tu");
    return Result;
  }

  case Kind::AsyncFunctionPointerAST: {
    std::string Result = getSILDeclRef().mangle();
    Result.append("Tu");
    return Result;
  }
  case Kind::PartialApplyForwarder: {
    std::string Result;
    Result = std::string(static_cast<llvm::Function *>(Pointer)->getName());
    return Result;
  }

  case Kind::DistributedAccessor: {
    std::string Result(getSILFunction()->getName());
    Result.append("TF");
    return Result;
  }

  case Kind::AccessibleFunctionRecord: {
    std::string Result(getSILFunction()->getName());
    Result.append("HF");
    return Result;
  }

  case Kind::ExtendedExistentialTypeShape: {
    auto genSig = getExtendedExistentialTypeShapeGenSig();
    auto existentialType = getExtendedExistentialTypeShapeType();
    auto isUnique = isExtendedExistentialTypeShapeUnique();

    return mangler.mangleExtendedExistentialTypeShapeSymbol(
                     genSig, existentialType, isUnique);
  }
  }
  llvm_unreachable("bad entity kind!");
}

SILDeclRef LinkEntity::getSILDeclRef() const {
  assert(getKind() == Kind::DistributedThunkAsyncFunctionPointer ||
         getKind() == Kind::AsyncFunctionPointerAST);

  return SILDeclRef(const_cast<ValueDecl *>(getDecl()),
             static_cast<SILDeclRef::Kind>(
                 reinterpret_cast<uintptr_t>(SecondaryPointer)));
}

SILLinkage LinkEntity::getLinkage(ForDefinition_t forDefinition) const {
  // For when `this` is a protocol conformance of some kind.
  auto getLinkageAsConformance = [&] {
    return getLinkageForProtocolConformance(
        getProtocolConformance()->getRootConformance(), forDefinition);
  };

  switch (getKind()) {
  case Kind::DispatchThunk:
  case Kind::DispatchThunkDerivative:
  case Kind::DispatchThunkInitializer:
  case Kind::DispatchThunkAllocator:
  case Kind::MethodDescriptor:
  case Kind::MethodDescriptorDerivative:
  case Kind::MethodDescriptorInitializer:
  case Kind::MethodDescriptorAllocator: {
    auto *decl = getDecl();

    // Protocol requirements don't have their own access control
    if (auto *proto = dyn_cast<ProtocolDecl>(decl->getDeclContext()))
      decl = proto;

    return getSILLinkage(getDeclLinkage(decl), forDefinition);
  }

  // Most type metadata depend on the formal linkage of their type.
  case Kind::ValueWitnessTable: {
    auto type = getType();

    // Builtin types, (), () -> () and so on are in the runtime.
    if (!type.getAnyNominal())
      return getSILLinkage(FormalLinkage::PublicUnique, forDefinition);

    // Imported types.
    if (isAccessorLazilyGenerated(getTypeMetadataAccessStrategy(type)))
      return SILLinkage::Shared;

    // Everything else is only referenced inside its module.
    return SILLinkage::Private;
  }

  case Kind::ObjCMetadataUpdateFunction:
  case Kind::TypeMetadataInstantiationCache:
  case Kind::TypeMetadataInstantiationFunction:
  case Kind::TypeMetadataSingletonInitializationCache:
  case Kind::TypeMetadataCompletionFunction:
  case Kind::TypeMetadataPattern:
    return SILLinkage::Private;

  case Kind::TypeMetadataLazyCacheVariable: {
    auto type = getType();

    // Imported types, non-primitive structural types.
    if (isAccessorLazilyGenerated(getTypeMetadataAccessStrategy(type)))
      return SILLinkage::Shared;

    // Everything else is only referenced inside its module.
    return SILLinkage::Private;
  }

  case Kind::TypeMetadataDemanglingCacheVariable:
    return SILLinkage::Shared;

  case Kind::TypeMetadata: {
    auto *nominal = getType().getAnyNominal();
    switch (getMetadataAddress()) {
    case TypeMetadataAddress::FullMetadata:
      // For imported types, the full metadata object is a candidate
      // for uniquing.
      if (getDeclLinkage(nominal) == FormalLinkage::PublicNonUnique)
        return SILLinkage::Shared;

      // Prespecialization of the same generic metadata may be requested
      // multiple times within the same module, so it needs to be uniqued.
      if (nominal->isGenericContext())
        return SILLinkage::Shared;

      // The full metadata object is private to the containing module.
      return SILLinkage::Private;
    case TypeMetadataAddress::AddressPoint: {
      return getSILLinkage(nominal
                           ? getDeclLinkage(nominal)
                           : FormalLinkage::PublicUnique,
                           forDefinition);
    }
    }
    llvm_unreachable("bad kind");
  }

  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
    // Prespecialization of the same non-canonical generic metadata may be
    // requested multiple times, so it needs to be uniqued.
    return SILLinkage::Shared;

  // ...but we don't actually expose individual value witnesses (right now).
  case Kind::ValueWitness: {
    auto *nominal = getType().getAnyNominal();
    if (getDeclLinkage(nominal) == FormalLinkage::PublicNonUnique)
      return SILLinkage::Shared;
    assert(forDefinition);
    return SILLinkage::Private;
  }

  case Kind::TypeMetadataAccessFunction:
    switch (getTypeMetadataAccessStrategy(getType())) {
    case MetadataAccessStrategy::PublicUniqueAccessor:
      return getSILLinkage(FormalLinkage::PublicUnique, forDefinition);
    case MetadataAccessStrategy::HiddenUniqueAccessor:
      return getSILLinkage(FormalLinkage::HiddenUnique, forDefinition);
    case MetadataAccessStrategy::PrivateAccessor:
      return getSILLinkage(FormalLinkage::Private, forDefinition);
    case MetadataAccessStrategy::ForeignAccessor:
    case MetadataAccessStrategy::NonUniqueAccessor:
      return SILLinkage::Shared;
    }
    llvm_unreachable("bad metadata access kind");

  case Kind::CanonicalSpecializedGenericTypeMetadataAccessFunction:
    return SILLinkage::Shared;

  case Kind::ObjCClassRef:
    return SILLinkage::Private;

  // Continuation prototypes need to be external or else LLVM will fret.
  case Kind::CoroutineContinuationPrototype:
    return SILLinkage::PublicExternal;

  case Kind::ObjCResilientClassStub: {
    switch (getMetadataAddress()) {
    case TypeMetadataAddress::FullMetadata:
      // The full class stub object is private to the containing module,
      // except for foreign types.
      return SILLinkage::Private;
    case TypeMetadataAddress::AddressPoint: {
      auto *classDecl = cast<ClassDecl>(getDecl());
      return getSILLinkage(getDeclLinkage(classDecl),
                           forDefinition);
    }
    }
    llvm_unreachable("invalid metadata address");
  }

  case Kind::EnumCase: {
    auto *elementDecl = cast<EnumElementDecl>(getDecl());
    return getSILLinkage(getDeclLinkage(elementDecl), forDefinition);
  }

  case Kind::FieldOffset: {
    auto *varDecl = cast<VarDecl>(getDecl());

    auto linkage = getDeclLinkage(varDecl);

    // Classes with resilient storage don't expose field offset symbols.
    if (cast<ClassDecl>(varDecl->getDeclContext())->isResilient()) {
      assert(linkage != FormalLinkage::PublicNonUnique &&
            "Cannot have a resilient class with non-unique linkage");

      if (linkage == FormalLinkage::PublicUnique)
        linkage = FormalLinkage::HiddenUnique;
    }

    return getSILLinkage(linkage, forDefinition);
  }

  case Kind::PropertyDescriptor: {
    // Return the linkage of the getter, which may be more permissive than the
    // property itself (for instance, with a private/internal property whose
    // accessor is @inlinable or @usableFromInline)
    auto getterDecl = cast<AbstractStorageDecl>(getDecl())
      ->getOpaqueAccessor(AccessorKind::Get);
    return getSILLinkage(getDeclLinkage(getterDecl), forDefinition);
  }

  case Kind::OpaqueTypeDescriptor: {
    auto *opaqueType = cast<OpaqueTypeDecl>(getDecl());

    // The opaque result type descriptor with availability conditions
    // has to be emitted into a client module when associated with
    // `@_alwaysEmitIntoClient` declaration which means it's linkage
    // has to be "shared".
    if (opaqueType->hasConditionallyAvailableSubstitutions()) {
      if (auto *srcDecl = opaqueType->getNamingDecl()) {
        if (srcDecl->getAttrs().hasAttribute<AlwaysEmitIntoClientAttr>())
          return SILLinkage::Shared;
      }
    }

    return getSILLinkage(getDeclLinkage(opaqueType), forDefinition);
  }

  case Kind::AssociatedConformanceDescriptor:
  case Kind::BaseConformanceDescriptor:
  case Kind::ObjCClass:
  case Kind::ObjCMetaclass:
  case Kind::SwiftMetaclassStub:
  case Kind::NominalTypeDescriptor:
  case Kind::NominalTypeDescriptorRecord:
  case Kind::ClassMetadataBaseOffset:
  case Kind::ProtocolDescriptor:
  case Kind::ProtocolDescriptorRecord:
  case Kind::ProtocolRequirementsBaseDescriptor:
  case Kind::MethodLookupFunction:
  case Kind::OpaqueTypeDescriptorRecord:
  case Kind::OpaqueTypeDescriptorAccessor:
  case Kind::OpaqueTypeDescriptorAccessorImpl:
  case Kind::OpaqueTypeDescriptorAccessorKey:
  case Kind::OpaqueTypeDescriptorAccessorVar:
    return getSILLinkage(getDeclLinkage(getDecl()), forDefinition);

  case Kind::CanonicalSpecializedGenericSwiftMetaclassStub:
    // Prespecialization of the same generic class' metaclass may be requested
    // multiple times within the same module, so it needs to be uniqued.
    return SILLinkage::Shared;

  case Kind::AssociatedTypeDescriptor:
    return getSILLinkage(getDeclLinkage(getAssociatedType()->getProtocol()),
                         forDefinition);

  case Kind::ProtocolWitnessTable:
  case Kind::ProtocolConformanceDescriptor:
  case Kind::ProtocolConformanceDescriptorRecord:
    return getLinkageForProtocolConformance(getRootProtocolConformance(),
                                            forDefinition);

  case Kind::ProtocolWitnessTablePattern:
    if (getLinkageAsConformance() == SILLinkage::Shared)
      return SILLinkage::Shared;
    return SILLinkage::Private;

  case Kind::ProtocolWitnessTableLazyAccessFunction:
  case Kind::ProtocolWitnessTableLazyCacheVariable: {
    auto ty = getType();
    ValueDecl *nominal = nullptr;
    if (auto *otat = ty->getAs<OpaqueTypeArchetypeType>()) {
      nominal = otat->getDecl();
    } else {
      nominal = ty->getAnyNominal();
    }
    assert(nominal);
    if (getDeclLinkage(nominal) == FormalLinkage::Private ||
        getLinkageAsConformance() == SILLinkage::Private) {
      return SILLinkage::Private;
    } else {
      return SILLinkage::Shared;
    }
  }

  case Kind::AssociatedTypeWitnessTableAccessFunction:
  case Kind::DefaultAssociatedConformanceAccessor:
  case Kind::GenericProtocolWitnessTableInstantiationFunction:
  case Kind::CanonicalPrespecializedGenericTypeCachingOnceToken:
    return SILLinkage::Private;

  case Kind::DynamicallyReplaceableFunctionKey:
    return getSILFunction()->getLinkage();

  case Kind::SILFunction:
    return getSILFunction()->getEffectiveSymbolLinkage();

  case Kind::AsyncFunctionPointerAST:
  case Kind::DistributedThunkAsyncFunctionPointer:
    return getSILLinkage(getDeclLinkage(getDecl()), forDefinition);

  case Kind::DynamicallyReplaceableFunctionImpl:
  case Kind::DynamicallyReplaceableFunctionKeyAST:
    return getSILLinkage(getDeclLinkage(getDecl()), forDefinition);

  case Kind::DynamicallyReplaceableFunctionVariable:
    return getSILFunction()->getEffectiveSymbolLinkage();
  case Kind::DynamicallyReplaceableFunctionVariableAST:
    return getSILLinkage(getDeclLinkage(getDecl()), forDefinition);

  case Kind::SILGlobalVariable:
  case Kind::ReadOnlyGlobalObject:
    return getSILGlobalVariable()->getLinkage();

  case Kind::ReflectionBuiltinDescriptor:
  case Kind::ReflectionFieldDescriptor: {
    // Reflection descriptors for imported types have shared linkage,
    // since we may emit them in other TUs in the same module.
    if (auto *nominal = getType().getAnyNominal())
      if (getDeclLinkage(nominal) == FormalLinkage::PublicNonUnique)
        return SILLinkage::Shared;
    return SILLinkage::Private;
  }
  case Kind::ReflectionAssociatedTypeDescriptor:
    if (getLinkageAsConformance() == SILLinkage::Shared)
      return SILLinkage::Shared;
    return SILLinkage::Private;

  case Kind::ModuleDescriptor:
  case Kind::ExtensionDescriptor:
  case Kind::AnonymousDescriptor:
    return SILLinkage::Shared;
  case Kind::DifferentiabilityWitness:
    return getSILDifferentiabilityWitness()->getLinkage();

  case Kind::AsyncFunctionPointer:
  case Kind::DispatchThunkAsyncFunctionPointer:
  case Kind::DispatchThunkInitializerAsyncFunctionPointer:
  case Kind::DispatchThunkAllocatorAsyncFunctionPointer:
  case Kind::PartialApplyForwarderAsyncFunctionPointer:
  case Kind::DistributedAccessorAsyncPointer:
    return getUnderlyingEntityForAsyncFunctionPointer()
        .getLinkage(forDefinition);
  case Kind::KnownAsyncFunctionPointer:
    return SILLinkage::PublicExternal;
  case Kind::PartialApplyForwarder:
  case Kind::DistributedAccessor:
  case Kind::AccessibleFunctionRecord:
    return SILLinkage::Private;
  case Kind::ExtendedExistentialTypeShape:
    return (isExtendedExistentialTypeShapeShared()
              ? SILLinkage::Shared : SILLinkage::Private);
  }
  llvm_unreachable("bad link entity kind");
}

bool LinkEntity::isContextDescriptor() const {
  switch (getKind()) {
  case Kind::ModuleDescriptor:
  case Kind::ExtensionDescriptor:
  case Kind::AnonymousDescriptor:
  case Kind::NominalTypeDescriptor:
  case Kind::ProtocolDescriptor:
  case Kind::OpaqueTypeDescriptor:
    return true;
  case Kind::AsyncFunctionPointer:
  case Kind::AsyncFunctionPointerAST:
  case Kind::DistributedThunkAsyncFunctionPointer:
  case Kind::PropertyDescriptor:
  case Kind::DispatchThunk:
  case Kind::DispatchThunkDerivative:
  case Kind::DispatchThunkInitializer:
  case Kind::DispatchThunkAllocator:
  case Kind::DispatchThunkAsyncFunctionPointer:
  case Kind::DispatchThunkInitializerAsyncFunctionPointer:
  case Kind::DispatchThunkAllocatorAsyncFunctionPointer:
  case Kind::PartialApplyForwarderAsyncFunctionPointer:
  case Kind::DistributedAccessorAsyncPointer:
  case Kind::MethodDescriptor:
  case Kind::MethodDescriptorDerivative:
  case Kind::MethodDescriptorInitializer:
  case Kind::MethodDescriptorAllocator:
  case Kind::MethodLookupFunction:
  case Kind::EnumCase:
  case Kind::FieldOffset:
  case Kind::ObjCClass:
  case Kind::ObjCClassRef:
  case Kind::ObjCMetaclass:
  case Kind::ObjCMetadataUpdateFunction:
  case Kind::ObjCResilientClassStub:
  case Kind::SwiftMetaclassStub:
  case Kind::ClassMetadataBaseOffset:
  case Kind::TypeMetadataPattern:
  case Kind::TypeMetadataInstantiationCache:
  case Kind::TypeMetadataInstantiationFunction:
  case Kind::TypeMetadataSingletonInitializationCache:
  case Kind::TypeMetadataCompletionFunction:
  case Kind::NominalTypeDescriptorRecord:
  case Kind::OpaqueTypeDescriptorRecord:
  case Kind::ProtocolDescriptorRecord:
  case Kind::ProtocolRequirementsBaseDescriptor:
  case Kind::AssociatedTypeDescriptor:
  case Kind::AssociatedConformanceDescriptor:
  case Kind::BaseConformanceDescriptor:
  case Kind::DefaultAssociatedConformanceAccessor:
  case Kind::SILFunction:
  case Kind::SILGlobalVariable:
  case Kind::ReadOnlyGlobalObject:
  case Kind::ProtocolWitnessTable:
  case Kind::ProtocolWitnessTablePattern:
  case Kind::GenericProtocolWitnessTableInstantiationFunction:
  case Kind::AssociatedTypeWitnessTableAccessFunction:
  case Kind::ReflectionAssociatedTypeDescriptor:
  case Kind::ProtocolConformanceDescriptor:
  case Kind::ProtocolConformanceDescriptorRecord:
  case Kind::ProtocolWitnessTableLazyAccessFunction:
  case Kind::ProtocolWitnessTableLazyCacheVariable:
  case Kind::ValueWitness:
  case Kind::ValueWitnessTable:
  case Kind::TypeMetadata:
  case Kind::TypeMetadataAccessFunction:
  case Kind::CanonicalSpecializedGenericTypeMetadataAccessFunction:
  case Kind::TypeMetadataLazyCacheVariable:
  case Kind::TypeMetadataDemanglingCacheVariable:
  case Kind::ReflectionBuiltinDescriptor:
  case Kind::ReflectionFieldDescriptor:
  case Kind::CoroutineContinuationPrototype:
  case Kind::DynamicallyReplaceableFunctionVariableAST:
  case Kind::DynamicallyReplaceableFunctionKeyAST:
  case Kind::DynamicallyReplaceableFunctionImpl:
  case Kind::DynamicallyReplaceableFunctionKey:
  case Kind::DynamicallyReplaceableFunctionVariable:
  case Kind::OpaqueTypeDescriptorAccessor:
  case Kind::OpaqueTypeDescriptorAccessorImpl:
  case Kind::OpaqueTypeDescriptorAccessorKey:
  case Kind::OpaqueTypeDescriptorAccessorVar:
  case Kind::DifferentiabilityWitness:
  case Kind::CanonicalSpecializedGenericSwiftMetaclassStub:
  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
  case Kind::CanonicalPrespecializedGenericTypeCachingOnceToken:
  case Kind::PartialApplyForwarder:
  case Kind::KnownAsyncFunctionPointer:
  case Kind::DistributedAccessor:
  case Kind::AccessibleFunctionRecord:
  case Kind::ExtendedExistentialTypeShape:
    return false;
  }
  llvm_unreachable("invalid descriptor");
}

llvm::Type *LinkEntity::getDefaultDeclarationType(IRGenModule &IGM) const {
  switch (getKind()) {
  case Kind::ModuleDescriptor:
  case Kind::ExtensionDescriptor:
  case Kind::AnonymousDescriptor:
  case Kind::NominalTypeDescriptor:
  case Kind::NominalTypeDescriptorRecord:
  case Kind::PropertyDescriptor:
    return IGM.TypeContextDescriptorTy;
  case Kind::OpaqueTypeDescriptor:
  case Kind::OpaqueTypeDescriptorRecord:
    return IGM.OpaqueTypeDescriptorTy;
  case Kind::ProtocolDescriptor:
    return IGM.ProtocolDescriptorStructTy;
  case Kind::AssociatedTypeDescriptor:
  case Kind::AssociatedConformanceDescriptor:
  case Kind::BaseConformanceDescriptor:
  case Kind::ProtocolDescriptorRecord:
  case Kind::ProtocolRequirementsBaseDescriptor:
    return IGM.ProtocolRequirementStructTy;
  case Kind::ProtocolConformanceDescriptor:
  case Kind::ProtocolConformanceDescriptorRecord:
    return IGM.ProtocolConformanceDescriptorTy;
  case Kind::ObjCClassRef:
    return IGM.ObjCClassPtrTy;
  case Kind::ObjCClass:
  case Kind::ObjCMetaclass:
  case Kind::SwiftMetaclassStub:
  case Kind::CanonicalSpecializedGenericSwiftMetaclassStub:
    return IGM.ObjCClassStructTy;
  case Kind::TypeMetadataLazyCacheVariable:
  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
    return IGM.TypeMetadataPtrTy;
  case Kind::TypeMetadataDemanglingCacheVariable:
    return llvm::StructType::get(IGM.Int32Ty, IGM.Int32Ty);
  case Kind::TypeMetadataSingletonInitializationCache:
    // TODO: put a cache variable on IGM
    return llvm::StructType::get(IGM.getLLVMContext(),
                                 {IGM.TypeMetadataPtrTy, IGM.Int8PtrTy});
  case Kind::TypeMetadata:
  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
    switch (getMetadataAddress()) {
    case TypeMetadataAddress::FullMetadata:
      if (getType().getClassOrBoundGenericClass())
        return IGM.FullHeapMetadataStructTy;
      else
        return IGM.FullTypeMetadataStructTy;
    case TypeMetadataAddress::AddressPoint:
      return IGM.TypeMetadataStructTy;
    }
    llvm_unreachable("invalid metadata address");

  case Kind::TypeMetadataPattern:
    // TODO: Use a real type?
    return IGM.Int8Ty;

  case Kind::ClassMetadataBaseOffset:
    // TODO: put a cache variable on IGM
    return llvm::StructType::get(IGM.getLLVMContext(), {
      IGM.SizeTy,  // Immediate members offset
      IGM.Int32Ty, // Negative size in words
      IGM.Int32Ty  // Positive size in words
    });

  case Kind::TypeMetadataInstantiationCache:
    // TODO: put a cache variable on IGM
    return llvm::ArrayType::get(IGM.Int8PtrTy,
                                NumGenericMetadataPrivateDataWords);
  case Kind::ReflectionBuiltinDescriptor:
  case Kind::ReflectionFieldDescriptor:
  case Kind::ReflectionAssociatedTypeDescriptor:
    return IGM.FieldDescriptorTy;
  case Kind::ValueWitnessTable: // TODO: use ValueWitnessTableTy
  case Kind::ProtocolWitnessTable:
  case Kind::ProtocolWitnessTablePattern:
    return IGM.WitnessTableTy;
  case Kind::FieldOffset:
    return IGM.SizeTy;
  case Kind::EnumCase:
    return IGM.Int32Ty;
  case Kind::ProtocolWitnessTableLazyCacheVariable:
    return IGM.WitnessTablePtrTy;
  case Kind::SILFunction:
    return IGM.FunctionPtrTy->getPointerTo();
  case Kind::MethodDescriptor:
  case Kind::MethodDescriptorInitializer:
  case Kind::MethodDescriptorAllocator:
  case Kind::MethodDescriptorDerivative:
    return IGM.MethodDescriptorStructTy;
  case Kind::DynamicallyReplaceableFunctionKey:
  case Kind::OpaqueTypeDescriptorAccessorKey:
    return IGM.DynamicReplacementKeyTy;
  case Kind::DynamicallyReplaceableFunctionVariable:
  case Kind::OpaqueTypeDescriptorAccessorVar:
    return IGM.DynamicReplacementLinkEntryTy;
  case Kind::ObjCMetadataUpdateFunction:
    return IGM.ObjCUpdateCallbackTy;
  case Kind::ObjCResilientClassStub:
    switch (getMetadataAddress()) {
    case TypeMetadataAddress::FullMetadata:
      return IGM.ObjCFullResilientClassStubTy;
    case TypeMetadataAddress::AddressPoint:
      return IGM.ObjCResilientClassStubTy;
    }
    llvm_unreachable("invalid metadata address");
  case Kind::DifferentiabilityWitness:
    return IGM.DifferentiabilityWitnessTy;
  case Kind::CanonicalPrespecializedGenericTypeCachingOnceToken:
    return IGM.OnceTy;
  case Kind::AsyncFunctionPointer:
  case Kind::DispatchThunkAsyncFunctionPointer:
  case Kind::DispatchThunkInitializerAsyncFunctionPointer:
  case Kind::DispatchThunkAllocatorAsyncFunctionPointer:
  case Kind::DistributedThunkAsyncFunctionPointer:
  case Kind::PartialApplyForwarderAsyncFunctionPointer:
  case Kind::DistributedAccessorAsyncPointer:
  case Kind::AsyncFunctionPointerAST:
  case Kind::KnownAsyncFunctionPointer:
    return IGM.AsyncFunctionPointerTy;
  case Kind::PartialApplyForwarder:
    return IGM.FunctionPtrTy;
  case Kind::AccessibleFunctionRecord:
    return IGM.AccessibleFunctionRecordTy;
  case Kind::ExtendedExistentialTypeShape:
    return IGM.RelativeAddressTy;
  default:
    llvm_unreachable("declaration LLVM type not specified");
  }
}

Alignment LinkEntity::getAlignment(IRGenModule &IGM) const {
  switch (getKind()) {
  case Kind::ModuleDescriptor:
  case Kind::ExtensionDescriptor:
  case Kind::AnonymousDescriptor:
  case Kind::NominalTypeDescriptor:
  case Kind::NominalTypeDescriptorRecord:
  case Kind::ProtocolDescriptor:
  case Kind::ProtocolDescriptorRecord:
  case Kind::AssociatedTypeDescriptor:
  case Kind::AssociatedConformanceDescriptor:
  case Kind::BaseConformanceDescriptor:
  case Kind::ProtocolConformanceDescriptor:
  case Kind::ProtocolConformanceDescriptorRecord:
  case Kind::ProtocolRequirementsBaseDescriptor:
  case Kind::ReflectionBuiltinDescriptor:
  case Kind::ReflectionFieldDescriptor:
  case Kind::ReflectionAssociatedTypeDescriptor:
  case Kind::PropertyDescriptor:
  case Kind::EnumCase:
  case Kind::MethodDescriptor:
  case Kind::MethodDescriptorInitializer:
  case Kind::MethodDescriptorAllocator:
  case Kind::OpaqueTypeDescriptor:
  case Kind::OpaqueTypeDescriptorRecord:
  case Kind::AccessibleFunctionRecord:
  case Kind::ExtendedExistentialTypeShape:
    return Alignment(4);
  case Kind::AsyncFunctionPointer:
  case Kind::DispatchThunkAsyncFunctionPointer:
  case Kind::DispatchThunkInitializerAsyncFunctionPointer:
  case Kind::DispatchThunkAllocatorAsyncFunctionPointer:
  case Kind::PartialApplyForwarderAsyncFunctionPointer:
  case Kind::DistributedAccessorAsyncPointer:
  case Kind::KnownAsyncFunctionPointer:
  case Kind::ObjCClassRef:
  case Kind::ObjCClass:
  case Kind::TypeMetadataLazyCacheVariable:
  case Kind::TypeMetadataSingletonInitializationCache:
  case Kind::TypeMetadata:
  case Kind::TypeMetadataPattern:
  case Kind::ClassMetadataBaseOffset:
  case Kind::TypeMetadataInstantiationCache:
  case Kind::ValueWitnessTable:
  case Kind::FieldOffset:
  case Kind::ProtocolWitnessTableLazyCacheVariable:
  case Kind::ProtocolWitnessTable:
  case Kind::ProtocolWitnessTablePattern:
  case Kind::ObjCMetaclass:
  case Kind::SwiftMetaclassStub:
  case Kind::CanonicalSpecializedGenericSwiftMetaclassStub:
  case Kind::DynamicallyReplaceableFunctionVariable:
  case Kind::DynamicallyReplaceableFunctionKey:
  case Kind::OpaqueTypeDescriptorAccessorKey:
  case Kind::OpaqueTypeDescriptorAccessorVar:
  case Kind::ObjCResilientClassStub:
  case Kind::DifferentiabilityWitness:
  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
  case Kind::PartialApplyForwarder:
    return IGM.getPointerAlignment();
  case Kind::CanonicalPrespecializedGenericTypeCachingOnceToken:
  case Kind::TypeMetadataDemanglingCacheVariable:
    return Alignment(8);
  case Kind::SILFunction:
    return Alignment(1);
  default:
    llvm_unreachable("alignment not specified");
  }
}

bool LinkEntity::isWeakImported(ModuleDecl *module) const {
  switch (getKind()) {
  case Kind::SILGlobalVariable:
  case Kind::ReadOnlyGlobalObject:
    if (getSILGlobalVariable()->getDecl()) {
      return getSILGlobalVariable()->getDecl()->isWeakImported(module);
    }
    return false;
  case Kind::DynamicallyReplaceableFunctionKey:
  case Kind::DynamicallyReplaceableFunctionVariable:
  case Kind::SILFunction:
  case Kind::DistributedAccessor: {
    return getSILFunction()->isWeakImported(module);
  }

  case Kind::AssociatedConformanceDescriptor:
  case Kind::DefaultAssociatedConformanceAccessor: {
    // Associated conformance descriptors use the protocol as their declaration
    // and are weak linked if either the protocol or the associated type stored
    // in extra storage area is weak linked.
    if (cast<ProtocolDecl>(getDecl())->isWeakImported(module))
      return true;

    auto assocConformance = getAssociatedConformance();
    auto *depMemTy = assocConformance.first->castTo<DependentMemberType>();
    return depMemTy->getAssocType()->isWeakImported(module);
  }

  case Kind::BaseConformanceDescriptor:
    return cast<ProtocolDecl>(getDecl())->isWeakImported(module);

  case Kind::TypeMetadata:
  case Kind::TypeMetadataAccessFunction: {
    if (auto *nominalDecl = getType()->getAnyNominal())
      return nominalDecl->isWeakImported(module);
    return false;
  }

  case Kind::AsyncFunctionPointerAST:
  case Kind::DistributedThunkAsyncFunctionPointer:
  case Kind::DispatchThunk:
  case Kind::DispatchThunkDerivative:
  case Kind::DispatchThunkInitializer:
  case Kind::DispatchThunkAllocator:
  case Kind::MethodDescriptor:
  case Kind::MethodDescriptorDerivative:
  case Kind::MethodDescriptorInitializer:
  case Kind::MethodDescriptorAllocator:
  case Kind::MethodLookupFunction:
  case Kind::EnumCase:
  case Kind::FieldOffset:
  case Kind::ObjCClass:
  case Kind::ObjCClassRef:
  case Kind::ObjCMetaclass:
  case Kind::SwiftMetaclassStub:
  case Kind::ClassMetadataBaseOffset:
  case Kind::PropertyDescriptor:
  case Kind::NominalTypeDescriptor:
  case Kind::NominalTypeDescriptorRecord:
  case Kind::ModuleDescriptor:
  case Kind::ProtocolDescriptor:
  case Kind::ProtocolDescriptorRecord:
  case Kind::ProtocolRequirementsBaseDescriptor:
  case Kind::AssociatedTypeDescriptor:
  case Kind::DynamicallyReplaceableFunctionKeyAST:
  case Kind::DynamicallyReplaceableFunctionVariableAST:
  case Kind::DynamicallyReplaceableFunctionImpl:
  case Kind::OpaqueTypeDescriptor:
  case Kind::OpaqueTypeDescriptorRecord:
  case Kind::OpaqueTypeDescriptorAccessor:
  case Kind::OpaqueTypeDescriptorAccessorImpl:
  case Kind::OpaqueTypeDescriptorAccessorKey:
  case Kind::OpaqueTypeDescriptorAccessorVar:
    return getDecl()->isWeakImported(module);

  case Kind::CanonicalSpecializedGenericSwiftMetaclassStub:
    return getType()->getClassOrBoundGenericClass()->isWeakImported(module);

  case Kind::ProtocolWitnessTable:
  case Kind::ProtocolConformanceDescriptor:
  case Kind::ProtocolConformanceDescriptorRecord:
    return getProtocolConformance()->getRootConformance()
                                   ->isWeakImported(module);

  case Kind::CanonicalSpecializedGenericTypeMetadataAccessFunction:
  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
  case Kind::CanonicalPrespecializedGenericTypeCachingOnceToken:
    return false;

  // TODO: Revisit some of the below, for weak conformances.
  case Kind::ObjCMetadataUpdateFunction:
  case Kind::ObjCResilientClassStub:
  case Kind::PartialApplyForwarder:
  case Kind::TypeMetadataPattern:
  case Kind::TypeMetadataInstantiationCache:
  case Kind::TypeMetadataInstantiationFunction:
  case Kind::TypeMetadataSingletonInitializationCache:
  case Kind::TypeMetadataCompletionFunction:
  case Kind::ExtensionDescriptor:
  case Kind::AnonymousDescriptor:
  case Kind::ProtocolWitnessTablePattern:
  case Kind::GenericProtocolWitnessTableInstantiationFunction:
  case Kind::AssociatedTypeWitnessTableAccessFunction:
  case Kind::ReflectionAssociatedTypeDescriptor:
  case Kind::ProtocolWitnessTableLazyAccessFunction:
  case Kind::ProtocolWitnessTableLazyCacheVariable:
  case Kind::ValueWitness:
  case Kind::ValueWitnessTable:
  case Kind::TypeMetadataLazyCacheVariable:
  case Kind::TypeMetadataDemanglingCacheVariable:
  case Kind::ReflectionBuiltinDescriptor:
  case Kind::ReflectionFieldDescriptor:
  case Kind::CoroutineContinuationPrototype:
  case Kind::DifferentiabilityWitness:
  case Kind::AccessibleFunctionRecord:
  case Kind::ExtendedExistentialTypeShape:
    return false;

  case Kind::AsyncFunctionPointer:
  case Kind::DispatchThunkAsyncFunctionPointer:
  case Kind::DispatchThunkInitializerAsyncFunctionPointer:
  case Kind::DispatchThunkAllocatorAsyncFunctionPointer:
  case Kind::PartialApplyForwarderAsyncFunctionPointer:
  case Kind::DistributedAccessorAsyncPointer:
    return getUnderlyingEntityForAsyncFunctionPointer()
        .isWeakImported(module);
  case Kind::KnownAsyncFunctionPointer:
    auto &context = module->getASTContext();
    auto deploymentAvailability =
        AvailabilityContext::forDeploymentTarget(context);
    return !deploymentAvailability.isContainedIn(
        context.getConcurrencyAvailability());
  }

  llvm_unreachable("Bad link entity kind");
}

DeclContext *LinkEntity::getDeclContextForEmission() const {
  switch (getKind()) {
  case Kind::AsyncFunctionPointerAST:
  case Kind::DistributedThunkAsyncFunctionPointer:
  case Kind::DispatchThunk:
  case Kind::DispatchThunkDerivative:
  case Kind::DispatchThunkInitializer:
  case Kind::DispatchThunkAllocator:
  case Kind::MethodDescriptor:
  case Kind::MethodDescriptorDerivative:
  case Kind::MethodDescriptorInitializer:
  case Kind::MethodDescriptorAllocator:
  case Kind::MethodLookupFunction:
  case Kind::EnumCase:
  case Kind::FieldOffset:
  case Kind::ObjCClass:
  case Kind::ObjCMetaclass:
  case Kind::SwiftMetaclassStub:
  case Kind::ObjCMetadataUpdateFunction:
  case Kind::ObjCResilientClassStub:
  case Kind::ClassMetadataBaseOffset:
  case Kind::PropertyDescriptor:
  case Kind::NominalTypeDescriptor:
  case Kind::NominalTypeDescriptorRecord:
  case Kind::TypeMetadataPattern:
  case Kind::TypeMetadataInstantiationCache:
  case Kind::TypeMetadataInstantiationFunction:
  case Kind::TypeMetadataSingletonInitializationCache:
  case Kind::TypeMetadataCompletionFunction:
  case Kind::ProtocolDescriptor:
  case Kind::ProtocolDescriptorRecord:
  case Kind::ProtocolRequirementsBaseDescriptor:
  case Kind::AssociatedTypeDescriptor:
  case Kind::AssociatedConformanceDescriptor:
  case Kind::DefaultAssociatedConformanceAccessor:
  case Kind::BaseConformanceDescriptor:
  case Kind::DynamicallyReplaceableFunctionVariableAST:
  case Kind::DynamicallyReplaceableFunctionKeyAST:
  case Kind::DynamicallyReplaceableFunctionImpl:
  case Kind::OpaqueTypeDescriptor:
  case Kind::OpaqueTypeDescriptorRecord:
  case Kind::OpaqueTypeDescriptorAccessor:
  case Kind::OpaqueTypeDescriptorAccessorImpl:
  case Kind::OpaqueTypeDescriptorAccessorKey:
  case Kind::OpaqueTypeDescriptorAccessorVar:
  case Kind::CanonicalPrespecializedGenericTypeCachingOnceToken:
    return getDecl()->getDeclContext();

  case Kind::CanonicalSpecializedGenericSwiftMetaclassStub:
    return getType()->getClassOrBoundGenericClass()->getDeclContext();

  case Kind::SILFunction:
  case Kind::DynamicallyReplaceableFunctionVariable:
  case Kind::DynamicallyReplaceableFunctionKey:
    return getSILFunction()->getDeclContext();

  case Kind::SILGlobalVariable:
  case Kind::ReadOnlyGlobalObject:
    if (auto decl = getSILGlobalVariable()->getDecl())
      return decl->getDeclContext();

    return nullptr;

  case Kind::ProtocolWitnessTable:
  case Kind::ProtocolConformanceDescriptor:
  case Kind::ProtocolConformanceDescriptorRecord:
    return getRootProtocolConformance()->getDeclContext();

  case Kind::ProtocolWitnessTablePattern:
  case Kind::GenericProtocolWitnessTableInstantiationFunction:
  case Kind::AssociatedTypeWitnessTableAccessFunction:
  case Kind::ReflectionAssociatedTypeDescriptor:
  case Kind::ProtocolWitnessTableLazyCacheVariable:
  case Kind::ProtocolWitnessTableLazyAccessFunction:
    return getProtocolConformance()->getDeclContext();

  case Kind::TypeMetadata: {
    auto ty = getType();
    // Only fully concrete nominal type metadata gets emitted eagerly.
    auto nom = ty->getAnyNominal();
    if (nom)
      return nom->getDeclContext();

    return nullptr;
  }

  // Always shared linkage
  case Kind::ModuleDescriptor:
  case Kind::ExtensionDescriptor:
  case Kind::AnonymousDescriptor:
  case Kind::ObjCClassRef:
  case Kind::TypeMetadataAccessFunction:
  case Kind::CanonicalSpecializedGenericTypeMetadataAccessFunction:
  case Kind::TypeMetadataLazyCacheVariable:
  case Kind::TypeMetadataDemanglingCacheVariable:
  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
    assert(isAlwaysSharedLinkage() && "kind should always be shared linkage");
    return nullptr;

  // TODO
  case Kind::CoroutineContinuationPrototype:
  case Kind::ReflectionFieldDescriptor:
  case Kind::ReflectionBuiltinDescriptor:
  case Kind::ValueWitness:
  case Kind::ValueWitnessTable:
  case Kind::DifferentiabilityWitness:
  case Kind::PartialApplyForwarder:
  case Kind::KnownAsyncFunctionPointer:
  case Kind::ExtendedExistentialTypeShape:
    return nullptr;

  case Kind::AsyncFunctionPointer:
  case Kind::DispatchThunkAsyncFunctionPointer:
  case Kind::DispatchThunkInitializerAsyncFunctionPointer:
  case Kind::DispatchThunkAllocatorAsyncFunctionPointer:
  case Kind::PartialApplyForwarderAsyncFunctionPointer:
  case Kind::DistributedAccessorAsyncPointer:
    return getUnderlyingEntityForAsyncFunctionPointer()
        .getDeclContextForEmission();

  case Kind::DistributedAccessor:
  case Kind::AccessibleFunctionRecord: {
    auto *funcDC = getSILFunction()->getDeclContext();
    return funcDC->getParentModule();
  }
  }
  llvm_unreachable("invalid decl kind");
}

bool LinkEntity::isAlwaysSharedLinkage() const {
  switch (getKind()) {
  case Kind::ModuleDescriptor:
  case Kind::ExtensionDescriptor:
  case Kind::AnonymousDescriptor:
  case Kind::ObjCClassRef:
  case Kind::TypeMetadataAccessFunction:
  case Kind::CanonicalSpecializedGenericTypeMetadataAccessFunction:
  case Kind::TypeMetadataLazyCacheVariable:
  case Kind::TypeMetadataDemanglingCacheVariable:
  case Kind::NoncanonicalSpecializedGenericTypeMetadata:
  case Kind::NoncanonicalSpecializedGenericTypeMetadataCacheVariable:
    return true;

  default:
    return false;
  }
}


text:
import java.io.File;

class Main {

  private static File[] <warning descr="Private method 'scanFolder(java.io.File)' is never used">scanFolder</warning>(File javasFolder) {
    return javasFolder.listFiles(Main::checkForJdk);
  }

  public static boolean checkForJdk(String <warning descr="Parameter 'homePath' is never used">homePath</warning>) {return false;}
  public static boolean checkForJdk(File homePath) {return false;}

}

redpajama_set_name: RedPajamaGithub


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Naucoria foetida Velen.

### Remarks
null


text:
#include "luawritedeclaration.h"
//#include "luawriteicondeclaration.h"
#include "luawriteinitialization.h"
//#include "luawriteiconinitialization.h"
//#include "luaextractimages.h"
#include "../driver.h"
#include "../ui4.h"
#include "../uic.h"
#include "../databaseinfo.h"
#include "../customwidgetsinfo.h"

#include <QtCore/qtextstream.h>
#include <QtCore/qdebug.h>

QT_BEGIN_NAMESPACE

namespace LUA {

WriteDeclaration::WriteDeclaration(Uic *uic)  :
    m_uic(uic),
    m_driver(uic->driver()),
    out(uic->output()),
    m_option(uic->option())
{
}

void WriteDeclaration::acceptUI(DomUI *node)
{
	QString qualifiedClassName = node->elementClass() + m_option.postfix;
	QString className = qualifiedClassName;

	QString varName = m_driver->findOrInsertWidget(node->elementWidget());
    QString widgetClassName = node->elementWidget()->attributeClass();

	out << "local ui_" << className << " = {}\n";

	TreeWalker::acceptWidget(node->elementWidget());

	WriteInitialization(m_uic).acceptUI(node);

	out << "return ui_" << className << "\n";

}

void WriteDeclaration::acceptWidget(DomWidget *node)
{
    TreeWalker::acceptWidget(node);
}

void WriteDeclaration::acceptSpacer(DomSpacer *node)
{
     TreeWalker::acceptSpacer(node);
}

void WriteDeclaration::acceptLayout(DomLayout *node)
{
    TreeWalker::acceptLayout(node);
}

void WriteDeclaration::acceptActionGroup(DomActionGroup *node)
{
    TreeWalker::acceptActionGroup(node);
}

void WriteDeclaration::acceptAction(DomAction *node)
{
    TreeWalker::acceptAction(node);
}

void WriteDeclaration::acceptButtonGroup(const DomButtonGroup *buttonGroup)
{
    TreeWalker::acceptButtonGroup(buttonGroup);
}

} // namespace CPP

QT_END_NAMESPACE


text:
module Google
  module Apis
    module CloudfunctionsV1
      # Version of the google-apis-cloudfunctions_v1 gem
      GEM_VERSION = "0.33.0"

      # Version of the code generator used to generate this client
      GENERATOR_VERSION = "0.11.0"

      # Revision of the discovery document this client was generated from
      REVISION = "20220824"
    end
  end
end


text:
require 'spec_helper'

describe Libgss::ActionRequest do

  let(:network) do
    network = new_network
    network.login
    network
  end

  let(:request) do
    network.new_action_request
  end

  describe "ruby_stored_script#execute" do
    before do
      request_fixture_load("01_basic")
      # HP満タンなので、減らす
      req1 = network.new_action_request
      req1.get_by_game_data
      req1.send_request # コールバックなしでもOK

      req1.outputs.length.should == 1
      game_data = req1.outputs.first["result"]
      new_content_attrs = {"hp" => 10} # 5ポイント減らす
      game_data["content"].update(new_content_attrs)
      #
      req2 = network.new_action_request
      req2.update("GameData", game_data)
      req2.send_request
      req2.outputs.first["result"].should == "OK"
    end

    it "valid" do
      callback_called = false
      request.execute("ItemRubyStoredScript", "use_item", {"item_cd" => "20001"})
      request.send_request do |outputs|
        callback_called = true
        outputs.length.should == 1
        outputs.first["result"].should == "recovery hp 5points"
      end
      callback_called.should == true
    end

    it "invalid args" do
      pending "どう振る舞うべきか検討"
      callback_called = false
      request.execute("ItemRubyStoredScript", "use_item", {}) # 引数の指定なし
      request.send_request do |outputs|
        callback_called = true
        outputs.length.should == 1
        outputs.first["result"].should == "recovery hp 5points"
      end
      callback_called.should == true
    end
  end

end


text:
<?php
namespace TFox\PangalinkBundle\Exception;

class AccountNotFoundException extends \Exception
{

    public function __construct($accountId)
    {
        $this->message = 'Account with ID ' . $accountId . ' not found.';
    }
}


text:
@interface IAWModelQuestion : IAWModelObject

@property (strong, nonatomic, readonly) NSString *questionText;
@property (strong, nonatomic, readonly) NSSet *options;

+ (instancetype)createQuestionWithText:(NSString *)text
                           inDatastore:(id<IAWPersistenceDatastoreProtocol>)datastore
                     usingIndexManager:(id<IAWPersistenceDatastoreIndexManagerProtocol>)indexManager
                                 error:(NSError **)error;

+ (instancetype)replaceQuestion:(IAWModelQuestion *)question
                 byAddingOption:(NSString *)option
                    inDatastore:(id<IAWPersistenceDatastoreProtocol>)datastore
                          error:(NSError **)error;

+ (BOOL)deleteQuestion:(IAWModelQuestion *)question
           inDatastore:(id<IAWPersistenceDatastoreProtocol>)datastore
                 error:(NSError **)error;

+ (NSSet *)indexableFieldnames;

+ (NSArray *)allQuestionsInIndexManager:(id<IAWPersistenceDatastoreIndexManagerProtocol>)indexManager;

@end


text:
const chai = global.chai = require('chai')
const expect = global.expect = chai.expect
const should = global.should = chai.should()

// const Promise = require('es6-promise').Promise
// global.Promise = Promise

// const chaiAsPromised = require('chai-as-promised')
// chai.use(chaiAsPromised)

const jsdom = require("jsdom")
const { JSDOM } = jsdom
const dom = new JSDOM(`<html><body></body></html>`)

const { document } = dom.window
global.document = dom.window.document
// global.navigator = dom.window.navigator


text:
code: true
type: page
title: import
description: Performs a bulk import on a collection
---

# Import

Create, update or delete large amount of documents as fast as possible.

This route is faster than the `document:m*` routes family (e.g. [document:mCreate](/sdk/js/7/controllers/document/m-create)), but no real-time notifications will be generated, even if some of the documents in the import match subscription filters.

```js
import (index, collection, bulkData, [options])
```

| Arguments  | Type                | Description                                     |
| ---------- | ------------------- | ----------------------------------------------- |
| `index`      |
string
 | Index name           |
| `collection` |
string
 | Collection name      |
| `bulkData` |
object[]
 | List of documents to be added to the collection |
| `options`  |
object
   | Query options                                   |

### bulkData

This API takes a JSON array containing a list of objects working in pairs.
In each pair, the first object specifies the action to perform (the most common is `create`) and the second specifies the document itself, like in the example below:

```js
[
  // Action object
  { create: { _id: 'id' } },
  // Document object
  { myField: 'myValue', myOtherField: 'myOtherValue' },

  // Another action object
  { create: { _id: 'another-id' } },
  // Another document object
  { myField: 'anotherValue', myOtherField: 'yetAnotherValue' }
];
```

::: warning
You cannot specify either the `_index` or the `_type` options with a bulk import.
You have to specify the index/collection in the request.
:::

Possible actions are `create`, `index`, `update`, `delete`.

Learn more at [Elasticsearch Bulk API](https://www.elastic.co/guide/en/elasticsearch/reference/7.3/docs-bulk.html)

### options

Additional query options

| Property   | Type
(default)              | Description                                                                  |
| ---------- | ------------------------------- | ---------------------------------------------------------------------------- |
| `queuable` |
boolean

(`true`) | If true, queues the request during downtime, until connected to Kuzzle again |
| [`timeout`](/sdk/7/core-classes/kuzzle/query#timeout)  |
number
               | Time (in ms) during which a request will still be waited to be resolved. Set it `-1` if you want to wait indefinitely |

---

## Resolves

Resolves to an object containing 2 properties:

| Property | Type                | Description                                         |
| -------- | ------------------- | --------------------------------------------------- |
| `successes`  |
object[]
 | Array of object containing successful document import |
| `errors` |
object[]
  | Array of object containing failed document import     |

Each item of the `successes` array is an object containing the action name as key and the corresponding object contain the following properties:

| Property | Type                | Description                                         |
| -------- | ------------------- | --------------------------------------------------- |
| `_id`   |
String
   | Document unique identifier      |
| `status`   |
String
   | HTTP status code for that query      |

Each item of the `successes` array is an object containing the action name as key and the corresponding object contain the following properties:

| Property | Type                | Description                                         |
| -------- | ------------------- | --------------------------------------------------- |
| `_id`   |
String
   | Document unique identifier      |
| `status`   |
String
   | HTTP status code for that query      |
| `error`   |
Object
   | Error object      |

Each error object contain the following properties:

| Property | Type                | Description                                         |
| -------- | ------------------- | --------------------------------------------------- |
| `type`  |
String
 | Elasticsearch client error type |
| `reason`  |
String
 | human readable error message |

## Usage

<<< ./snippets/import.js


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title></title>
	<link rel="stylesheet" href="stylesheets/ionicons.min.css"/>
	<link rel="stylesheet" href="stylesheets/alert.css"/>

Something broke.

		<button class="cancel alert-button">Cancel</button>
		<button class="continue alert-button">Yes</button>


text:
<!DOCTYPE html>

<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />

<title>notes_newsite.utf8</title>

<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/cosmo.min.css" rel="stylesheet" />

<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />

<link href="site_libs/highlightjs-9.12.0/textmate.css" rel="stylesheet" />

<link rel="stylesheet" href="styles.css" type="text/css" />

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">

      </button>
      Ben Best, PhD

  Home

  About

  Research

  Teaching

  Software

inspiring sites: - tclavelle: http://tclavelle.github.io using Jekyll http://html5up.net/spectral - jules32: http://hadley.nz like https://github.com/jules32/jules32.github.io - http://www.ericdfournier.com - http://faculty.washington.edu/bmarwick/ - http://lucafoschini.com - ZevRoss Spatial Analysis | Spatial and Environmental Statistics - carousel - About | Services | Clients | Publications - Garth Tarr: Shiny app consulting + Research + Teaching + Blog

cd /Users/bbest/github/jules32.github.io
jekyll serve

TODO:

timeline (Gantt)

see About Agency - Start Bootstrap Theme

great dynamic moving Career chronology section at Jalpc, a JekyllThemes template

carousel

interactive viz embedded inside carousel

slick - the last carousel you'll ever need

ramnathv/slickCarousel: jQuery Slick Carousel HTML Widget for R

Sitemap: - About - Timeline with overlaps (dashed for part-time, solid for full-time) - 1998: BA Aquatic Bio, BS Marine Bio - 1999: DBA European Human Rights Foundation - 2000 - 2002: IT for Bren - 2002 - 2008: Researcher in Marine Geospatial Ecology Lab - 2004 - 2007: MS in Env Sci: HabMod + ConnMod (pt) - 2008 - 2016: PhD in Mar Bio & Cons Mgmt: Habmod + Spatial Decision Frameworks - 201

Teaching

pic of S/W Carpentry

Geospatial

GIS

Adv GIS

Marine GIS

Informatics

Env Info

Ecology

Landscape Ecology

Research

SDM

Spatial Decision Frameworks

Other

Design

Web

Shiny apps

Github & Travis-CI: OHI-Science subcountry

Domain names: - benbestphd.com - bendbest.com - benbest.me - benbest.biz - benbest.consulting - benbest.technology - benbest.tech

Cool themes: - Freelancer - One Page Theme - Start Bootstrap - Hadley Wickham - Agency - One Page Bootstrap Theme - Start Bootstrap - timeline in About - Creative - One Page Bootstrap Theme - Start Bootstrap - cool flash icons - want: - banner on front - menu stays on top as scroll down -

Copyright © 2017. EcoQuants.com, 508 E Haley St, Santa Barbara CA 93103. 805-705-9770


text:
function onSay(cid, words, param)
	local housePrice = configManager.getNumber(configKeys.HOUSE_PRICE)
	if housePrice == -1 then
		return true
	end

	local player = Player(cid)
	if player:getPremiumDays() <= 0 then
		player:sendCancelMessage("You need a premium account.")
		return false
	end

	local position = player:getPosition()
	position:getNextPosition(player:getDirection())

	local house = House(getTileHouseInfo(position))
	if house == nil then
		player:sendCancelMessage("You have to be looking at the door of the house you would like to buy.")
		return false
	end

	if house:getOwnerGuid() > 0 then
		player:sendCancelMessage("This house already has an owner.")
		return false
	end

	if player:getHouse() then
		player:sendCancelMessage("You are already the owner of a house.")
		return false
	end

	local price = house:getTileCount() * housePrice
	if not player:removeMoney(price) then
		player:sendCancelMessage("You do not have enough money.")
		return false
	end

	house:setOwnerGuid(player:getGuid())
	player:sendTextMessage(MESSAGE_INFO_DESCR, "You have successfully bought this house, be sure to have the money for the rent in the bank.")
	return false
end


text:
namespace vd {

class MeshImpl : public IMesh {

public:

    MeshImpl(
            VoidApp& app,
            const std::vector<Vector3> &vertices,
            const std::vector<int> &triangles
    );

    void Draw(const VoidApp &app);

private:

    ci::gl::BatchRef _batch;

};

}


text:
 // Design Basic Game Solo Challenge-- CHRONO BOOTS

// This is a solo challenge

// ------------------------------------------------------

// *@*@*@*@*@* NOTE!! PLEASE SEE THE FINAL VERSION AT: *@*@*@*@*@*@*@*

// https://github.com/clairemation/clairemation.github.io/blob/master/projects/chronoboots/chronoboots.js
// and
// https://github.com/clairemation/clairemation.github.io/blob/master/projects/chronoboots/chronoboots.html

// or running live at:
// https://clairemation.github.io/projects/chronoboots/chronoboots.html

//  IT IS VERY DIFFERENT (and actually works)!

//  The game and my approach changed considerably as I was coding and learning, so at some point I started clean in another file. What is left in this file is an unholy mashup of a bunch of different versions in one file (even the pseudocode is at odds with itself). You could view this as the pseudocode and (nonfunctioning) initial solution, and the other files as the refactored version. (Though they could still stand to have a lot more refactoring done--redundancy reduced, etc.)

// Thanks.

//-----------------------------------------------------

// (This part is updated to reflect the final version.)

// Your mission description: Collect three crystals on a prehistoric lava field, but don't let the lava touch you!

// Overall mission: Help a stranded time traveler collect fuel crystals from era to era so they can return home.

// Goals: Acquire (walk onto) all three crystals on the map

// Characters: Hero

// Objects:
// hero (called 'ampersand' in the code, because I originally used '&' to represent her onscreen)
// crystals list object
// map object
// lava field object
// (On the html page: a display table, message boxes, buttons.)

// (Below here it's all a mix of different versions--originally you were picking up gears, not crystals, and bringing them to a base. The lava was a tar pit that didn't kill you but made you drop your gears.)

// Functions:
// map:
// -display
// -write to tile
// -read tile

// ampersand:
// -return current position
// -move
// -add item to inventory
// -lose item from inventory

// lava controller:
// -expand (turn random empty tile neighboring a lava tile into a lava tile)
// -contract (turn a random lava tile into an empty tile)
// -if Ampersand is on a lava tile, remove 1 item from her inventory, deposit it on random empty tile

// base camp:
// add item to inventory and check if goal reached

// Pseudocode
//
// general program flow:

// REPEAT {
//   status = turn()
//   IF status = gameOver, call gameOverHandler
//   IF status = win, call winHandler
// }

// function gameOverHandler {
//   print "Ouch! Boiled in lava! Game Over.\nYou collected x gears."
// }

// function winHandler {
//   print "Great job! You got all three gears! On to the next era!"
// }

// function turn() = {
//
//  drawScreen()
//
//  prompt command UNTIL you get a viable direction
//  REPEAT {
//   shift lava
//   move ampersand one tile in designated direction
//   sleep 0.2s
//   display map
//   IF this tile == any lava tile, return gameOver (end turn, lose)
//  } UNTIL this tile == any node tile
//
//  IF this tile == any fieldGear tile, add 1 to amp's inventory and remove gear from field

//  IF inventory == totalGears, return win

//  return continue (next turn, no win or lose)
// }

//  nodes = [[y,x], [y,x], [y,x]...] <--list of node points on map

//  fieldGears = [[y,x], [y,x], [y,x]] <-- coords of gears on the field

//  totalGears = 3

// baseMap = [
//        123456789ABCDEFGHIJKLMNOPQRST
//    1 ["   •---•---------•-----•     "]
//    2 ["   |   |         |     |     "]
//    3 ["•--•---•------•--•--•--•--•  "]
//    4 ["• |   |      |     |     |  "]
//    5 ["A••   |  •---•     •--•--•  "]
//    6 ["|      |  |            |     "]
//    7 ["•------•--•------------•-----"]
//  ]
//  top & left coords -- for reference only
//  A = base camp

//  liveMap = [
//        123456789ABCDEFGHIJKLMNOPQRST
//    1 ["   •---@---------•-----@     "]
//    2 ["   |   | ####    |     | ### "]
//    3 ["•--•---•--#---@--•--•--•-##  "]
//    4 ["|  |   |      | ##  |     |  "]
//    5 ["A&-•   |  •---•  #  •--•--•  "]
//    6 ["|      |  |   ####     |     "]
//    7 ["•------•--•------------•-----"]
//  ]
// (for instance)
// & = Dr. Ampersand
// @ = gear
// # = tar

//  function drawScreen: {
//  output "Inventory: x gears"
//  output EACH row of liveMap() as a string
//  }
//

// function liveMap() {
//   dupe baseMap -> displayMap
//   draw EACH lava tile to displayMap
//   draw EACH field gear to displayMap
//   draw Ampersand to displayMap
//   return displayMap
// }

// ampersand {

//   x = whatever
//   y = whatever
//   gears = 0
// }

// lavaController {

//   tiles = [[y,x], [y, x], [y, x]...]
//   borderTiles = ditto

//  function shift() {
//   3x expand() {
//      REPEAT {pop random tile from borderTiles array} UNTIL it's not a gear tile
//      push it to lava tiles array
//      for EACH neighboring tile to left, right, up, down
//        IF it's not a lava tile, add to borderTiles array
//   }

//   2x contract() {
//      pop random tile from tiles array
//      push it to borderTiles array
//      for EACH of its neighbors to left, right, up, down {
//        IF it is in borderTiles && NONE of it its neighbors are lava
//          {delete it from borderTiles}
//        }
//   }

// }

  // [
 //                  1         2
 //        01234567890123456789012345678
 //*0*/   "   •---@---------•-----@     ".split(""),
 // /*1*/ "   |   | ####    |     | ### ".split(""),
 // /*2*/ "•--•---•--#---@--•--•--•-##  ".split(""),
 // /*3*/ "|  |   |      | ##  |     |  ".split(""),
 // /*4*/ "•--•   |  •---•  #  •--•--•  ".split(""),
 // /*5*/ "|      |  |   ####     |     ".split(""),
 // /*6*/ "&------•--•------------•----•".split("")
 // ]

//

// INITIAL CODE==============================================

// environment variables------------------------------------------
var totalCrystals = 3;
var status = 'ok';

// map--------------------------------------------------

var map = {

  baseMap: [
   "   •---•---------•-----•     ".split(""),
   "   |   |         |     |     ".split(""),
   "•--•---•------•--•--•--•--•  ".split(""),
   "|  |   |      |     |     |  ".split(""),
   "•--•   |  •---•     •--•--•  ".split(""),
   "|      |  |            |     ".split(""),
   "•------•--•------------•----•".split("")
   ],

   displayMap: [
   "   •---•---------•-----•     ".split(""),
   "   |   |         |     |     ".split(""),
   "•--•---•------•--•--•--•--•  ".split(""),
   "|  |   |      |     |     |  ".split(""),
   "•--•   |  •---•     •--•--•  ".split(""),
   "|      |  |            |     ".split(""),
   "•------•--•------------•----•".split("")
   ],

}

// world objects----------------------------------------------

var ampersand = {
  image: '&',
  coords: {y: 6, x: 0}
}

var lava = {
  image: '#',
  coords: [
    {y: 1, x: 9},
    {y: 1, x: 10},
    {y: 1, x: 11},
    {y: 1, x: 12},
    {y: 1, x: 25},
    {y: 1, x: 26},
    {y: 1, x: 27},
    {y: 4, x: 16},
    {y: 4, x: 17},
    {y: 5, x: 17},
    {y: 6, x: 14},
    {y: 6, x: 15},
    {y: 6, x: 16},
    {y: 6, x: 17}
  ],
  shift: function() {
    //TODO -- expand and contract lava fields
  }
}

var crystals = {
  image: '◊',
  coords: [
    {y: 2, x: 17},
    {y: 0, x: 23},
    {y: 2, x: 4}
        ]
}

// functions---------------------------------------------------------------------

var updateDisplayMap = function() {

  //draw ampersand to display map
  map.displayMap[ampersand.coords.y][ampersand.coords.x] = ampersand.image;

  //draw lava tiles
  for (var i in lava.coords){
    y = lava.coords[i].y;
    x = lava.coords[i].x;
    map.displayMap[y][x] = lava.image;
  }

  //draw crystals
  for (var i in crystals.coords){
    y = crystals.coords[i].y;
    x = crystals.coords[i].x;
    map.displayMap[y][x] = crystals.image;
  }
}

//------------------------------------------

var drawScreen = function() {
  console.log("Collect " + totalCrystals + " crystals\n");
  for (var line in map.displayMap) {
    console.log(map.displayMap[line].join(""));
  }
}

//------------------------------------------

var gameOverHandler = function() {
  //TODO
}

//------------------------------------------

var winHandler = function() {
  //TODO
}

//------------------------------------------

var main = function(){
  while (true) {
    status = turn();
    if (status == 'lose') {gameOverHandler()}
    if (status == 'win') {winHandler()}
  }
}

//---------------------------------------------

var turn = function(){

  //prompt input until we get a viable direction
  var repeat = false;
  do {
    //prompt command -- placeholder value now
    direction = up;
  } while (repeat);

  //travel towards node
  do {

    lava.shift();

    switch (direction) {
      case 'up': ampersand.coords.y --;
      case 'down': ampersand.coords.y ++;
      case 'left': ampersand.coords.x --;
      case 'right': ampersand.coords.y ++;
    }

    //sleep

    //display map
    updateDisplayMap();
    drawScreen();

    //if you step in lava, return status = lose

  } while (map.baseMap[ampersand.y][ampersand.x] != '•'); // end travel

  //check tile for crystal

  //if remaining crystals = 0, return a win

  //else continue to the next turn
  return 'ok';

} //function turn

// function turn() = {
//
//  drawScreen()
//
//  prompt command UNTIL you get a viable direction
//  REPEAT {
//   shift lava
//   move ampersand one tile in designated direction
//   sleep 0.2s
//   display map
//   IF this tile == any lava tile, return gameOver (end turn, lose)
//  } UNTIL this tile == any node tile
//
//  IF this tile == any fieldGear tile, add 1 to amp's inventory and remove gear from field

//  IF inventory == totalGears, return win

//  return continue (next turn, no win or lose)
// }

// function drawScreen() {
//   console.log(\nCollected: " + ampersand.gears + " gears\n")
//   for (var i = 0; i < liveMap.length; i ++)
//     console.log(liveMap[i].join(""));
//   console.log("\n");
// }

// var ampersand = {
//   gears: 0,
//   y: 2,
//   x: 3,

//   move: function(direction) {

//     switch (direction) {

//       case 'left':
//         // liveMap[this.y][this.x] = baseMap[this.y][this.x]; //erase old spot
//         // var newX = this.x; //set new working X position
//         do {
//           newX --
//         } while ((baseMap[this.y][newX] != '•') && (baseMap[this.y][newX] != '@') && (baseMap[this.y][newX] != '#')); //move working position left until node
//         this.x = newX; //set official X to working X
//         // liveMap[this.y][this.x] = '&'; //draw new position
//         break;

//       case 'right':
//         liveMap[this.y][this.x] = baseMap[this.y][this.x];
//         var newX = this.x;
//         do {
//           newX ++;
//         } while ((baseMap[this.y][newX] != '•') && (baseMap[this.y][newX] != '@') && (baseMap[this.y][newX] != '#'));
//         this.x = newX;
//         liveMap[this.y][this.x] = '&';
//         break;

//       case 'up':
//         liveMap[this.y][this.x] = baseMap[this.y][this.x];
//         var newY = this.y;
//         do {
//           newY --;
//         } while ((baseMap[newY][this.x] != '•') && (baseMap[newY][this.x] != '@') && (baseMap[newY][this.x] != '#'));
//         this.y = newY;
//         liveMap[this.y][this.x] = '&';
//         break;

//       case 'down':
//         liveMap[this.y][this.x] = baseMap[this.y][this.x];
//         var newY = this.y;
//         do {
//           newY ++;
//         } while ((baseMap[newY][this.x] != '•') && (baseMap[newY][this.x] != '@') && (baseMap[newY][this.x] != '#'));
//         this.y = newY;
//         liveMap[this.y][this.x] = '&';
//         break;

//     } //switch (direction)

//   } //move function

// } //ampersand object

// var tarpit = {

//   tarTiles: [
//     [1,9],
//     [1,10],
//     [1,11],
//     [1,12],

//     [1,25],
//     [1,26],
//     [1,27],

//     [2,0],

//     [2,5],
//     [2,6],

//     [3,6],
//     [3,7],
//     [4,7],
//     [5,4],
//     [5,5],
//     [5,6],
//     [5,7]
//   ],

//   contains: function(character){
//     var charPosition = [character.y, character.x];
//     for (var i = 0; i < this.tarTiles.length; i++) {
//       if (charPosition == this.tarTiles[i]) {
//         return true;
//       }
//     }
//     return false;
//   },//contains function

//   washAway: function(gear){
//     ampersand.gears --;
//     liveMap[gear.y][gear.x] = '@';
//   },//washAway function

//   expand: function() {
//     //to do
//   },//expand function

// }//tarpit object

// // MAIN PROGRAM---------------------------------------

// do {

// drawScreen();

// // prompt("Enter a move");

// gameOver = true;

// } while ((!gameOver) && (!win));

// TEST CODE------------------------------------
// drawScreen();
// amp.move('up');
// drawScreen();

// Refactored Code-------------------

// See at https://github.com/clairemation/clairemation.github.io/blob/master/projects/chronoboots/chronoboots.js
// and
// https://github.com/clairemation/clairemation.github.io/blob/master/projects/chronoboots/chronoboots.html

// or running live at:
// https://clairemation.github.io/projects/chronoboots/chronoboots.html

// Reflection-------------------------
//

// -What was the most difficult part of this challenge?
// Maybe not falling down the rabbit hole!

// -What did you learn about creating objects and functions that interact with one another?
// Once I got into integrating the script into html objects, it's like a light came on. I'd been working hard trying to manage the game "clock"/cycles/ticks/whatever you want to call it, but when it was running on the page I could have the character and lava refreshing asynchronously and it was all both simpler and easier to pull off than I anticipated. I have some experience programming, but I've never been able to make something like this, let alone so relatively simply.

// -Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
// Did I! Once I got into using it with html and css, everything was new. Though the whole approach reminded me of HyperCard, this old visual object-scripting language for the Mac that was around when I was a kid, and I only ever played around with a little bit. It was really interesting to read in the (fellow DBC-er's) blog linked on the assignment page that JavaScript in fact derive from HyperCard!

// -How can you access and manipulate properties of objects?
// So far we haven't learned about any way to keep object properties private, so to access one from outside you can simply reference it using either of these notations:
// object.propery or object[property]
// and compare or assign as you would with any variable.
// The bracket notation evaluates the phrase inside the brackets first, so you can use a variable there to access varying properties depending on the program state.


text:
#ifndef VOL_IO_INTERNAL_VOLUME_IO_H
#define VOL_IO_INTERNAL_VOLUME_IO_H

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /*HAVE_CONFIG_H*/

#ifndef  VIOAPI
#if defined(_MSC_VER)
#define  VIOAPI /*__declspec(dllexport)*/
#else
#define  VIOAPI
#endif /* _MSC_VER not defined */
#endif /* VIOAPI not defined */

#include  <volume_io.h>

#endif


text:
#region Copyright

#endregion

using System;
using System.Net;

namespace Kodestruct.Wood.NDS.Entities
{
    public enum MemberMaterialCategory
    {
        Lumber,
        Timber,
        GluedLaminatedTimber,
        Decking
    }
}


text:
package raft

import (
	"errors"

	pb "./raftpb"
	"golang.org/x/next/context"
)

type SnapshotStatus int

const (
	SnapshotFinish  SnapshotStatus = 1
	SnapshotFailure SnapshotStatus = 2
)

var (
	emptyState = pb.HardState{}

	ErrStopped = errors.New("raft:stopped")
)

type SoftState struct {
	Lead      uint64
	RaftState StateType
}

func (a *SoftState) equal(b *SoftState) bool {
	return a.Lead == b.Lead && a.RaftState == b.RaftState
}

type Ready struct {
	*SoftState
	pb.HardState
	ReadStates       []ReadState
	Entries          []pb.Entry
	CommittedEntries []pb.Entry
	Messages         []pb.Message
	MustSync         bool
}

func isHardStateEqual(a, b pb.HardState) bool {
	return a.Term == b.Term && a.Vote == b.Vote && a.Commit == b.Commit
}

func IsEmptyHardState(st pb.HardState) bool {
	return isHardStateEqual(st, emptyState)
}

func IsEmptySnap(sp pb.Snapshot) bool {
	return sp.Metadata.Index == 0
}

func (rd Ready) containsUpdates() bool {
	return rd.SoftState != nil || !IsEmptyHardState(rd.HardState) ||
		!IsEmptySnap(rd.Snapshot) || len(rd.Entries) > 0 ||
		len(rd.CommittedEntries) > 0 || len(rd.Messages) > 0 ||
		len(rd.ReadStates) != 0
}

type Node interface {
	Tick()
	Campaign(ctx context.Context) error
	Propose(ctx context.Context, data []byte) error
	ProposeConfChange(ctx context.Context, cc pb.ConfChange) error
	Step(ctx context.Context, msg pb.Message) error

	Ready() <-chan Ready

	Advance()
	ApplyConfChange(cc pb.ConfChange) *pb.ConfState

	TransferLeadership(ctx context.Context, lead, transferee uint64)

	ReadIndex(ctx context.Context, rctx []byte) error

	Status() Status
	ReportUnreachable(id uint64)
	ReportSnapshot(id uint64, status SnapshotStatus)
	Stop()
}

type Peer struct {
	ID      uint64
	Context []byte
}

func StartNode(c *Config, peers []Peer) Node {
}

func RestartNode(c *Config) Node {
}

type node struct {
	propc      chan pb.Message
	recvc      chan pb.Message
	confc      chan pb.ConfChange
	confstatec chan pb.ConfState
	readyc     chan Ready
	advancec   chan struct{}
	tickc      chan struct{}
	done       chan struct{}
	stop       chan struct{}
	status     chan struct{}

	logger Logger
}

func newNode() node {
}

func (n *node) Stop() {
}

func (n *node) run(r *raft) {
}

func (n *node) Tick() {
}

func (n *node) Campaign(ctx context.Context) error {
}

func (n *node) Propose(ctx context.Context, data []byte) error {
}

func (n *node) Step(ctx context.Context, m pb.Message) error {
}

func (n *node) ProposeConfChange(ctx context.Context, cc pb.ConfChange) error {
}

func (n *node) step(ctx context.Context, m pb.Message) error {
}

func (n *node) Ready() <-chan Ready {
}

func (n *node) Advance() {
}

func (n *node) ApplyConfChange(cc pb.ConfChange) *pb.ConfState {
}

func (n *node) Status() Status {
}

func (n *node) ReportUnreachable(id uint64) {
}

func (n *node) ReportSnapshot(id uint64, status SnapshotStatus) {
}

func (n *node) TransferLeadership(ctx context.Context, lead, transferee uint64) {
}

func (n *node) ReadIndex(ctx context.Context, rctx []byte) error {
}

func newReady(r *raft, prevSoftSt *SoftState, prevHardst pb.HardState) Ready {
}

func MustSync(st, prevst pb.HardState, entsnum int) bool {
}


text:
#include <assert.h>
#include <errno.h>
#include <limits.h>
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "uv.h"
#include "internal.h"
#include "handle-inl.h"
#include "req-inl.h"

/* The only event loop we support right now */
static uv_loop_t uv_default_loop_;

/* uv_once intialization guards */
static uv_once_t uv_init_guard_ = UV_ONCE_INIT;
static uv_once_t uv_default_loop_init_guard_ = UV_ONCE_INIT;

static void uv__crt_invalid_parameter_handler(const wchar_t* expression,
    const wchar_t* function, const wchar_t * file, unsigned int line,
    uintptr_t reserved) {
  /* No-op. */
}

static void uv_init(void) {
  /* Tell Windows that we will handle critical errors. */
  SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX |
               SEM_NOOPENFILEERRORBOX);

  /* Tell the CRT to not exit the application when an invalid parameter is */
  /* passed. The main issue is that invalid FDs will trigger this behavior. */
#if !defined(__MINGW32__) || __MSVCRT_VERSION__ >= 0x800
  _set_invalid_parameter_handler(uv__crt_invalid_parameter_handler);
#endif

  /* Fetch winapi function pointers. This must be done first because other */
  /* intialization code might need these function pointers to be loaded. */
  uv_winapi_init();

  /* Initialize winsock */
  uv_winsock_init();

  /* Initialize FS */
  uv_fs_init();

  /* Initialize signal stuff */
  uv_signals_init();

  /* Initialize console */
  uv_console_init();

  /* Initialize utilities */
  uv__util_init();
}

static void uv_loop_init(uv_loop_t* loop) {
  /* Create an I/O completion port */
  loop->iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 1);
  if (loop->iocp == NULL) {
    uv_fatal_error(GetLastError(), "CreateIoCompletionPort");
  }

  /* To prevent uninitialized memory access, loop->time must be intialized */
  /* to zero before calling uv_update_time for the first time. */
  loop->time = 0;
  loop->last_tick_count = 0;
  uv_update_time(loop);

  QUEUE_INIT(&loop->handle_queue);
  QUEUE_INIT(&loop->active_reqs);
  loop->active_handles = 0;

  loop->pending_reqs_tail = NULL;

  loop->endgame_handles = NULL;

  RB_INIT(&loop->timers);

  loop->check_handles = NULL;
  loop->prepare_handles = NULL;
  loop->idle_handles = NULL;

  loop->next_prepare_handle = NULL;
  loop->next_check_handle = NULL;
  loop->next_idle_handle = NULL;

  memset(&loop->poll_peer_sockets, 0, sizeof loop->poll_peer_sockets);

  loop->active_tcp_streams = 0;
  loop->active_udp_streams = 0;

  loop->timer_counter = 0;
  loop->stop_flag = 0;
}

static void uv_default_loop_init(void) {
  /* Initialize libuv itself first */
  uv__once_init();

  /* Initialize the main loop */
  uv_loop_init(&uv_default_loop_);
}

void uv__once_init(void) {
  uv_once(&uv_init_guard_, uv_init);
}

uv_loop_t* uv_default_loop(void) {
  uv_once(&uv_default_loop_init_guard_, uv_default_loop_init);
  return &uv_default_loop_;
}

uv_loop_t* uv_loop_new(void) {
  uv_loop_t* loop;

  /* Initialize libuv itself first */
  uv__once_init();

  loop = (uv_loop_t*)malloc(sizeof(uv_loop_t));

  if (!loop) {
    uv_fatal_error(ERROR_OUTOFMEMORY, "malloc");
  }

  uv_loop_init(loop);
  return loop;
}

void uv_loop_delete(uv_loop_t* loop) {
  if (loop != &uv_default_loop_) {
    int i;
    for (i = 0; i < ARRAY_SIZE(loop->poll_peer_sockets); i++) {
      SOCKET sock = loop->poll_peer_sockets[i];
      if (sock != 0 && sock != INVALID_SOCKET) {
        closesocket(sock);
      }
    }

    free(loop);
  }
}

int uv_backend_fd(const uv_loop_t* loop) {
  return -1;
}

int uv_backend_timeout(const uv_loop_t* loop) {
  return 0;
}

static void uv_poll(uv_loop_t* loop, int block) {
  DWORD bytes, timeout;
  ULONG_PTR key;
  OVERLAPPED* overlapped;
  uv_req_t* req;

  if (block) {
    timeout = uv_get_poll_timeout(loop);
  } else {
    timeout = 0;
  }

  GetQueuedCompletionStatus(loop->iocp,
                            &bytes,
                            &key,
                            &overlapped,
                            timeout);

  if (overlapped) {
    /* Package was dequeued */
    req = uv_overlapped_to_req(overlapped);
    uv_insert_pending_req(loop, req);
  } else if (GetLastError() != WAIT_TIMEOUT) {
    /* Serious error */
    uv_fatal_error(GetLastError(), "GetQueuedCompletionStatus");
  } else {
    /* We're sure that at least `timeout` milliseconds have expired, but */
    /* this may not be reflected yet in the GetTickCount() return value. */
    /* Therefore we ensure it's taken into account here. */
    uv__time_forward(loop, timeout);
  }
}

static void uv_poll_ex(uv_loop_t* loop, int block) {
  BOOL success;
  DWORD timeout;
  uv_req_t* req;
  OVERLAPPED_ENTRY overlappeds[128];
  ULONG count;
  ULONG i;

  if (block) {
    timeout = uv_get_poll_timeout(loop);
  } else {
    timeout = 0;
  }

  success = pGetQueuedCompletionStatusEx(loop->iocp,
                                         overlappeds,
                                         ARRAY_SIZE(overlappeds),
                                         &count,
                                         timeout,
                                         FALSE);

  if (success) {
    for (i = 0; i < count; i++) {
      /* Package was dequeued */
      req = uv_overlapped_to_req(overlappeds[i].lpOverlapped);
      uv_insert_pending_req(loop, req);
    }
  } else if (GetLastError() != WAIT_TIMEOUT) {
    /* Serious error */
    uv_fatal_error(GetLastError(), "GetQueuedCompletionStatusEx");
  } else if (timeout > 0) {
    /* We're sure that at least `timeout` milliseconds have expired, but */
    /* this may not be reflected yet in the GetTickCount() return value. */
    /* Therefore we ensure it's taken into account here. */
    uv__time_forward(loop, timeout);
  }
}

static int uv__loop_alive(uv_loop_t* loop) {
  return loop->active_handles > 0 ||
         !QUEUE_EMPTY(&loop->active_reqs) ||
         loop->endgame_handles != NULL;
}

int uv_run(uv_loop_t *loop, uv_run_mode mode) {
  int r;
  void (*poll)(uv_loop_t* loop, int block);

  if (pGetQueuedCompletionStatusEx)
    poll = &uv_poll_ex;
  else
    poll = &uv_poll;

  r = uv__loop_alive(loop);
  while (r != 0 && loop->stop_flag == 0) {
    uv_update_time(loop);
    uv_process_timers(loop);

    uv_process_reqs(loop);
    uv_idle_invoke(loop);
    uv_prepare_invoke(loop);

    (*poll)(loop, loop->idle_handles == NULL &&
                  loop->pending_reqs_tail == NULL &&
                  loop->endgame_handles == NULL &&
                  !loop->stop_flag &&
                  (loop->active_handles > 0 ||
                   !QUEUE_EMPTY(&loop->active_reqs)) &&
                  !(mode & UV_RUN_NOWAIT));

    uv_check_invoke(loop);
    uv_process_endgames(loop);

    if (mode == UV_RUN_ONCE) {
      /* UV_RUN_ONCE implies forward progess: at least one callback must have
       * been invoked when it returns. uv__io_poll() can return without doing
       * I/O (meaning: no callbacks) when its timeout expires - which means we
       * have pending timers that satisfy the forward progress constraint.
       *
       * UV_RUN_NOWAIT makes no guarantees about progress so it's omitted from
       * the check.
       */
      uv_update_time(loop);
      uv_process_timers(loop);
    }

    r = uv__loop_alive(loop);
    if (mode & (UV_RUN_ONCE | UV_RUN_NOWAIT))
      break;
  }

  /* The if statement lets the compiler compile it to a conditional store.
   * Avoids dirtying a cache line.
   */
  if (loop->stop_flag != 0)
    loop->stop_flag = 0;

  return r;
}


text:
package org.apache.hadoop.hdfs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.BlockLocation;
import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlock;
import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
import org.apache.hadoop.security.UserGroupInformation;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

public class TestDFSUtil {

  /**
   * Reset to default UGI settings since some tests change them.
   */
  @Before
  public void resetUGI() {
    UserGroupInformation.setConfiguration(new Configuration());
  }

  /**
   * Test conversion of LocatedBlock to BlockLocation
   */
  @Test
  public void testLocatedBlocks2Locations() {
    DatanodeInfo d = DFSTestUtil.getLocalDatanodeInfo();
    DatanodeInfo[] ds = new DatanodeInfo[1];
    ds[0] = d;

    // ok
    ExtendedBlock b1 = new ExtendedBlock("bpid", 1, 1, 1);
    LocatedBlock l1 = new LocatedBlock(b1, ds, 0, false);

    // corrupt
    ExtendedBlock b2 = new ExtendedBlock("bpid", 2, 1, 1);
    LocatedBlock l2 = new LocatedBlock(b2, ds, 0, true);

    List<LocatedBlock> ls = Arrays.asList(l1, l2);
    LocatedBlocks lbs = new LocatedBlocks(10, false, ls, l2, true);

    BlockLocation[] bs = DFSUtil.locatedBlocks2Locations(lbs);

    assertTrue("expected 2 blocks but got " + bs.length, bs.length == 2);

    int corruptCount = 0;
    for (BlockLocation b : bs) {
      if (b.isCorrupt()) {
        corruptCount++;
      }
    }

    assertTrue("expected 1 corrupt files but got " + corruptCount,
        corruptCount == 1);

    // test an empty location
    bs = DFSUtil.locatedBlocks2Locations(new LocatedBlocks());
    assertEquals(0, bs.length);
  }

  @Test
  public void testSubstituteForWildcardAddress() throws IOException {
    assertEquals("foo:12345",
        DFSUtil.substituteForWildcardAddress("0.0.0.0:12345", "foo"));
    assertEquals("127.0.0.1:12345",
        DFSUtil.substituteForWildcardAddress("127.0.0.1:12345", "foo"));
  }

  @Test
  public void testIsValidName() {
    assertFalse(DFSUtil.isValidName("/foo/../bar"));
    assertFalse(DFSUtil.isValidName("/foo//bar"));
    assertTrue(DFSUtil.isValidName("/"));
    assertTrue(DFSUtil.isValidName("/bar/"));
  }

  @Test(timeout = 5000)
  public void testGetSpnegoKeytabKey() {
    HdfsConfiguration conf = new HdfsConfiguration();
    String defaultKey = "default.spengo.key";
    conf.unset(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY);
    assertEquals("Test spnego key in config is null", defaultKey,
        DFSUtil.getSpnegoKeytabKey(conf, defaultKey));

    conf.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY, "");
    assertEquals("Test spnego key is empty", defaultKey,
        DFSUtil.getSpnegoKeytabKey(conf, defaultKey));

    String spengoKey = "spengo.key";
    conf.set(DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY,
        spengoKey);
    assertEquals("Test spnego key is NOT null",
        DFSConfigKeys.DFS_WEB_AUTHENTICATION_KERBEROS_KEYTAB_KEY,
        DFSUtil.getSpnegoKeytabKey(conf, defaultKey));
  }
}