text:
using namespace SourceKit;
using namespace swift;
using namespace swift::ide;
using swift::index::SymbolKind;
using swift::index::SymbolSubKind;
using swift::index::SymbolProperty;
using swift::index::SymbolPropertySet;
using swift::index::SymbolInfo;
using swift::index::SymbolRole;
using swift::index::SymbolRoleSet;

#define KIND(NAME, CONTENT) static UIdent Kind##NAME(CONTENT);
#include "SourceKit/Core/ProtocolUIDs.def"

#define REFACTORING(KIND, NAME, ID) static UIdent Kind##Refactoring##KIND("source.refactoring.kind."#ID);
#include "swift/IDE/RefactoringKinds.def"

static UIdent Attr_IBAction("source.decl.attribute.ibaction");
static UIdent Attr_IBOutlet("source.decl.attribute.iboutlet");
static UIdent Attr_IBDesignable("source.decl.attribute.ibdesignable");
static UIdent Attr_IBInspectable("source.decl.attribute.ibinspectable");
static UIdent Attr_GKInspectable("source.decl.attribute.gkinspectable");
static UIdent Attr_Objc("source.decl.attribute.objc");
static UIdent Attr_ObjcNamed("source.decl.attribute.objc.name");
static UIdent Attr_Private("source.decl.attribute.private");
static UIdent Attr_FilePrivate("source.decl.attribute.fileprivate");
static UIdent Attr_Internal("source.decl.attribute.internal");
static UIdent Attr_Public("source.decl.attribute.public");
static UIdent Attr_Open("source.decl.attribute.open");
static UIdent Attr_Setter_Private("source.decl.attribute.setter_access.private");
static UIdent Attr_Setter_FilePrivate("source.decl.attribute.setter_access.fileprivate");
static UIdent Attr_Setter_Internal("source.decl.attribute.setter_access.internal");
static UIdent Attr_Setter_Public("source.decl.attribute.setter_access.public");
static UIdent Attr_Setter_Open("source.decl.attribute.setter_access.open");
static UIdent EffectiveAccess_Public("source.decl.effective_access.public");
static UIdent EffectiveAccess_Internal("source.decl.effective_access.internal");
static UIdent EffectiveAccess_FilePrivate("source.decl.effective_access.fileprivate");
static UIdent EffectiveAccess_LessThanFilePrivate("source.decl.effective_access.less_than_fileprivate");

std::unique_ptr<LangSupport>
SourceKit::createSwiftLangSupport(SourceKit::Context &SKCtx) {
  return std::unique_ptr<LangSupport>(new SwiftLangSupport(SKCtx));
}

const std::string LangSupport::SynthesizedUSRSeparator = "::SYNTHESIZED::";

namespace {

class UIdentVisitor : public ASTVisitor<UIdentVisitor,
                                        UIdent, UIdent, UIdent, UIdent > {
  const bool IsRef;

public:
  explicit UIdentVisitor(bool IsRef) : IsRef(IsRef) { }

  /// TODO: reconsider whether having a default case is a good idea.
  UIdent visitDecl(const Decl *D) { return UIdent(); }

  UIdent visitFuncDecl(const FuncDecl *D);
  UIdent visitVarDecl(const VarDecl *D);
  UIdent visitParamDecl(const ParamDecl *D);
  UIdent visitExtensionDecl(const ExtensionDecl *D);

#define UID_FOR(CLASS) \
  UIdent visit##CLASS##Decl(const CLASS##Decl *) { \
    return IsRef ? KindRef##CLASS : KindDecl##CLASS; \
  }
  UID_FOR(Class)
  UID_FOR(Struct)
  UID_FOR(Enum)
  UID_FOR(EnumElement)
  UID_FOR(Protocol)
  UID_FOR(TypeAlias)
  UID_FOR(AssociatedType)
  UID_FOR(GenericTypeParam)
  UID_FOR(Constructor)
  UID_FOR(Destructor)
  UID_FOR(Subscript)
  UID_FOR(OpaqueType)
#undef UID_FOR
};

} // anonymous namespace

UIdent UIdentVisitor::visitFuncDecl(const FuncDecl *D) {
  if (auto AD = dyn_cast<AccessorDecl>(D)) {
    return SwiftLangSupport::getUIDForAccessor(AD->getStorage(),
                                               AD->getAccessorKind(),
                                               IsRef);
  }

  if (auto *Op = D->getOperatorDecl()) {
    switch (Op->getKind()) {
    case DeclKind::PrefixOperator:
      return IsRef ? KindRefFunctionPrefixOperator : KindDeclFunctionPrefixOperator;
    case DeclKind::PostfixOperator:
      return IsRef ? KindRefFunctionPostfixOperator : KindDeclFunctionPostfixOperator;
    case DeclKind::InfixOperator:
      return IsRef ? KindRefFunctionInfixOperator : KindDeclFunctionInfixOperator;
    default:
      llvm_unreachable("unexpected operator kind");
    }
  }

  const DeclContext *DC = D->getDeclContext();
  if (DC->isTypeContext()) {
    if (D->isStatic()) {
      if (D->getCorrectStaticSpelling() == StaticSpellingKind::KeywordClass)
        return IsRef ? KindRefMethodClass : KindDeclMethodClass;
      else
        return IsRef ? KindRefMethodStatic : KindDeclMethodStatic;
    }
    return IsRef ? KindRefMethodInstance : KindDeclMethodInstance;
  }
  return IsRef ? KindRefFunctionFree : KindDeclFunctionFree;
}

UIdent UIdentVisitor::visitVarDecl(const VarDecl *D) {
  const DeclContext *DC = D->getDeclContext();
  if (DC->isTypeContext()) {
    if (D->isStatic()) {
      if (D->getCorrectStaticSpelling() == StaticSpellingKind::KeywordClass)
        return IsRef ? KindRefVarClass : KindDeclVarClass;
      else
        return IsRef ? KindRefVarStatic : KindDeclVarStatic;
    }
    return IsRef ? KindRefVarInstance : KindDeclVarInstance;
  }
  if (DC->isLocalContext())
    return IsRef ? KindRefVarLocal : KindDeclVarLocal;
  return IsRef ? KindRefVarGlobal : KindDeclVarGlobal;
}

UIdent UIdentVisitor::visitParamDecl(const ParamDecl *D) {
  // There is no KindRefVarParam. It's not usually an interesting difference.
  return IsRef ? KindRefVarLocal : KindDeclVarParam;
}

UIdent UIdentVisitor::visitExtensionDecl(const ExtensionDecl *D) {
  assert(!IsRef && "reference to an extension ?");
  if (NominalTypeDecl *NTD = D->getExtendedNominal()) {
    if (isa<StructDecl>(NTD))
      return KindDeclExtensionStruct;
    if (isa<ClassDecl>(NTD))
      return KindDeclExtensionClass;
    if (isa<EnumDecl>(NTD))
      return KindDeclExtensionEnum;
    if (isa<ProtocolDecl>(NTD))
      return KindDeclExtensionProtocol;
  }
  return UIdent();
}

namespace {
/// A simple FileSystemProvider that creates an InMemoryFileSystem for a given
/// dictionary of file contents and overlays that on top of the real filesystem.
class InMemoryFileSystemProvider: public SourceKit::FileSystemProvider {
  /// Provides the real filesystem, overlayed with an InMemoryFileSystem that
  /// contains specified files at specified locations.
  llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
  getFileSystem(OptionsDictionary &options, std::string &error) override {
    auto InMemoryFS = llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem>(
        new llvm::vfs::InMemoryFileSystem());

    static UIdent KeyFiles("key.files");
    static UIdent KeyName("key.name");
    static UIdent KeySourceFile("key.sourcefile");
    static UIdent KeySourceText("key.sourcetext");
    bool failed = options.forEach(KeyFiles, [&](OptionsDictionary &file) {
      StringRef name;
      if (!file.valueForOption(KeyName, name)) {
        error = "missing 'key.name'";
        return true;
      }

      StringRef content;
      if (file.valueForOption(KeySourceText, content)) {
        auto buffer = llvm::MemoryBuffer::getMemBufferCopy(content, name);
        InMemoryFS->addFile(name, 0, std::move(buffer));
        return false;
      }

      StringRef mappedPath;
      if (!file.valueForOption(KeySourceFile, mappedPath)) {
        error = "missing 'key.sourcefile' or 'key.sourcetext'";
        return true;
      }

      auto bufferOrErr = llvm::MemoryBuffer::getFile(mappedPath);
      if (auto err = bufferOrErr.getError()) {
        llvm::raw_string_ostream errStream(error);
        errStream << "error reading target file '" << mappedPath
                  << "': " << err.message() << "\n";
        return true;
      }

      auto renamedBuffer = llvm::MemoryBuffer::getMemBufferCopy(
          bufferOrErr.get()->getBuffer(), name);
      InMemoryFS->addFile(name, 0, std::move(renamedBuffer));
      return false;
    });

    if (failed)
      return nullptr;

    auto OverlayFS = llvm::IntrusiveRefCntPtr<llvm::vfs::OverlayFileSystem>(
        new llvm::vfs::OverlayFileSystem(llvm::vfs::getRealFileSystem()));
    OverlayFS->pushOverlay(std::move(InMemoryFS));
    return OverlayFS;
  }
};
}

static void
configureCompletionInstance(std::shared_ptr<CompletionInstance> CompletionInst,
                            std::shared_ptr<GlobalConfig> GlobalConfig) {
  auto Opts = GlobalConfig->getCompletionOpts();
  CompletionInst->setOptions({
    Opts.MaxASTContextReuseCount,
    Opts.CheckDependencyInterval
  });
}

SwiftLangSupport::SwiftLangSupport(SourceKit::Context &SKCtx)
    : NotificationCtr(SKCtx.getNotificationCenter()),
      SwiftExecutablePath(SKCtx.getSwiftExecutablePath()),
      ReqTracker(SKCtx.getRequestTracker()), CCCache(new SwiftCompletionCache),
      CompileManager(RuntimeResourcePath, DiagnosticDocumentationPath) {
  llvm::SmallString<128> LibPath(SKCtx.getRuntimeLibPath());
  llvm::sys::path::append(LibPath, "swift");
  RuntimeResourcePath = std::string(LibPath.str());
  DiagnosticDocumentationPath = SKCtx.getDiagnosticDocumentationPath().str();

  Stats = std::make_shared<SwiftStatistics>();
  EditorDocuments = std::make_shared<SwiftEditorDocumentFileMap>();
  ASTMgr = std::make_shared<SwiftASTManager>(
      EditorDocuments, SKCtx.getGlobalConfiguration(), Stats, ReqTracker,
      SwiftExecutablePath, RuntimeResourcePath, DiagnosticDocumentationPath);

  CompletionInst = std::make_shared<CompletionInstance>();

  configureCompletionInstance(CompletionInst, SKCtx.getGlobalConfiguration());

  // By default, just use the in-memory cache.
  CCCache->inMemory = std::make_unique<ide::CodeCompletionCache>();

  // Provide a default file system provider.
  setFileSystemProvider("in-memory-vfs", std::make_unique<InMemoryFileSystemProvider>());
}

SwiftLangSupport::~SwiftLangSupport() {
}

void SwiftLangSupport::globalConfigurationUpdated(
    std::shared_ptr<GlobalConfig> Config) {
  configureCompletionInstance(CompletionInst, Config);
}

void SwiftLangSupport::dependencyUpdated() {
  CompletionInst->markCachedCompilerInstanceShouldBeInvalidated();
}

UIdent SwiftLangSupport::getUIDForDeclLanguage(const swift::Decl *D) {
  if (D->hasClangNode())
    return KindObjC;
  return KindSwift;
}

UIdent SwiftLangSupport::getUIDForDecl(const Decl *D, bool IsRef) {
  return UIdentVisitor(IsRef).visit(const_cast<Decl*>(D));
}

UIdent SwiftLangSupport::getUIDForExtensionOfDecl(const Decl *D) {
  switch (D->getKind()) {
    case swift::DeclKind::Struct:
      return KindDeclExtensionStruct;
    case swift::DeclKind::Enum:
      return KindDeclExtensionEnum;
    case swift::DeclKind::Class:
      return KindDeclExtensionClass;
    case swift::DeclKind::Protocol:
      return KindDeclExtensionProtocol;
    default:
      llvm_unreachable("cannot have extension.");
  }
}

UIdent SwiftLangSupport::getUIDForLocalVar(bool IsRef) {
  return IsRef ? KindRefVarLocal : KindDeclVarLocal;
}

UIdent SwiftLangSupport::getUIDForAccessor(const ValueDecl *D,
                                           AccessorKind AccKind,
                                           bool IsRef) {
  switch (AccKind) {
  case AccessorKind::Get:
    return IsRef ? KindRefAccessorGetter : KindDeclAccessorGetter;
  case AccessorKind::Set:
    return IsRef ? KindRefAccessorSetter : KindDeclAccessorSetter;
  case AccessorKind::WillSet:
    return IsRef ? KindRefAccessorWillSet : KindDeclAccessorWillSet;
  case AccessorKind::DidSet:
    return IsRef ? KindRefAccessorDidSet : KindDeclAccessorDidSet;
  case AccessorKind::Address:
    return IsRef ? KindRefAccessorAddress : KindDeclAccessorAddress;
  case AccessorKind::MutableAddress:
    return IsRef ? KindRefAccessorMutableAddress
                 : KindDeclAccessorMutableAddress;
  case AccessorKind::Read:
    return IsRef ? KindRefAccessorRead : KindDeclAccessorRead;
  case AccessorKind::Modify:
    return IsRef ? KindRefAccessorModify : KindDeclAccessorModify;
  }

  llvm_unreachable("Unhandled AccessorKind in switch.");
}

SourceKit::UIdent SwiftLangSupport::getUIDForModuleRef() {
  return KindRefModule;
}

SourceKit::UIdent SwiftLangSupport::getUIDForObjCAttr() {
  return Attr_Objc;
}

UIdent SwiftLangSupport::getUIDForRefactoringKind(ide::RefactoringKind Kind){
  switch(Kind) {
  case ide::RefactoringKind::None: llvm_unreachable("cannot end up here.");
#define REFACTORING(KIND, NAME, ID)                                            \
  case ide::RefactoringKind::KIND: return KindRefactoring##KIND;
#include "swift/IDE/RefactoringKinds.def"
  }
}

UIdent SwiftLangSupport::getUIDForCodeCompletionDeclKind(
    ide::CodeCompletionDeclKind Kind, bool IsRef) {
  if (IsRef) {
    // FIXME: The code-completion kind is also used for semantic annotations.
    // We should either create a new kind or rename the code-completion kind to
    // something more general.
    switch (Kind) {
    case CodeCompletionDeclKind::Module: return KindRefModule;
    case CodeCompletionDeclKind::Class: return KindRefClass;
    case CodeCompletionDeclKind::Actor: return KindRefActor;
    case CodeCompletionDeclKind::Struct: return KindRefStruct;
    case CodeCompletionDeclKind::Enum: return KindRefEnum;
    case CodeCompletionDeclKind::EnumElement: return KindRefEnumElement;
    case CodeCompletionDeclKind::Protocol: return KindRefProtocol;
    case CodeCompletionDeclKind::AssociatedType: return KindRefAssociatedType;
    case CodeCompletionDeclKind::TypeAlias: return KindRefTypeAlias;
    case CodeCompletionDeclKind::GenericTypeParam: return KindRefGenericTypeParam;
    case CodeCompletionDeclKind::Constructor: return KindRefConstructor;
    case CodeCompletionDeclKind::Destructor: return KindRefDestructor;
    case CodeCompletionDeclKind::Subscript: return KindRefSubscript;
    case CodeCompletionDeclKind::StaticMethod: return KindRefMethodClass;
    case CodeCompletionDeclKind::InstanceMethod: return KindRefMethodInstance;
    case CodeCompletionDeclKind::PrefixOperatorFunction: return KindRefFunctionPrefixOperator;
    case CodeCompletionDeclKind::PostfixOperatorFunction: return KindRefFunctionPostfixOperator;
    case CodeCompletionDeclKind::InfixOperatorFunction: return KindRefFunctionInfixOperator;
    case CodeCompletionDeclKind::PrecedenceGroup: return KindRefPrecedenceGroup;
    case CodeCompletionDeclKind::FreeFunction: return KindRefFunctionFree;
    case CodeCompletionDeclKind::StaticVar: return KindRefVarClass;
    case CodeCompletionDeclKind::InstanceVar: return KindRefVarInstance;
    case CodeCompletionDeclKind::LocalVar: return KindRefVarLocal;
    case CodeCompletionDeclKind::GlobalVar: return KindRefVarGlobal;
    }
  }

  switch (Kind) {
  case CodeCompletionDeclKind::Module: return KindDeclModule;
  case CodeCompletionDeclKind::Class: return KindDeclClass;
  case CodeCompletionDeclKind::Actor: return KindDeclActor;
  case CodeCompletionDeclKind::Struct: return KindDeclStruct;
  case CodeCompletionDeclKind::Enum: return KindDeclEnum;
  case CodeCompletionDeclKind::EnumElement: return KindDeclEnumElement;
  case CodeCompletionDeclKind::Protocol: return KindDeclProtocol;
  case CodeCompletionDeclKind::AssociatedType: return KindDeclAssociatedType;
  case CodeCompletionDeclKind::TypeAlias: return KindDeclTypeAlias;
  case CodeCompletionDeclKind::GenericTypeParam: return KindDeclGenericTypeParam;
  case CodeCompletionDeclKind::Constructor: return KindDeclConstructor;
  case CodeCompletionDeclKind::Destructor: return KindDeclDestructor;
  case CodeCompletionDeclKind::Subscript: return KindDeclSubscript;
  case CodeCompletionDeclKind::StaticMethod: return KindDeclMethodClass;
  case CodeCompletionDeclKind::InstanceMethod: return KindDeclMethodInstance;
  case CodeCompletionDeclKind::PrefixOperatorFunction: return KindDeclFunctionPrefixOperator;
  case CodeCompletionDeclKind::PostfixOperatorFunction: return KindDeclFunctionPostfixOperator;
  case CodeCompletionDeclKind::InfixOperatorFunction: return KindDeclFunctionInfixOperator;
  case CodeCompletionDeclKind::PrecedenceGroup: return KindDeclPrecedenceGroup;
  case CodeCompletionDeclKind::FreeFunction: return KindDeclFunctionFree;
  case CodeCompletionDeclKind::StaticVar: return KindDeclVarClass;
  case CodeCompletionDeclKind::InstanceVar: return KindDeclVarInstance;
  case CodeCompletionDeclKind::LocalVar: return KindDeclVarLocal;
  case CodeCompletionDeclKind::GlobalVar: return KindDeclVarGlobal;
  }

  llvm_unreachable("Unhandled CodeCompletionDeclKind in switch.");
}

UIdent SwiftLangSupport::getUIDForSyntaxNodeKind(SyntaxNodeKind SC) {
  switch (SC) {
  case SyntaxNodeKind::Keyword:
    return KindKeyword;
  case SyntaxNodeKind::Identifier:
  case SyntaxNodeKind::DollarIdent:
    return KindIdentifier;
  case SyntaxNodeKind::Operator:
    return KindOperator;
  case SyntaxNodeKind::Integer:
  case SyntaxNodeKind::Floating:
    return KindNumber;
  case SyntaxNodeKind::String:
    return KindString;
  case SyntaxNodeKind::StringInterpolationAnchor:
    return KindStringInterpolation;
  case SyntaxNodeKind::CommentLine:
  case SyntaxNodeKind::CommentBlock:
    return KindComment;
  case SyntaxNodeKind::CommentMarker:
    return KindCommentMarker;
  case SyntaxNodeKind::CommentURL:
    return KindCommentURL;
  case SyntaxNodeKind::DocCommentLine:
  case SyntaxNodeKind::DocCommentBlock:
    return KindDocComment;
  case SyntaxNodeKind::DocCommentField:
    return KindDocCommentField;
  case SyntaxNodeKind::TypeId:
    return KindTypeIdentifier;
  case SyntaxNodeKind::BuildConfigKeyword:
    return KindBuildConfigKeyword;
  case SyntaxNodeKind::BuildConfigId:
    return KindBuildConfigId;
  case SyntaxNodeKind::PoundDirectiveKeyword:
    return KindPoundDirectiveKeyword;
  case SyntaxNodeKind::AttributeId:
    return KindAttributeId;
  case SyntaxNodeKind::AttributeBuiltin:
    return KindAttributeBuiltin;
  case SyntaxNodeKind::EditorPlaceholder:
    return KindPlaceholder;
  case SyntaxNodeKind::ObjectLiteral:
    return KindObjectLiteral;
  }

  // Default to a known kind to prevent crashing in non-asserts builds
  assert(0 && "Unhandled SyntaxNodeKind in switch.");
  return KindIdentifier;
}

UIdent SwiftLangSupport::getUIDForSyntaxStructureKind(
    SyntaxStructureKind Kind) {
  switch (Kind) {
    case SyntaxStructureKind::Class:
      return KindDeclClass;
    case SyntaxStructureKind::Struct:
      return KindDeclStruct;
    case SyntaxStructureKind::Protocol:
      return KindDeclProtocol;
    case SyntaxStructureKind::Enum:
      return KindDeclEnum;
    case SyntaxStructureKind::Extension:
      return KindDeclExtension;
    case SyntaxStructureKind::FreeFunction:
      return KindDeclFunctionFree;
    case SyntaxStructureKind::InstanceFunction:
      return KindDeclMethodInstance;
    case SyntaxStructureKind::StaticFunction:
      return KindDeclMethodStatic;
    case SyntaxStructureKind::ClassFunction:
      return KindDeclMethodClass;
    case SyntaxStructureKind::GlobalVariable:
      return KindDeclVarGlobal;
    case SyntaxStructureKind::InstanceVariable:
      return KindDeclVarInstance;
    case SyntaxStructureKind::StaticVariable:
      return KindDeclVarStatic;
    case SyntaxStructureKind::ClassVariable:
      return KindDeclVarClass;
    case SyntaxStructureKind::LocalVariable:
      return KindDeclVarLocal;
    case SyntaxStructureKind::EnumCase:
      return KindDeclEnumCase;
    case SyntaxStructureKind::EnumElement:
      return KindDeclEnumElement;
    case SyntaxStructureKind::TypeAlias:
      return KindDeclTypeAlias;
    case SyntaxStructureKind::Subscript:
      return KindDeclSubscript;
    case SyntaxStructureKind::AssociatedType:
      return KindDeclAssociatedType;
    case SyntaxStructureKind::GenericTypeParam:
      return KindDeclGenericTypeParam;
    case SyntaxStructureKind::Parameter:
      return KindDeclVarParam;
    case SyntaxStructureKind::ForEachStatement:
      return KindStmtForEach;
    case SyntaxStructureKind::WhileStatement:
      return KindStmtWhile;
    case SyntaxStructureKind::RepeatWhileStatement:
      return KindStmtRepeatWhile;
    case SyntaxStructureKind::IfStatement:
      return KindStmtIf;
    case SyntaxStructureKind::GuardStatement:
      return KindStmtGuard;
    case SyntaxStructureKind::SwitchStatement:
      return KindStmtSwitch;
    case SyntaxStructureKind::CaseStatement:
      return KindStmtCase;
    case SyntaxStructureKind::BraceStatement:
      return KindStmtBrace;
    case SyntaxStructureKind::CallExpression:
      return KindExprCall;
    case SyntaxStructureKind::ArrayExpression:
      return KindExprArray;
    case SyntaxStructureKind::DictionaryExpression:
      return KindExprDictionary;
    case SyntaxStructureKind::ObjectLiteralExpression:
      return KindExprObjectLiteral;
    case SyntaxStructureKind::TupleExpression:
      return KindExprTuple;
    case SyntaxStructureKind::ClosureExpression:
      return KindExprClosure;
    case SyntaxStructureKind::Argument:
      return KindExprArg;
  }

  llvm_unreachable("Unhandled SyntaxStructureKind in switch.");
}

UIdent SwiftLangSupport::getUIDForSyntaxStructureElementKind(
    SyntaxStructureElementKind Kind) {
  switch (Kind) {
    case SyntaxStructureElementKind::Id: return KindStructureElemId;
    case SyntaxStructureElementKind::Expr: return KindStructureElemExpr;
    case SyntaxStructureElementKind::InitExpr: return KindStructureElemInitExpr;
    case SyntaxStructureElementKind::ConditionExpr: return KindStructureElemCondExpr;
    case SyntaxStructureElementKind::Pattern: return KindStructureElemPattern;
    case SyntaxStructureElementKind::TypeRef: return KindStructureElemTypeRef;
  }

  llvm_unreachable("Unhandled SyntaxStructureElementKind in switch.");
}

SourceKit::UIdent SwiftLangSupport::
getUIDForRangeKind(swift::ide::RangeKind Kind) {
  switch (Kind) {
    case swift::ide::RangeKind::SingleExpression: return KindRangeSingleExpression;
    case swift::ide::RangeKind::SingleStatement: return KindRangeSingleStatement;
    case swift::ide::RangeKind::SingleDecl: return KindRangeSingleDeclaration;
    case swift::ide::RangeKind::MultiStatement: return KindRangeMultiStatement;
    case swift::ide::RangeKind::MultiTypeMemberDecl:
      return KindRangeMultiTypeMemberDeclaration;
    case swift::ide::RangeKind::PartOfExpression: return KindRangeInvalid;
    case swift::ide::RangeKind::Invalid: return KindRangeInvalid;
  }

  llvm_unreachable("Unhandled RangeKind in switch.");
}

SourceKit::UIdent SwiftLangSupport::
getUIDForRegionType(swift::ide::RegionType Type) {
  switch (Type) {
    case swift::ide::RegionType::ActiveCode: return KindEditActive;
    case swift::ide::RegionType::InactiveCode: return KindEditInactive;
    case swift::ide::RegionType::Selector: return KindEditSelector;
    case swift::ide::RegionType::String: return KindEditString;
    case swift::ide::RegionType::Comment: return KindEditComment;
    case swift::ide::RegionType::Mismatch: return KindEditMismatch;
    case swift::ide::RegionType::Unmatched: return KindEditUnknown;
  }
}

SourceKit::UIdent SwiftLangSupport::
getUIDForRefactoringRangeKind(ide::RefactoringRangeKind Kind) {
  switch (Kind) {
  case ide::RefactoringRangeKind::BaseName:
    return KindRenameRangeBase;
  case ide::RefactoringRangeKind::KeywordBaseName:
    return KindRenameRangeKeywordBase;
  case ide::RefactoringRangeKind::ParameterName:
    return KindRenameRangeParam;
  case ide::RefactoringRangeKind::NoncollapsibleParameterName:
    return KindRenameRangeNoncollapsibleParam;
  case ide::RefactoringRangeKind::DeclArgumentLabel:
    return KindRenameRangeDeclArgLabel;
  case ide::RefactoringRangeKind::CallArgumentLabel:
    return KindRenameRangeCallArgLabel;
  case ide::RefactoringRangeKind::CallArgumentColon:
    return KindRenameRangeCallArgColon;
  case ide::RefactoringRangeKind::CallArgumentCombined:
    return KindRenameRangeCallArgCombined;
  case ide::RefactoringRangeKind::SelectorArgumentLabel:
    return KindRenameRangeSelectorArgLabel;
  }
}

UIdent SwiftLangSupport::getUIDForSymbol(SymbolInfo sym, bool isRef) {

#define UID_FOR(CLASS) isRef ? KindRef##CLASS : KindDecl##CLASS;

  switch (sym.SubKind) {
  default: break;
  case SymbolSubKind::AccessorGetter: return UID_FOR(AccessorGetter);
  case SymbolSubKind::AccessorSetter: return UID_FOR(AccessorSetter);
  case SymbolSubKind::SwiftAccessorWillSet: return UID_FOR(AccessorWillSet);
  case SymbolSubKind::SwiftAccessorDidSet: return UID_FOR(AccessorDidSet);
  case SymbolSubKind::SwiftAccessorAddressor: return UID_FOR(AccessorAddress);
  case SymbolSubKind::SwiftAccessorMutableAddressor: return UID_FOR(AccessorMutableAddress);
  }

#define SIMPLE_CASE(KIND) \
  case SymbolKind::KIND: \
    return UID_FOR(KIND);

  switch (sym.Kind) {
  SIMPLE_CASE(Enum)
  SIMPLE_CASE(Struct)
  SIMPLE_CASE(Class)
  SIMPLE_CASE(Protocol)
  SIMPLE_CASE(Constructor)
  SIMPLE_CASE(Destructor)

  case SymbolKind::EnumConstant:
    return UID_FOR(EnumElement);

  case SymbolKind::TypeAlias:
    if (sym.SubKind == SymbolSubKind::SwiftAssociatedType)
      return UID_FOR(AssociatedType);
    if (sym.SubKind == SymbolSubKind::SwiftGenericTypeParam)
      return UID_FOR(GenericTypeParam);
    return UID_FOR(TypeAlias);

  case SymbolKind::Function:
  case SymbolKind::StaticMethod:
    if (sym.SubKind == SymbolSubKind::SwiftPrefixOperator)
      return UID_FOR(FunctionPrefixOperator);
    if (sym.SubKind == SymbolSubKind::SwiftPostfixOperator)
      return UID_FOR(FunctionPostfixOperator);
    if (sym.SubKind == SymbolSubKind::SwiftInfixOperator)
      return UID_FOR(FunctionInfixOperator);
    if (sym.Kind == SymbolKind::StaticMethod) {
      return UID_FOR(MethodStatic);
    } else {
      return UID_FOR(FunctionFree);
    }
  case SymbolKind::Variable:
    return UID_FOR(VarGlobal);
  case SymbolKind::InstanceMethod:
    return UID_FOR(MethodInstance);
  case SymbolKind::ClassMethod:
    return UID_FOR(MethodClass);
  case SymbolKind::InstanceProperty:
    if (sym.SubKind == SymbolSubKind::SwiftSubscript)
      return UID_FOR(Subscript);
    return UID_FOR(VarInstance);
  case SymbolKind::ClassProperty:
    return UID_FOR(VarClass);
  case SymbolKind::StaticProperty:
    return UID_FOR(VarStatic);

  case SymbolKind::Extension:
    assert(!isRef && "reference to extension decl?");
    if (sym.SubKind == SymbolSubKind::SwiftExtensionOfStruct) {
      return KindDeclExtensionStruct;
    } else if (sym.SubKind == SymbolSubKind::SwiftExtensionOfClass) {
      return KindDeclExtensionClass;
    } else if (sym.SubKind == SymbolSubKind::SwiftExtensionOfEnum) {
      return KindDeclExtensionEnum;
    } else if (sym.SubKind == SymbolSubKind::SwiftExtensionOfProtocol) {
      return KindDeclExtensionProtocol;
    } else {
      llvm_unreachable("missing extension sub kind");
    }

  case SymbolKind::Module:
    return KindRefModule;

  case SymbolKind::CommentTag:
    return KindCommentTag;

  default:
    // TODO: reconsider whether having a default case is a good idea.
    llvm_unreachable("unhandled symbol kind Swift doesn't use");
  }

#undef SIMPLE_CASE
#undef UID_FOR
}

SourceKit::UIdent SwiftLangSupport::getUIDForNameKind(swift::ide::NameKind Kind) {
  switch(Kind) {
  case swift::ide::NameKind::ObjC: return KindNameObjc;
  case swift::ide::NameKind::Swift: return KindNameSwift;
  }

  llvm_unreachable("Unhandled NameKind in switch.");
}

swift::ide::NameKind SwiftLangSupport::getNameKindForUID(SourceKit::UIdent Id) {
  if (Id == KindNameObjc)
    return swift::ide::NameKind::ObjC;
  assert(Id == KindNameSwift);
  return swift::ide::NameKind::Swift;
}

Optional<UIdent> SwiftLangSupport::getUIDForDeclAttribute(const swift::DeclAttribute *Attr) {
  // Check special-case names first.
  switch (Attr->getKind()) {
    case DAK_IBAction: {
      return Attr_IBAction;
    }
    case DAK_IBSegueAction: {
      static UIdent Attr_IBSegueAction("source.decl.attribute.ibsegueaction");
      return Attr_IBSegueAction;
    }
    case DAK_IBOutlet: {
      return Attr_IBOutlet;
    }
    case DAK_IBDesignable: {
      return Attr_IBDesignable;
    }
    case DAK_IBInspectable: {
      return Attr_IBInspectable;
    }
    case DAK_GKInspectable: {
      return Attr_GKInspectable;
    }
    case DAK_ObjC: {
      if (cast<ObjCAttr>(Attr)->hasName()) {
        return Attr_ObjcNamed;
      } else {
        return Attr_Objc;
      }
    }
    case DAK_AccessControl: {
      switch (cast<AbstractAccessControlAttr>(Attr)->getAccess()) {
        case AccessLevel::Private:
          return Attr_Private;
        case AccessLevel::FilePrivate:
          return Attr_FilePrivate;
        case AccessLevel::Internal:
          return Attr_Internal;
        case AccessLevel::Public:
          return Attr_Public;
        case AccessLevel::Open:
          return Attr_Open;
      }
    }
    case DAK_SetterAccess: {
      switch (cast<AbstractAccessControlAttr>(Attr)->getAccess()) {
        case AccessLevel::Private:
          return Attr_Setter_Private;
        case AccessLevel::FilePrivate:
          return Attr_Setter_FilePrivate;
        case AccessLevel::Internal:
          return Attr_Setter_Internal;
        case AccessLevel::Public:
          return Attr_Setter_Public;
        case AccessLevel::Open:
          return Attr_Setter_Open;
      }
    }

    // Ignore these.
    case DAK_ShowInInterface:
    case DAK_RawDocComment:
    case DAK_HasInitialValue:
    case DAK_HasStorage:
      return None;
    default:
      break;
  }

  switch (Attr->getKind()) {
    case DAK_Count:
      break;
#define DECL_ATTR(X, CLASS, ...)\
    case DAK_##CLASS: {\
      static UIdent Attr_##X("source.decl.attribute."#X); \
      return Attr_##X; \
    }
#include "swift/AST/Attr.def"
  }

  return None;
}

UIdent SwiftLangSupport::getUIDForFormalAccessScope(const swift::AccessScope Scope) {
  if (Scope.isPublic()) {
    return EffectiveAccess_Public;
  } else if (Scope.isInternal()) {
    return EffectiveAccess_Internal;
  } else if (Scope.isFileScope()) {
    return EffectiveAccess_FilePrivate;
  } else if (Scope.isPrivate()) {
    return EffectiveAccess_LessThanFilePrivate;
  } else {
    llvm_unreachable("Unsupported access scope");
  }
}

std::vector<UIdent> SwiftLangSupport::UIDsFromDeclAttributes(const DeclAttributes &Attrs) {
  std::vector<UIdent> AttrUIDs;

  for (auto Attr : Attrs) {
    if (auto AttrUID = getUIDForDeclAttribute(Attr)) {
      AttrUIDs.push_back(AttrUID.getValue());
    }
  }

  return AttrUIDs;
}

bool SwiftLangSupport::printDisplayName(const swift::ValueDecl *D,
                                        llvm::raw_ostream &OS) {
  if (!D->hasName())
    return true;

  OS << D->getName();
  return false;
}

bool SwiftLangSupport::printUSR(const ValueDecl *D, llvm::raw_ostream &OS) {
  return ide::printValueDeclUSR(D, OS);
}

bool SwiftLangSupport::printDeclTypeUSR(const ValueDecl *D, llvm::raw_ostream &OS) {
  return ide::printDeclTypeUSR(D, OS);
}

bool SwiftLangSupport::printTypeUSR(Type Ty, llvm::raw_ostream &OS) {
  return ide::printTypeUSR(Ty, OS);
}

bool SwiftLangSupport::printAccessorUSR(const AbstractStorageDecl *D,
                                        AccessorKind AccKind,
                                        llvm::raw_ostream &OS) {
  return ide::printAccessorUSR(D, AccKind, OS);
}

void SwiftLangSupport::printMemberDeclDescription(const swift::ValueDecl *VD,
                                                  swift::Type baseTy,
                                                  bool usePlaceholder,
                                                  llvm::raw_ostream &OS) {
  // Base name.
  OS << VD->getBaseName().userFacingName();

  // Parameters.
  auto *M = VD->getModuleContext();
  auto substMap = baseTy->getMemberSubstitutionMap(M, VD);
  auto printSingleParam = [&](ParamDecl *param) {
    auto paramTy = param->getInterfaceType();

    // Label.
    if (!param->getArgumentName().empty())
      OS << param->getArgumentName() << ": ";

    // InOut.
    if (param->isInOut()) {
      OS << "&";
      paramTy = paramTy->getInOutObjectType();
    }

    // Type.
    if (usePlaceholder)
      OS << "<#T##";

    paramTy = paramTy.subst(substMap);
    if (paramTy->hasError() && param->getTypeRepr()) {
      // Fallback to 'TypeRepr' printing.
      param->getTypeRepr()->print(OS);
    } else {
      paramTy.print(OS);
    }

    if (usePlaceholder)
      OS << "#>";
  };
  auto printParams = [&](const ParameterList *params) {
    OS << '(';
    bool isFirst = true;
    for (auto param : params->getArray()) {
      if (isFirst)
        isFirst = false;
      else
        OS << ", ";
      printSingleParam(param);
    }
    OS << ')';
  };
  if (isa<EnumElementDecl>(VD) || isa<FuncDecl>(VD)) {
    if (const auto ParamList = getParameterList(const_cast<ValueDecl *>(VD))) {
      printParams(ParamList);
    }
  } else if (isa<VarDecl>(VD)) {
    // Var decl doesn't have parameters.
  } else {
    llvm_unreachable("Unsupported Decl kind for printMemberDeclDescription()");
  }
}

std::string SwiftLangSupport::resolvePathSymlinks(StringRef FilePath) {
  std::string InputPath = FilePath.str();
  llvm::SmallString<256> output;
  if (llvm::sys::fs::real_path(InputPath, output))
    return InputPath;
  return std::string(output.str());
}

void SwiftLangSupport::getStatistics(StatisticsReceiver receiver) {
  std::vector<Statistic *> stats = {
#define SWIFT_STATISTIC(VAR, UID, DESC) &Stats->VAR,
#include "SwiftStatistics.def"
  };
  receiver(stats);
}

FileSystemProvider *SwiftLangSupport::getFileSystemProvider(StringRef Name) {
  auto It = FileSystemProviders.find(Name);
  if (It == FileSystemProviders.end())
    return nullptr;
  return It->second.get();
}

void SwiftLangSupport::setFileSystemProvider(
     StringRef Name, std::unique_ptr<FileSystemProvider> FileSystemProvider) {
  assert(FileSystemProvider);
  auto Result = FileSystemProviders.try_emplace(Name, std::move(FileSystemProvider));
  assert(Result.second && "tried to set existing FileSystemProvider");
}

llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem>
SwiftLangSupport::getFileSystem(const Optional<VFSOptions> &vfsOptions,
                                Optional<StringRef> primaryFile,
                                std::string &error) {
  // First, try the specified vfsOptions.
  if (vfsOptions) {
    auto provider = getFileSystemProvider(vfsOptions->name);
    if (!provider) {
      error = "unknown virtual filesystem '" + vfsOptions->name + "'";
      return nullptr;
    }

    return provider->getFileSystem(*vfsOptions->options, error);
  }

  // Otherwise, try to find an open document with a filesystem.
  if (primaryFile) {
    if (auto doc = EditorDocuments->getByUnresolvedName(*primaryFile)) {
      return doc->getFileSystem();
    }
  }

  // Fallback to the real filesystem.
  return llvm::vfs::getRealFileSystem();
}

void SwiftLangSupport::performWithParamsToCompletionLikeOperation(
    llvm::MemoryBuffer *UnresolvedInputFile, unsigned Offset,
    ArrayRef<const char *> Args,
    llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> FileSystem,
    SourceKitCancellationToken CancellationToken,
    llvm::function_ref<void(CancellableResult<CompletionLikeOperationParams>)>
        PerformOperation) {
  assert(FileSystem);

  // Resolve symlinks for the input file; we resolve them for the input files
  // in the arguments as well.
  // FIXME: We need the Swift equivalent of Clang's FileEntry.
  llvm::SmallString<128> bufferIdentifier;
  if (auto err = FileSystem->getRealPath(
          UnresolvedInputFile->getBufferIdentifier(), bufferIdentifier))
    bufferIdentifier = UnresolvedInputFile->getBufferIdentifier();

  // Create a buffer for code completion. This contains '\0' at 'Offset'
  // position of 'UnresolvedInputFile' buffer.
  auto origOffset = Offset;
  auto newBuffer = ide::makeCodeCompletionMemoryBuffer(
      UnresolvedInputFile, Offset, bufferIdentifier);

  SourceManager SM;
  DiagnosticEngine Diags(SM);
  PrintingDiagnosticConsumer PrintDiags;
  EditorDiagConsumer TraceDiags;
  trace::TracedOperation TracedOp{trace::OperationKind::CodeCompletion};

  Diags.addConsumer(PrintDiags);
  if (TracedOp.enabled()) {
    Diags.addConsumer(TraceDiags);
    trace::SwiftInvocation SwiftArgs;
    trace::initTraceInfo(SwiftArgs, bufferIdentifier, Args);
    TracedOp.setDiagnosticProvider(
        [&](SmallVectorImpl<DiagnosticEntryInfo> &diags) {
          TraceDiags.getAllDiagnostics(diags);
        });
    TracedOp.start(
        SwiftArgs,
        {std::make_pair("OriginalOffset", std::to_string(origOffset)),
         std::make_pair("Offset", std::to_string(Offset))});
  }
  ForwardingDiagnosticConsumer CIDiags(Diags);

  CompilerInvocation Invocation;
  std::string CompilerInvocationError;
  bool CreatingInvocationFailed = getASTManager()->initCompilerInvocation(
      Invocation, Args, FrontendOptions::ActionType::Typecheck, Diags,
      newBuffer->getBufferIdentifier(), FileSystem, CompilerInvocationError);
  if (CreatingInvocationFailed) {
    PerformOperation(CancellableResult<CompletionLikeOperationParams>::failure(
        CompilerInvocationError));
    return;
  }
  if (!Invocation.getFrontendOptions().InputsAndOutputs.hasInputs()) {
    PerformOperation(CancellableResult<CompletionLikeOperationParams>::failure(
        "no input filenames specified"));
    return;
  }

  // Pin completion instance.
  auto CompletionInst = getCompletionInstance();

  auto CancellationFlag = std::make_shared<std::atomic<bool>>(false);
  ReqTracker->setCancellationHandler(CancellationToken, [CancellationFlag] {
    CancellationFlag->store(true, std::memory_order_relaxed);
  });

  CompletionLikeOperationParams Params = {Invocation, newBuffer.get(), &CIDiags,
                                          CancellationFlag};
  PerformOperation(
      CancellableResult<CompletionLikeOperationParams>::success(Params));
}

CloseClangModuleFiles::~CloseClangModuleFiles() {
  clang::Preprocessor &PP = loader.getClangPreprocessor();
  clang::ModuleMap &ModMap = PP.getHeaderSearchInfo().getModuleMap();
  for (auto I = ModMap.module_begin(), E = ModMap.module_end(); I != E; ++I) {
    clang::Module *M = I->second;
    if (!M->isSubModule() && M->getASTFile())
      M->getASTFile()->closeFile();
  }
}

void SourceKit::disableExpensiveSILOptions(SILOptions &Opts) {
  // Disable the sanitizers.
  Opts.Sanitizers = {};

  // Disable PGO and code coverage.
  Opts.GenerateProfile = false;
  Opts.EmitProfileCoverageMapping = false;
  Opts.UseProfile = "";
}


text:
//
//  UIActionSheet+TFKit.m
//  TFEasyCoderDemo
//
//  Created by ztf on 16/12/9.
//  Copyright © 2016年 ztf. All rights reserved.
//

#import "UIActionSheet+TFKit.h"
#import "NSObject+TFExecute.h"

@implementation UIActionSheet (TFKit)
@dynamic backBlock;

+(UIActionSheet *_Nullable)TF_CODE_PRE(showWithTitle):(NSString *_Nullable)title
                                               inView:(UIView   *_Nullable)inView
                                    cancelButtonTitle:(NSString *_Nullable)cancle
                               destructiveButtonTitle:(NSString *_Nullable)des
                                    otherButtonTitles:(NSArray  *_Nullable)othter
                                                block:(_Nullable TFUIActionSheetBackBlock)block{

    int btCount = 0;
    UIActionSheet *sheet = [[UIActionSheet alloc]init];
    sheet.delegate = (id)self;
    sheet.title = title;

    if (cancle) {
        sheet.cancelButtonIndex = btCount;
        [sheet addButtonWithTitle:cancle];
        btCount += 1;
    }
    if (des) {
        sheet.destructiveButtonIndex = btCount;
        [sheet addButtonWithTitle:des];
        btCount += 1;
    }
    for (int i = 0; i < othter.count; i++) {
        [sheet addButtonWithTitle:othter[i]];
    }
    [sheet TF_CODE_PRE(showInView):inView?inView:[UIApplication sharedApplication].keyWindow block:block];
    return sheet;
}

/**
 *  block 回调点击的方法
 *
 *  @param block
 */
-(void)TF_CODE_PRE(showInView):(UIView *_Nullable)view block:(_Nullable TFUIActionSheetBackBlock)block{
    if (!view || !block)return;
    [self tf_synthesizeAllCategoryPropertyForSelf];
    self.backBlock = block;
    self.delegate = self;
    [self showInView:view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (self.backBlock) {
        NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
        self.backBlock(actionSheet,buttonIndex,buttonTitle);
    }

}

@end

redpajama_set_name: RedPajamaGithub


text:
Write it here.

### Environment

<!--
	Write answers right after the questions
-->

1. What `go` version are you using?
2. Are you using the latest `go-shodan` version?
3. What OS are you using?

### Minimal reproducible demo

<!--
	Make sure you've removed all sensitive data like login, password or token!
-->

```go
// you code here
```


text:
namespace imp_wrapper {

  Global_Bundle::Global_Bundle() :
//    underworld_root("", nullptr),
    overworld_profession_library() {
    initialize_standard_library();
  }

  Global_Bundle::~Global_Bundle() = default;

  void Global_Bundle::initialize_standard_library() {
    standard_library = new cpp_stl::Standard_Library();
    standard_library->initialize_overworld(overworld_profession_library);
    standard_library->initialize_underworld(zookeeper);
    imp_mirror::Temporary_Interface_Manager temporary_interface_manager;
    imp_mirror::Mirror mirror(overworld_profession_library, element_map, nullptr, temporary_interface_manager,
                              header_files);
    imp_mirror::Scope scope(standard_library->get_overworld_dungeon().get_scope());
    mirror.reflect_root(standard_library->get_underworld_dungeon(), scope);
  }

  void Global_Bundle::load_file(const std::string &path, underworld::Dungeon &underworld_root) {
    zookeeper.load_file(path, underworld_root);
  }

  void Global_Bundle::mirror(imp_mirror::Temporary_Interface_Manager &temporary_interface_manager,
                             Project_Bundle &project_bundle) {
    imp_mirror::Mirror mirror(overworld_profession_library, element_map, &project_bundle.get_graph(),
                              temporary_interface_manager,
                              header_files);
    mirror.reflect_root(project_bundle.get_underworld_root(), project_bundle.get_mirror_scope());
  }

  void Global_Bundle::solve(Project_Bundle &project_bundle) {
    auto &graph = project_bundle.get_graph();
    auto &overworld_root = project_bundle.get_overworld_root();

    solving::Profession_Solver solver(graph, overworld_profession_library);
    solver.scan_fresh();

#if DEBUG_SOLVER > 2
    solving::log_nodes(graph);
#endif

    auto solved = solver.solve();

#if DEBUG_SOLVER > 1
    solving::log_nodes(graph);
#endif

//    auto node = solving::find_node(graph, 10, 9);
//    auto &profession = node->get_profession();
//    auto dungeon = dynamic_cast<overworld::Dungeon *>(&profession);
//    auto l = profession.get_debug_name();
//    auto temp = node->get_debug_string();
//    node->get_debug_string();
    if (!solved) {
      auto &unknowns = solver.get_unsolved_nodes();
      if (unknowns.size() > 0) {
        auto &unknown = *unknowns[0];
        auto &element = unknown.get_element();
        unknown._get_status();
        throw std::runtime_error("Could not determine type of \"" + element.get_name() +
                                 "\" at " + element.get_source_point().get_start().to_string() + ".");
      }

      auto &conflicts = solver.get_conflicts();
      if (conflicts.size() > 0) {
        auto &conflict = conflicts.front();
        throw std::runtime_error(
          solving::get_node_debug_string(conflict.get_connection().get_first()) + " is not compatible with "
          + solving::get_node_debug_string(conflict.get_connection().get_second()));
      }
    }

//    lifetime::Ownership_Mirror ownership_mirror(ownership_graph);
//    ownership_mirror.reflect(overworld_root);

    lifetime::Ownership_Solver ownership_solver(graph);
    std::cout << std::endl << "Logging initial ownership:" << std::endl;
    solving::log_node_trees(graph);
    ownership_solver.solve();
    std::cout << std::endl << "Logging final ownership:" << std::endl;
    solving::log_node_trees(graph);
#if DEBUG_SOLVER > 0
    solving::log_nodes(graph);
#endif
  }

  void Global_Bundle::render(const std::string &output_path, overworld::Dungeon &overworld_root) {
    imp_taskmaster::Taskmaster taskmaster(overworld_root, output_path, *standard_library);
    taskmaster.render();
  }

  overworld::Dungeon &Global_Bundle::create_realm(const std::string &name) {
    auto realm = new overworld::Dungeon(name);
    realms[name] = overworld::Dungeon_Owner(realm);
    return *realm;
  }

  std::unique_ptr<Project_Bundle> Global_Bundle::create_project_bundle(const std::string &name) {
    auto &realm = create_realm(name);
    auto bundle = std::unique_ptr<Project_Bundle>(new Project_Bundle(realm));
    auto &scope = bundle->get_mirror_scope();
    scope.add_dungeon(standard_library->get_overworld_dungeon());
    return bundle;
  }

  overworld::Dungeon *Global_Bundle::get_realm(const std::string &name) {
    if (realms.count(name) == 0)
      return nullptr;

    return realms[name].get();
  }
}

// TODO iterators
// TODO while loops
// TODO ranges
// TODO numeric and string indexes
// TODO enums
// TODO casting
// TODO instantatiation field initialization
// TODO #import
// TODO aliases
// TODO implicit return


text:
	Effective Dates:12/21/2015 - Present

Identification Number:
SI 01130 TN 72

Intended Audience:See Transmittal Sheet

Originating Office:ORDP OISP

Title:Resources Exclusions

Type:POMS Transmittals

Program:Title XVI (SSI); Disability

Link To Reference:

PROGRAM OPERATIONS MANUAL SYSTEM
Part 05 - Supplemental Security Income
Chapter 011  Resources
Subchapter 30 - Resources Exclusions
Transmittal No. 72,  12/2015

Audience

FO/TSC:  CR, CR TXVI, DRT, FR, OA, OS, RR, SR, TA, TE, TSC-SR

Originating Component
OISP

Effective Date
Upon Receipt

Background

The Stephen Beck, Jr., Achieving a Better Life Experience (ABLE) Act, enacted December 19, 2014, provides a resource exclusion for up to and including $100,000 in a qualifying ABLE account and an exclusion for distributions from the account that are used to pay for most types of qualified disability expenses.

Summary of Changes

SI 01130.740 Achieving a Better Life Experience (ABLE) Accounts

This new section explains ABLE accounts and provides instructions for developing and documenting account balances and distributions.

SI 01130.740 Achieving a Better Life Experience (ABLE) Accounts

CITATIONS:
Public
Law 113295 The Stephen Beck, Jr., Achieving a Better Life
Experience Act (ABLE Act)  Enacted December 19, 2014
A. What is an ABLE Account?

An Achieving a Better Life Experience (ABLE) account is a type of
tax-advantaged account that can be used to save funds for the
disability-related expenses of the accounts designated beneficiary,
who must be blind or disabled by a condition that began prior to the
individuals 26th birthday.

An ABLE program can be established and maintained by a State or a State
agency directly or by contracting with a private company (an
instrumentality of the State). An eligible individual can open an ABLE
account through the ABLE program of the individuals State of
residence. If an eligible individuals State of residence does not
have an ABLE program but has contracted with another State, the eligible
individual can open an ABLE account through that other States ABLE
program.

An eligible individual can be the designated beneficiary of only one ABLE
account, which must be administered by the ABLE program of the State in
which he or she lives or, if the designated beneficiary lives in a
contracting State, by the ABLE program of the State with which the State
of the individuals residence has contracted. If the designated
beneficiary of an ABLE account moves to another State, then the individual
must transfer his or her ABLE account to the new State of residence or, if
the new State of residence is a contracting State, to the ABLE program of
the State with which the new State of residence has contracted.

Upon the death of the designated beneficiary, funds remaining in the ABLE
account, after payment of any outstanding qualified disability expenses,
are used to reimburse the State(s) for certain Medical Assistance
(Medicaid) benefits the designated beneficiary received.
B. Definition of terms
1. Designated beneficiary

The designated beneficiary is the eligible individual who established and
is the owner of the ABLE account. To be an eligible individual, he or she
must be:

eligible for Supplemental Security Income (SSI) based on disability or
blindness that began before age 26;

entitled to Disability Insurance Benefits (DIB), Childhood Disability
Benefits (CDB), or Disabled Widows or Widowers Benefits
(DWB) based on disability or blindness that began before age 26; or

someone who has certified, or whose parent or guardian has certified, that
he or she:

has a medically determinable impairment meeting certain statutorily
specified criteria; or,

is blind; and,

the disability or blindness occurred before age 26.

NOTE: No inference regarding disability under the Social Security
Act may be drawn from a disability certification.
2. Contributions

A contribution is the deposit of funds into an ABLE account. Any person
can contribute to an ABLE account. (Note that person, as
defined by the Internal Revenue Code, includes an individual, trust,
estate, partnership, association, company, or corporation.) However, the
Internal Revenue Service (IRS) limits the total annual contributions any
ABLE account can receive from all sources to the amount of the per-donee
gift-tax exclusion in effect for a given calendar year. For 2016, that
limit is $14,000.
3. Distributions

A distribution is the withdrawal or issuance of funds from an ABLE
account. The designated beneficiary or the person with signature authority
determines when distributions are made. Distributions may be made only to
or for the benefit of the designated beneficiary.
4. Person with signature authority

A person with signature authority can establish and control an ABLE
account for a designated beneficiary who is a minor child or is otherwise
incapable of managing the account. The person with signature authority
must be the designated beneficiary's parent, legal guardian, or agent
acting under power of attorney. For SSI purposes, we always consider the
designated beneficiary to be the owner of an ABLE account, regardless of
whether someone else has signature authority over it.
5. Qualified disability expenses

Qualified disability expenses (QDEs) are expenses related to the blindness
or disability of the designated beneficiary and that are for the benefit
of the designated beneficiary. In general, a QDE includes, but is not
limited to, the following types of expenses:

Education;

Housing;

Transportation;

 Employment training and support;

 Assistive technology and related services;

Health;

Prevention and wellness;

Financial management and administrative services;

Legal fees;

Expenses for ABLE account oversight and monitoring;

Funeral and burial; and,

Basic living expenses
6. Rollover

A rollover is the distribution of all or some of the funds from one ABLE
account to the ABLE account of a member of the original, designated
beneficiary's family. For the purposes of a rollover, a member of the
designated beneficiary's family means a sibling, which includes
step-siblings and half-siblings, whether by blood or by adoption.
7. ABLE Program

An ABLE program is the program established and maintained by a State (or
agency or instrumentality thereof) through which the residents of that
State, or the residents of a contracting State, can open ABLE accounts.
8. Qualified disability expense (QDE) for housing

Housing expenses for purposes of an ABLE account are the same as they are
for in-kind support and maintenance purposes, except that they do not
include food. QDEs for housing are payments for:

Mortgage (including property insurance required by the mortgage holder);

Real property taxes;

Rent;

Heating fuel;

Gas;

Electricity;

Water;

Sewer; or

Garbage removal.
C. When to exclude ABLE account contributions, balances, earnings, and distributions
1. Exclude contributions

Exclude contributions to an ABLE account from the income of the designated
beneficiary. This includes rollovers from a family member's ABLE account
to an SSI recipient's ABLE account.

NOTE: Do not deduct contributions from the countable income of the
person who makes the contribution. The fact that a person uses his or her
income to contribute to an ABLE account does not mean that income is not
countable for SSI purposes. For example, a recipient or deemor can have
contributions automatically deducted from his or her paycheck and
deposited into an ABLE account. In this case, include the income used to
make the ABLE-account contribution in the recipient or deemor's gross
wages.
2. Exclude ABLE account earnings

The funds in an ABLE account are invested and can accrue interest, earn
dividends, and otherwise appreciate in value. Such earnings increase the
account's balance. Exclude any earnings an ABLE account receives from the
income of the designated beneficiary.
3. Exclude up to and including $100,000 of balance

Exclude up to and including $100,000 of the balance of funds in an ABLE
account from the resources of the designated beneficiary.
4. Do not count ABLE account distributions as income

A distribution from an ABLE account is not income but is a conversion of a
resource from one form to another. See SI 01110.600B.4. Do not count
distributions from an ABLE account as income of the designated
beneficiary, regardless of whether the distributions are for non-housing
QDEs, housing QDEs, or non-qualified expenses.
5. Exclude retained distributions for non-housing related qualified disability expenses (QDE)

Exclude from the designated beneficiarys countable resources a
distribution for a QDE other than housing if it is retained beyond the
month received.

This exclusion applies for as long as:

the designated beneficiary maintains, makes contributions to, or receives
distributions from the ABLE account;

the distribution is unspent; and

the distribution is identifiable. (NOTE: Excludable funds
commingled with non-excludable funds must be identifiable to be excluded.
See SI 01130.700A.)

NOTE : Apply normal SSI resource counting rules and exclusions to
assets or other items purchased with funds from an ABLE account.

a. Example of an excluded distribution

Eric takes a distribution of $500 from his ABLE account in June 2016 to
pay for a health-related QDE. His health-related expense is not due until
September, so Eric deposits the distribution into his checking account in
June. The distribution is not income in June. Eric maintains his ABLE
account at all relevant times, and the distribution is both unspent and
identifiable until Eric pays his health-related expense in September. We
therefore exclude the $500 from Eric's countable resources in July,
August, and September. See SI 01130.700 for instructions on identifying
when excluded funds have been commingled with non-excluded funds.

b. Example of an excluded QDE purchase

Fred takes a distribution of $1,500 from his ABLE account in September
2016 to buy a QDE - a wheelchair. The wheelchair is an excluded resource
in October and continuing, because it is an individuals personal
property required for a medical condition. See SI 01130.430 for
instructions on household goods, personal effects, and other personal
property.
D. When to count ABLE account balances and distributions
1. Count ABLE account balance amounts over $100,000

Count the amount by which an ABLE account balance exceeds $100,000 as a
countable resource of the designated beneficiary.
a. Rule for indefinite benefit suspension and continuing eligibility for Medicaid during periods of excess resources attributable to an ABLE account

A special rule applies when the balance of an SSI recipient's ABLE account
exceeds $100,000 by an amount that causes the recipient to exceed the SSI
resource limit--whether alone or in combination with other resources. When
this happens, the recipient is put into a special SSI suspension period
where:

we suspend the recipient's SSI benefits without time limit (as long as he
or she remains otherwise eligible);

the recipient retains continued eligibility for Medical Assistance
(Medicaid); and

the individuals eligibility does not terminate after 12 continuous
months of suspension.

We will reinstate the recipient's regular SSI eligibility for any month in
which the individuals ABLE account balance no longer causes the
recipient to exceed the resource limit and he or she is otherwise
eligible.

NOTE: Updated instructions will be issued when additional
procedures related to this special suspension status are complete. Due to
the limitation on contributions described in this section at
SI 01130.740B.2, there will be no SSI recipients in this suspension status
for several years (until individuals have been able to contribute more
than $100,000 to an ABLE account).

Example  excess resources  recipient is suspended but
retains eligibility for Medicaid

Paul is the designated beneficiary of an ABLE account with a balance as of
the first of the month of $101,000. Paul's only other countable resource
is a checking account with a balance of $1,500. Pauls countable
resources are $2,500 and therefore exceed the SSI resource limit. However,
since Paul's ABLE account balance is causing him to exceed the resource
limit (i.e., his countable resources other than the ABLE account are less
than $2,000), Pauls SSI eligibility is suspended and his cash
benefits stop, but he retains eligibility for Medicaid.
b. Ineligibility due to excess resources other than an ABLE account

The special suspension rule does not apply when:

the balance of an SSI recipient's ABLE account exceeds $100,000 by an
amount that causes the recipient to exceed the SSI resource limit;

but the resources other than the ABLE account alone would make the
individual ineligible for SSI, due to excess resources

When this happens, suspend the recipient's SSI benefits using the payment
status code N04. While in N04, the recipient loses eligibility for Medical
Assistance (Medicaid) and the individuals SSI eligibility will
terminate 12 months later if the suspension continues during this period.
Reinstate the recipient's regular SSI eligibility and Medicaid benefits
for any month in which the individuals ABLE account balance and
other resources no longer cause the recipient to exceed the resource
limit.

Example  combination of resources  recipient loses SSI
eligibility

Christine is the designated beneficiary of an ABLE account with a balance
as of the first of the month of $101,000. Christine's only other countable
resource is a checking account with a balance of $3,000. Christine's
countable resources are $4,000 and therefore exceed the SSI resource
limit.

However, because her ABLE account balance is not the cause (i.e., her
countable resources other than the ABLE account are more than $2,000), the
special rule does not apply, and Christine is not eligible for SSI because
of excess resources. Christines SSI benefits are suspended using
payment status N04, and her Medicaid benefits will stop.
c. Ineligibility for other reasons

If an individual is ineligible for any reason other than excess resources
in an ABLE account, the special suspension status does not apply. Suspend
the individuals SSI eligibility using normal procedures.

Example  ineligibility for a reason other than excess resources
in an ABLE account

In April, Sam has a first of the month resource balance in his ABLE
account of $102,500. However, Sam also has excess deemed income in April
and will be N01 despite the excess funds in his ABLE account. Before the
end of April, Sam leaves the U.S. and does not return until July 1. Sam
will be N03 for May, June and July. If Sam still has excess resources in
his ABLE account effective August 1 and is otherwise SSI eligible, he will
go into the special ABLE resource suspension status and be eligible for
Medicaid.
2. Count as a resource retained distributions for housing-related QDEs or expenses that are not QDEs

A distribution from an ABLE account is not income, but is a conversion of
a resource from one form to another. See SI 01110.600B.4.

Count as a resource a distribution for a housing-related QDE or for an
expense that is not a QDE if the distribution is retained into the month
following the month of receipt. If the distribution is spent within the
month of receipt it has no effect on eligibility. However, apply normal
SSI resource counting rules and exclusions to assets or other items
purchased with funds from an ABLE account

Example  retained housing QDE is a resource

Amy takes a distribution of $500 from her ABLE account in May to pay her
rent for June. She deposits the $500 into her checking account in May, and
withdraws $500 in cash on June 3rd and pays her landlord. This
distribution is a housing-related QDE and part of her checking account
balance as of the first of June, which makes it a countable resource for
the month of June.
E. How to verify, document, and record ABLE account balances
1. Obtain evidence of the ABLE account

Whenever a recipient or deemor alleges being the designated beneficiary of
an ABLE account, obtain evidence that provides the following information:

the name of the designated beneficiary;

the State ABLE program that is administering the account;

the name of the person who has signature authority (if different from the
designated beneficiary);

the unique account number assigned by the State to the ABLE account;

the account opened date;

the first-of-the-month account balance or information sufficient to derive
a first-of-the-month balance.

If the available evidence doesn't provide this information, contact the
appropriate ABLE program to obtain it.
2. Document the evidence

Fax the evidence into the electronic folder (EF) or Non-disability
Repository for Evidentiary Documents (NDReD). If you contact the ABLE
program directly, document the information you received on a Report of
Contact (DROC) in MSSICS or on a Report of Contact (SSA-5002) in
non-MSSICS claims.
3. Record the account on a MSSICS Other Resource page

Record the account information and balance on a MSSICS Other Resource
(ROTH) page. There is an ABLE account drop down under Type.
See MS INTRANETSSI 013.032 for instructions on completing this screen.

NOTE:  The designated beneficiary of an ABLE account is always the
owner of the account for SSI purposes.
F. How to verify, document, and record ABLE account distributions
1. When to develop

Only verify a distribution when a recipient or deemor alleges retaining,
or other evidence indicates he or she retained, all or part of a
distribution into months following the month of receipt. Since
distributions do not count as income, the distribution is only material in
determining whether the recipient's countable resources exceed the limit.
2. Verify the distribution

Obtain evidence showing the amount of any distributions, the dates taken,
and who received them (for example, whether it was paid directly to a
vendor). Obtain and accept the recipient or deemor's allegation as to
whether a distribution was or will be used for:

a QDE other than housing;

a housing QDE; or

an expense that is not a QDE.
3. Exclude retained distributions for QDEs other than housing

Exclude from the designated beneficiarys countable resources any
retained distribution or part of a distribution for a QDE other than
housing per SI 01130.740C.5 in this section.

Example of a retained QDE other than housing

Elizabeth takes a distribution of $500 from her ABLE account in May to pay
for a health-related QDE she expects to pay in September. She deposits the
distribution into her checking account in May and withdraws it in
September to pay the health-related QDE. We would exclude the $500 from
Elizabeth's countable resources from June through September. Starting in
June, the technician documents the deposit on the RFIA page inputting $500
as the excluded amount. She selects Other as
the exclusion reason and inputs ABLE QDE distribution as the
other reason.
4. Count retained distributions for housing QDEs and expenses that are not QDEs

Count as a resource any distribution or part of a distribution for a
housing QDE or an expense that is not a QDE if it is retained into the
month following the month of receipt.

Example of a retained QDE for housing

Amy takes a distribution of $500 from her ABLE account in May to pay her
rent for June. She deposits the $500 into her checking account in May, and
withdraws $500 in cash on June 3rd and pays her landlord. This
distribution, which is a housing-related QDE, is part of her checking
account balance as of the first of the month in June, which makes it a
countable resource for the month of June.
5. Record the amount excluded on the appropriate resource page

ABLE account distributions are the conversion of a resource from one form
to another. Accordingly, they continue to be a resource if retained into
the month following the month of receipt. A retained QDE distribution is
excluded from resources per SI 01130.740F.3 in this section.

Depending on how and where they are retained, record the amount in the
"amount excluded" field of the appropriate resource page in MSSICS with a
reason of "ABLE QDE distribution."

SI 01130 TN 72 - Resources Exclusions - 12/21/2015


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

	<include layout="@layout/horizontal_divider_line_blue"/>

    <TextView
        android:id="@+id/temperatureDescripterTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="8dp"
        android:text="@string/temperature" />

    <SeekBar
        android:id="@+id/temperatureBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="4500"
        android:paddingBottom="8dp" />

    <EditText
        android:id="@+id/temperatureText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number" >
    </EditText>

</LinearLayout>


text:
#ifndef SkPixelRef_DEFINED
#define SkPixelRef_DEFINED

#include "SkBitmap.h"
#include "SkRefCnt.h"
#include "SkString.h"
#include "SkFlattenable.h"
#include "SkTDArray.h"

//#define SK_SUPPORT_LEGACY_PIXELREF_CONSTRUCTOR

#ifdef SK_DEBUG
    /**
     *  Defining SK_IGNORE_PIXELREF_SETPRELOCKED will force all pixelref
     *  subclasses to correctly handle lock/unlock pixels. For performance
     *  reasons, simple malloc-based subclasses call setPreLocked() to skip
     *  the overhead of implementing these calls.
     *
     *  This build-flag disables that optimization, to add in debugging our
     *  call-sites, to ensure that they correctly balance their calls of
     *  lock and unlock.
     */
//    #define SK_IGNORE_PIXELREF_SETPRELOCKED
#endif

class SkColorTable;
class SkData;
struct SkIRect;
class SkMutex;

class GrTexture;

/** \class SkPixelRef

    This class is the smart container for pixel memory, and is used with
    SkBitmap. A pixelref is installed into a bitmap, and then the bitmap can
    access the actual pixel memory by calling lockPixels/unlockPixels.

    This class can be shared/accessed between multiple threads.
*/
class SK_API SkPixelRef : public SkFlattenable {
public:
    SK_DECLARE_INST_COUNT(SkPixelRef)

#ifdef SK_SUPPORT_LEGACY_PIXELREF_CONSTRUCTOR
    // DEPRECATED -- use a constructor that takes SkImageInfo
    explicit SkPixelRef(SkBaseMutex* mutex = NULL);
#endif

    explicit SkPixelRef(const SkImageInfo&);
    SkPixelRef(const SkImageInfo&, SkBaseMutex* mutex);
    virtual ~SkPixelRef();

    const SkImageInfo& info() const {
        return fInfo;
    }

    /** Return the pixel memory returned from lockPixels, or null if the
        lockCount is 0.
    */
    void* pixels() const { return fPixels; }

    /** Return the current colorTable (if any) if pixels are locked, or null.
    */
    SkColorTable* colorTable() const { return fColorTable; }

    /**
     *  Returns true if the lockcount > 0
     */
    bool isLocked() const { return fLockCount > 0; }

    SkDEBUGCODE(int getLockCount() const { return fLockCount; })

    /** Call to access the pixel memory, which is returned. Balance with a call
        to unlockPixels().
    */
    void lockPixels();
    /** Call to balanace a previous call to lockPixels(). Returns the pixels
        (or null) after the unlock. NOTE: lock calls can be nested, but the
        matching number of unlock calls must be made in order to free the
        memory (if the subclass implements caching/deferred-decoding.)
    */
    void unlockPixels();

    /**
     *  Some bitmaps can return a copy of their pixels for lockPixels(), but
     *  that copy, if modified, will not be pushed back. These bitmaps should
     *  not be used as targets for a raster device/canvas (since all pixels
     *  modifications will be lost when unlockPixels() is called.)
     */
    bool lockPixelsAreWritable() const;

    /** Returns a non-zero, unique value corresponding to the pixels in this
        pixelref. Each time the pixels are changed (and notifyPixelsChanged is
        called), a different generation ID will be returned.
    */
    uint32_t getGenerationID() const;

    /** Call this if you have changed the contents of the pixels. This will in-
        turn cause a different generation ID value to be returned from
        getGenerationID().
    */
    void notifyPixelsChanged();

    /** Returns true if this pixelref is marked as immutable, meaning that the
        contents of its pixels will not change for the lifetime of the pixelref.
    */
    bool isImmutable() const { return fIsImmutable; }

    /** Marks this pixelref is immutable, meaning that the contents of its
        pixels will not change for the lifetime of the pixelref. This state can
        be set on a pixelref, but it cannot be cleared once it is set.
    */
    void setImmutable();

    /** Return the optional URI string associated with this pixelref. May be
        null.
    */
    const char* getURI() const { return fURI.size() ? fURI.c_str() : NULL; }

    /** Copy a URI string to this pixelref, or clear the URI if the uri is null
     */
    void setURI(const char uri[]) {
        fURI.set(uri);
    }

    /** Copy a URI string to this pixelref
     */
    void setURI(const char uri[], size_t len) {
        fURI.set(uri, len);
    }

    /** Assign a URI string to this pixelref.
    */
    void setURI(const SkString& uri) { fURI = uri; }

    /**
     *  If the pixelRef has an encoded (i.e. compressed) representation,
     *  return a ref to its data. If the pixelRef
     *  is uncompressed or otherwise does not have this form, return NULL.
     *
     *  If non-null is returned, the caller is responsible for calling unref()
     *  on the data when it is finished.
     */
    SkData* refEncodedData() {
        return this->onRefEncodedData();
    }

    /**
     *  Experimental -- tells the caller if it is worth it to call decodeInto().
     *  Just an optimization at this point, to avoid checking the cache first.
     *  We may remove/change this call in the future.
     */
    bool implementsDecodeInto() {
        return this->onImplementsDecodeInto();
    }

    /**
     *  Return a decoded instance of this pixelRef in bitmap. If this cannot be
     *  done, return false and the bitmap parameter is ignored/unchanged.
     *
     *  pow2 is the requeste power-of-two downscale that the caller needs. This
     *  can be ignored, and the "original" size can be returned, but if the
     *  underlying codec can efficiently return a smaller size, that should be
     *  done. Some examples:
     *
     *  To request the "base" version (original scale), pass 0 for pow2
     *  To request 1/2 scale version (1/2 width, 1/2 height), pass 1 for pow2
     *  To request 1/4 scale version (1/4 width, 1/4 height), pass 2 for pow2
     *  ...
     *
     *  If this returns true, then bitmap must be "locked" such that
     *  bitmap->getPixels() will return the correct address.
     */
    bool decodeInto(int pow2, SkBitmap* bitmap) {
        SkASSERT(pow2 >= 0);
        return this->onDecodeInto(pow2, bitmap);
    }

    /** Are we really wrapping a texture instead of a bitmap?
     */
    virtual GrTexture* getTexture() { return NULL; }

    bool readPixels(SkBitmap* dst, const SkIRect* subset = NULL);

    /**
     *  Makes a deep copy of this PixelRef, respecting the requested config.
     *  @param config Desired config.
     *  @param subset Subset of this PixelRef to copy. Must be fully contained within the bounds of
     *         of this PixelRef.
     *  @return A new SkPixelRef, or NULL if either there is an error (e.g. the destination could
     *          not be created with the given config), or this PixelRef does not support deep
     *          copies.
     */
    virtual SkPixelRef* deepCopy(SkBitmap::Config config, const SkIRect* subset = NULL) {
        return NULL;
    }

#ifdef SK_BUILD_FOR_ANDROID
    /**
     *  Acquire a "global" ref on this object.
     *  The default implementation just calls ref(), but subclasses can override
     *  this method to implement additional behavior.
     */
    virtual void globalRef(void* data=NULL);

    /**
     *  Release a "global" ref on this object.
     *  The default implementation just calls unref(), but subclasses can override
     *  this method to implement additional behavior.
     */
    virtual void globalUnref();
#endif

    SK_DEFINE_FLATTENABLE_TYPE(SkPixelRef)

    // Register a listener that may be called the next time our generation ID changes.
    //
    // We'll only call the listener if we're confident that we are the only SkPixelRef with this
    // generation ID.  If our generation ID changes and we decide not to call the listener, we'll
    // never call it: you must add a new listener for each generation ID change.  We also won't call
    // the listener when we're certain no one knows what our generation ID is.
    //
    // This can be used to invalidate caches keyed by SkPixelRef generation ID.
    struct GenIDChangeListener {
        virtual ~GenIDChangeListener() {}
        virtual void onChange() = 0;
    };

    // Takes ownership of listener.
    void addGenIDChangeListener(GenIDChangeListener* listener);

protected:
    /** Called when the lockCount goes from 0 to 1. The caller will have already
        acquire a mutex for thread safety, so this method need not do that.
    */
    virtual void* onLockPixels(SkColorTable**) = 0;

    /**
     *  Called when the lock count goes from 1 to 0. The caller will have
     *  already acquire a mutex for thread safety, so this method need not do
     *  that.
     *
     *  If the previous call to onLockPixels failed (i.e. returned NULL), then
     *  the onUnlockPixels will NOT be called.
     */
    virtual void onUnlockPixels() = 0;

    /** Default impl returns true */
    virtual bool onLockPixelsAreWritable() const;

    // returns false;
    virtual bool onImplementsDecodeInto();
    // returns false;
    virtual bool onDecodeInto(int pow2, SkBitmap* bitmap);

    /**
     *  For pixelrefs that don't have access to their raw pixels, they may be
     *  able to make a copy of them (e.g. if the pixels are on the GPU).
     *
     *  The base class implementation returns false;
     */
    virtual bool onReadPixels(SkBitmap* dst, const SkIRect* subsetOrNull);

    // default impl returns NULL.
    virtual SkData* onRefEncodedData();

    /**
     *  Returns the size (in bytes) of the internally allocated memory.
     *  This should be implemented in all serializable SkPixelRef derived classes.
     *  SkBitmap::fPixelRefOffset + SkBitmap::getSafeSize() should never overflow this value,
     *  otherwise the rendering code may attempt to read memory out of bounds.
     *
     *  @return default impl returns 0.
     */
    virtual size_t getAllocatedSizeInBytes() const;

    /** Return the mutex associated with this pixelref. This value is assigned
        in the constructor, and cannot change during the lifetime of the object.
    */
    SkBaseMutex* mutex() const { return fMutex; }

    // serialization
    SkPixelRef(SkFlattenableReadBuffer&, SkBaseMutex*);
    virtual void flatten(SkFlattenableWriteBuffer&) const SK_OVERRIDE;

    // only call from constructor. Flags this to always be locked, removing
    // the need to grab the mutex and call onLockPixels/onUnlockPixels.
    // Performance tweak to avoid those calls (esp. in multi-thread use case).
    void setPreLocked(void* pixels, SkColorTable* ctable);

private:
    SkBaseMutex*    fMutex; // must remain in scope for the life of this object
    // FIXME: fInfo should be const once we remove old constructor that does
    // not set it.
    SkImageInfo     fInfo;

    void*           fPixels;
    SkColorTable*   fColorTable;    // we do not track ownership, subclass does
    int             fLockCount;

    mutable uint32_t fGenerationID;
    mutable bool     fUniqueGenerationID;

    SkTDArray<GenIDChangeListener*> fGenIDChangeListeners;  // pointers are owned

    SkString    fURI;

    // can go from false to true, but never from true to false
    bool    fIsImmutable;
    // only ever set in constructor, const after that
    bool    fPreLocked;

    void needsNewGenID();
    void callGenIDChangeListeners();

    void setMutex(SkBaseMutex* mutex);

    // When copying a bitmap to another with the same shape and config, we can safely
    // clone the pixelref generation ID too, which makes them equivalent under caching.
    friend class SkBitmap;  // only for cloneGenID
    void cloneGenID(const SkPixelRef&);

    typedef SkFlattenable INHERITED;
};

#endif


text:
package org.apache.hadoop.fs.shell;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.zip.GZIPInputStream;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileChecksum;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.shell.PathExceptions.PathIsDirectoryException;
import org.apache.hadoop.io.DataInputBuffer;
import org.apache.hadoop.io.DataOutputBuffer;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.SequenceFile;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.CompressionCodecFactory;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.util.StringUtils;

/**
 * Display contents or checksums of files
 */
@InterfaceAudience.Private
@InterfaceStability.Evolving

class Display extends FsCommand {
  public static void registerCommands(CommandFactory factory) {
    factory.addClass(Cat.class, "-cat");
    factory.addClass(Text.class, "-text");
    factory.addClass(Checksum.class, "-checksum");
  }

  /**
   * Displays file content to stdout
   */
  public static class Cat extends Display {
    public static final String NAME = "cat";
    public static final String USAGE = "[-ignoreCrc] <src> ...";
    public static final String DESCRIPTION =
      "Fetch all files that match the file pattern <src> \n" +
      "and display their content on stdout.\n";

    private boolean verifyChecksum = true;

    @Override
    protected void processOptions(LinkedList<String> args)
    throws IOException {
      CommandFormat cf = new CommandFormat(1, Integer.MAX_VALUE, "ignoreCrc");
      cf.parse(args);
      verifyChecksum = !cf.getOpt("ignoreCrc");
    }

    @Override
    protected void processPath(PathData item) throws IOException {
      if (item.stat.isDirectory()) {
        throw new PathIsDirectoryException(item.toString());
      }

      item.fs.setVerifyChecksum(verifyChecksum);
      printToStdout(getInputStream(item));
    }

    private void printToStdout(InputStream in) throws IOException {
      try {
        IOUtils.copyBytes(in, out, getConf(), false);
      } finally {
        in.close();
      }
    }

    protected InputStream getInputStream(PathData item) throws IOException {
      return item.fs.open(item.path);
    }
  }

  /**
   * Same behavior as "-cat", but handles zip and TextRecordInputStream
   * encodings.
   */
  public static class Text extends Cat {
    public static final String NAME = "text";
    public static final String USAGE = Cat.USAGE;
    public static final String DESCRIPTION =
      "Takes a source file and outputs the file in text format.\n" +
      "The allowed formats are zip and TextRecordInputStream.";

    @Override
    protected InputStream getInputStream(PathData item) throws IOException {
      FSDataInputStream i = (FSDataInputStream)super.getInputStream(item);

      // check codecs
      CompressionCodecFactory cf = new CompressionCodecFactory(getConf());
      CompressionCodec codec = cf.getCodec(item.path);
      if (codec != null) {
        return codec.createInputStream(i);
      }

      switch(i.readShort()) {
        case 0x1f8b: { // RFC 1952
          i.seek(0);
          return new GZIPInputStream(i);
        }
        case 0x5345: { // 'S' 'E'
          if (i.readByte() == 'Q') {
            i.close();
            return new TextRecordInputStream(item.stat);
          }
          break;
        }
      }
      i.seek(0);
      return i;
    }
  }

  public static class Checksum extends Display {
    public static final String NAME = "checksum";
    public static final String USAGE = "<src> ...";
    public static final String DESCRIPTION =
      "Dump checksum information for files that match the file\n" +
      "pattern <src> to stdout. Note that this requires a round-trip\n" +
      "to a datanode storing each block of the file, and thus is not\n" +
      "efficient to run on a large number of files. The checksum of a\n" +
      "file depends on its content, block size and the checksum\n" +
      "algorithm and parameters used for creating the file.";

    @Override
    protected void processPath(PathData item) throws IOException {
      if (item.stat.isDirectory()) {
        throw new PathIsDirectoryException(item.toString());
      }

      FileChecksum checksum = item.fs.getFileChecksum(item.path);
      if (checksum == null) {
        out.printf("%s\tNONE\t\n", item.toString());
      } else {
        String checksumString = StringUtils.byteToHexString(
            checksum.getBytes(), 0, checksum.getLength());
        out.printf("%s\t%s\t%s\n",
            item.toString(), checksum.getAlgorithmName(),
            checksumString);
      }
    }
  }

  protected class TextRecordInputStream extends InputStream {
    SequenceFile.Reader r;
    WritableComparable<?> key;
    Writable val;

    DataInputBuffer inbuf;
    DataOutputBuffer outbuf;

    public TextRecordInputStream(FileStatus f) throws IOException {
      final Path fpath = f.getPath();
      final Configuration lconf = getConf();
      r = new SequenceFile.Reader(lconf,
          SequenceFile.Reader.file(fpath));
      key = ReflectionUtils.newInstance(
          r.getKeyClass().asSubclass(WritableComparable.class), lconf);
      val = ReflectionUtils.newInstance(
          r.getValueClass().asSubclass(Writable.class), lconf);
      inbuf = new DataInputBuffer();
      outbuf = new DataOutputBuffer();
    }

    public int read() throws IOException {
      int ret;
      if (null == inbuf || -1 == (ret = inbuf.read())) {
        if (!r.next(key, val)) {
          return -1;
        }
        byte[] tmp = key.toString().getBytes();
        outbuf.write(tmp, 0, tmp.length);
        outbuf.write('\t');
        tmp = val.toString().getBytes();
        outbuf.write(tmp, 0, tmp.length);
        outbuf.write('\n');
        inbuf.reset(outbuf.getData(), outbuf.getLength());
        outbuf.reset();
        ret = inbuf.read();
      }
      return ret;
    }

    public void close() throws IOException {
      r.close();
      super.close();
    }
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.appservice.models;

import com.azure.core.annotation.Fluent;
import com.azure.resourcemanager.appservice.fluent.models.AppServiceCertificateInner;
import com.azure.resourcemanager.appservice.fluent.models.AppServiceCertificateOrderPatchResourceProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;

/** ARM resource for a certificate order that is purchased through Azure. */
@Fluent
public final class AppServiceCertificateOrderPatchResource extends ProxyOnlyResource {
    /*
     * AppServiceCertificateOrderPatchResource resource specific properties
     */
    @JsonProperty(value = "properties")
    private AppServiceCertificateOrderPatchResourceProperties innerProperties;

    /**
     * Get the innerProperties property: AppServiceCertificateOrderPatchResource resource specific properties.
     *
     * @return the innerProperties value.
     */
    private AppServiceCertificateOrderPatchResourceProperties innerProperties() {
        return this.innerProperties;
    }

    /** {@inheritDoc} */
    @Override
    public AppServiceCertificateOrderPatchResource withKind(String kind) {
        super.withKind(kind);
        return this;
    }

    /**
     * Get the certificates property: State of the Key Vault secret.
     *
     * @return the certificates value.
     */
    public Map<String, AppServiceCertificateInner> certificates() {
        return this.innerProperties() == null ? null : this.innerProperties().certificates();
    }

    /**
     * Set the certificates property: State of the Key Vault secret.
     *
     * @param certificates the certificates value to set.
     * @return the AppServiceCertificateOrderPatchResource object itself.
     */
    public AppServiceCertificateOrderPatchResource withCertificates(
        Map<String, AppServiceCertificateInner> certificates) {
        if (this.innerProperties() == null) {
            this.innerProperties = new AppServiceCertificateOrderPatchResourceProperties();
        }
        this.innerProperties().withCertificates(certificates);
        return this;
    }

    /**
     * Get the distinguishedName property: Certificate distinguished name.
     *
     * @return the distinguishedName value.
     */
    public String distinguishedName() {
        return this.innerProperties() == null ? null : this.innerProperties().distinguishedName();
    }

    /**
     * Set the distinguishedName property: Certificate distinguished name.
     *
     * @param distinguishedName the distinguishedName value to set.
     * @return the AppServiceCertificateOrderPatchResource object itself.
     */
    public AppServiceCertificateOrderPatchResource withDistinguishedName(String distinguishedName) {
        if (this.innerProperties() == null) {
            this.innerProperties = new AppServiceCertificateOrderPatchResourceProperties();
        }
        this.innerProperties().withDistinguishedName(distinguishedName);
        return this;
    }

    /**
     * Get the domainVerificationToken property: Domain verification token.
     *
     * @return the domainVerificationToken value.
     */
    public String domainVerificationToken() {
        return this.innerProperties() == null ? null : this.innerProperties().domainVerificationToken();
    }

    /**
     * Get the validityInYears property: Duration in years (must be 1).
     *
     * @return the validityInYears value.
     */
    public Integer validityInYears() {
        return this.innerProperties() == null ? null : this.innerProperties().validityInYears();
    }

    /**
     * Set the validityInYears property: Duration in years (must be 1).
     *
     * @param validityInYears the validityInYears value to set.
     * @return the AppServiceCertificateOrderPatchResource object itself.
     */
    public AppServiceCertificateOrderPatchResource withValidityInYears(Integer validityInYears) {
        if (this.innerProperties() == null) {
            this.innerProperties = new AppServiceCertificateOrderPatchResourceProperties();
        }
        this.innerProperties().withValidityInYears(validityInYears);
        return this;
    }

    /**
     * Get the keySize property: Certificate key size.
     *
     * @return the keySize value.
     */
    public Integer keySize() {
        return this.innerProperties() == null ? null : this.innerProperties().keySize();
    }

    /**
     * Set the keySize property: Certificate key size.
     *
     * @param keySize the keySize value to set.
     * @return the AppServiceCertificateOrderPatchResource object itself.
     */
    public AppServiceCertificateOrderPatchResource withKeySize(Integer keySize) {
        if (this.innerProperties() == null) {
            this.innerProperties = new AppServiceCertificateOrderPatchResourceProperties();
        }
        this.innerProperties().withKeySize(keySize);
        return this;
    }

    /**
     * Get the productType property: Certificate product type.
     *
     * @return the productType value.
     */
    public CertificateProductType productType() {
        return this.innerProperties() == null ? null : this.innerProperties().productType();
    }

    /**
     * Set the productType property: Certificate product type.
     *
     * @param productType the productType value to set.
     * @return the AppServiceCertificateOrderPatchResource object itself.
     */
    public AppServiceCertificateOrderPatchResource withProductType(CertificateProductType productType) {
        if (this.innerProperties() == null) {
            this.innerProperties = new AppServiceCertificateOrderPatchResourceProperties();
        }
        this.innerProperties().withProductType(productType);
        return this;
    }

    /**
     * Get the autoRenew property: true if the certificate should be automatically renewed when
     * it expires; otherwise, false.
     *
     * @return the autoRenew value.
     */
    public Boolean autoRenew() {
        return this.innerProperties() == null ? null : this.innerProperties().autoRenew();
    }

    /**
     * Set the autoRenew property: true if the certificate should be automatically renewed when
     * it expires; otherwise, false.
     *
     * @param autoRenew the autoRenew value to set.
     * @return the AppServiceCertificateOrderPatchResource object itself.
     */
    public AppServiceCertificateOrderPatchResource withAutoRenew(Boolean autoRenew) {
        if (this.innerProperties() == null) {
            this.innerProperties = new AppServiceCertificateOrderPatchResourceProperties();
        }
        this.innerProperties().withAutoRenew(autoRenew);
        return this;
    }

    /**
     * Get the provisioningState property: Status of certificate order.
     *
     * @return the provisioningState value.
     */
    public ProvisioningState provisioningState() {
        return this.innerProperties() == null ? null : this.innerProperties().provisioningState();
    }

    /**
     * Get the status property: Current order status.
     *
     * @return the status value.
     */
    public CertificateOrderStatus status() {
        return this.innerProperties() == null ? null : this.innerProperties().status();
    }

    /**
     * Get the signedCertificate property: Signed certificate.
     *
     * @return the signedCertificate value.
     */
    public CertificateDetails signedCertificate() {
        return this.innerProperties() == null ? null : this.innerProperties().signedCertificate();
    }

    /**
     * Get the csr property: Last CSR that was created for this order.
     *
     * @return the csr value.
     */
    public String csr() {
        return this.innerProperties() == null ? null : this.innerProperties().csr();
    }

    /**
     * Set the csr property: Last CSR that was created for this order.
     *
     * @param csr the csr value to set.
     * @return the AppServiceCertificateOrderPatchResource object itself.
     */
    public AppServiceCertificateOrderPatchResource withCsr(String csr) {
        if (this.innerProperties() == null) {
            this.innerProperties = new AppServiceCertificateOrderPatchResourceProperties();
        }
        this.innerProperties().withCsr(csr);
        return this;
    }

    /**
     * Get the intermediate property: Intermediate certificate.
     *
     * @return the intermediate value.
     */
    public CertificateDetails intermediate() {
        return this.innerProperties() == null ? null : this.innerProperties().intermediate();
    }

    /**
     * Get the root property: Root certificate.
     *
     * @return the root value.
     */
    public CertificateDetails root() {
        return this.innerProperties() == null ? null : this.innerProperties().root();
    }

    /**
     * Get the serialNumber property: Current serial number of the certificate.
     *
     * @return the serialNumber value.
     */
    public String serialNumber() {
        return this.innerProperties() == null ? null : this.innerProperties().serialNumber();
    }

    /**
     * Get the lastCertificateIssuanceTime property: Certificate last issuance time.
     *
     * @return the lastCertificateIssuanceTime value.
     */
    public OffsetDateTime lastCertificateIssuanceTime() {
        return this.innerProperties() == null ? null : this.innerProperties().lastCertificateIssuanceTime();
    }

    /**
     * Get the expirationTime property: Certificate expiration time.
     *
     * @return the expirationTime value.
     */
    public OffsetDateTime expirationTime() {
        return this.innerProperties() == null ? null : this.innerProperties().expirationTime();
    }

    /**
     * Get the isPrivateKeyExternal property: true if private key is external; otherwise,
     * false.
     *
     * @return the isPrivateKeyExternal value.
     */
    public Boolean isPrivateKeyExternal() {
        return this.innerProperties() == null ? null : this.innerProperties().isPrivateKeyExternal();
    }

    /**
     * Get the appServiceCertificateNotRenewableReasons property: Reasons why App Service Certificate is not renewable
     * at the current moment.
     *
     * @return the appServiceCertificateNotRenewableReasons value.
     */
    public List<ResourceNotRenewableReason> appServiceCertificateNotRenewableReasons() {
        return this.innerProperties() == null
            ? null
            : this.innerProperties().appServiceCertificateNotRenewableReasons();
    }

    /**
     * Get the nextAutoRenewalTimestamp property: Time stamp when the certificate would be auto renewed next.
     *
     * @return the nextAutoRenewalTimestamp value.
     */
    public OffsetDateTime nextAutoRenewalTimestamp() {
        return this.innerProperties() == null ? null : this.innerProperties().nextAutoRenewalTimestamp();
    }

    /**
     * Get the contact property: Contact info.
     *
     * @return the contact value.
     */
    public CertificateOrderContact contact() {
        return this.innerProperties() == null ? null : this.innerProperties().contact();
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    @Override
    public void validate() {
        super.validate();
        if (innerProperties() != null) {
            innerProperties().validate();
        }
    }
}


text:
package org.springframework.osgi.test.internal.util.jar.storage;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;

/**
 * Memory based storage. This class writes the information to a byte array.
 *
 * @author Costin Leau
 *
 */
public class MemoryStorage implements Storage {

	private ByteArrayOutputStream buffer = new ByteArrayOutputStream();

	public void dispose() {
		buffer = new ByteArrayOutputStream(0);
	}

	public InputStream getInputStream() {
		return new ByteArrayInputStream(buffer.toByteArray());
	}

	public OutputStream getOutputStream() {
		return buffer;
	}

	public Resource getResource() {
		return new ByteArrayResource(buffer.toByteArray());
	}
}