<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "IncrementalParser.h"
#include "ASTDumper.h"
#include "ASTNodeEraser.h"
#include "DeclCollector.h"
#include "DeclExtractor.h"
#include "DynamicLookup.h"
#include "ReturnSynthesizer.h"
#include "ValuePrinterSynthesizer.h"
#include "cling/Interpreter/CIFactory.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Transaction.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/FileManager.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Parse/Parser.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ASTWriter.h"

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_os_ostream.h"

#include <ctime>
#include <iostream>
#include <stdio.h>
#include <sstream>

using namespace clang;

namespace cling {
  IncrementalParser::IncrementalParser(Interpreter* interp,
                                       int argc, const char* const *argv,
                                       const char* llvmdir):
    m_Interpreter(interp), m_Consumer(0), m_FirstTransaction(0),
    m_LastTransaction(0) {

    CompilerInstance* CI
      = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer("", "CLING"),
                            argc, argv, llvmdir);
    assert(CI && "CompilerInstance is (null)!");

    m_Consumer = dyn_cast<DeclCollector>(&CI->getASTConsumer());
    assert(m_Consumer && "Expected ChainedConsumer!");

    m_CI.reset(CI);

    if (CI->getFrontendOpts().ProgramAction != clang::frontend::ParseSyntaxOnly){
      m_CodeGen.reset(CreateLLVMCodeGen(CI->getDiagnostics(), "cling input",
                                        CI->getCodeGenOpts(),
                                        *m_Interpreter->getLLVMContext()
                                        ));
    }

    CreateSLocOffsetGenerator();

    // Add transformers to the IncrementalParser, which owns them
    m_TTransformers.push_back(new EvaluateTSynthesizer(&CI->getSema()));

    m_TTransformers.push_back(new ValuePrinterSynthesizer(&CI->getSema(), 0));
    m_TTransformers.push_back(new ReturnSynthesizer(&CI->getSema()));
    m_TTransformers.push_back(new ASTDumper());
    m_TTransformers.push_back(new DeclExtractor(&getCI()->getSema()));

    m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema(),
                              false /*skipFuncBodies*/));
    CI->getPreprocessor().EnterMainSourceFile();
    // Initialize the parser after we have entered the main source file.
    m_Parser->Initialize();
    // Perform initialization that occurs after the parser has been initialized
    // but before it parses anything. Initializes the consumers too.
    CI->getSema().Initialize();
  }

  IncrementalParser::~IncrementalParser() {
    if (hasCodeGenerator()) {
      getCodeGenerator()->ReleaseModule();
    }
    const Transaction* T = getFirstTransaction();
    const Transaction* nextT = 0;
    while (T) {
      nextT = T->getNext();
      delete T;
      T = nextT;
    }

    for (size_t i = 0; i < m_TTransformers.size(); ++i)
      delete m_TTransformers[i];
  }

  Transaction* IncrementalParser::beginTransaction(const CompilationOptions&
                                                   Opts) {
    llvm::Module* M = 0;
    if (hasCodeGenerator())
      M = getCodeGenerator()->GetModule();

    Transaction* NewCurT = new Transaction(Opts, M);
    Transaction* OldCurT = m_Consumer->getTransaction();
    m_Consumer->setTransaction(NewCurT);
    // If we are in the middle of transaction and we see another begin
    // transaction - it must be nested transaction.
    if (OldCurT && !OldCurT->isCompleted()) {
      OldCurT->addNestedTransaction(NewCurT); // takes the ownership
      return NewCurT;
    }

    if (!m_FirstTransaction) {
      m_FirstTransaction = NewCurT;
      m_LastTransaction = NewCurT;
    }
    else {
      m_LastTransaction->setNext(NewCurT);
      m_LastTransaction = NewCurT;
    }

    return NewCurT;
  }

  Transaction* IncrementalParser::endTransaction() const {
    Transaction* CurT = m_Consumer->getTransaction();
    CurT->setCompleted();
    const DiagnosticsEngine& Diags = getCI()->getSema().getDiagnostics();

    //TODO: Make the enum orable.
    if (Diags.getNumWarnings() > 0)
      CurT->setIssuedDiags(Transaction::kWarnings);

    if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
      CurT->setIssuedDiags(Transaction::kErrors);

    if (CurT->hasNestedTransactions()) {
      for(Transaction::const_nested_iterator I = CurT->nested_decls_begin(),
            E = CurT->nested_decls_end(); I != E; ++I)
        assert((*I)->isCompleted() && "Nested transaction not completed!?");
    }

    if (CurT->isNestedTransaction()) {
      // TODO: Add proper logic in the case where there are multiple nested
      // transaction. This now won't handle the case where there are more than
      // one level 1 nested transactions.
      m_Consumer->setTransaction(CurT->getParent());
    }

    return CurT;
  }

  void IncrementalParser::commitTransaction(Transaction* T) {
    //Transaction* CurT = m_Consumer->getTransaction();
    assert(T->isCompleted() && "Transaction not ended!?");

    // Check for errors...
    if (T->getIssuedDiags() == Transaction::kErrors) {
      rollbackTransaction(T);
      return;
    }

    if (T->hasNestedTransactions()) {
      for(Transaction::const_nested_iterator I = T->nested_decls_begin(),
            E = T->nested_decls_end(); I != E; ++I)
        commitTransaction(*I);
    }

    // We are sure it's safe to pipe it through the transformers
    bool success = true;
    for (size_t i = 0; i < m_TTransformers.size(); ++i) {
      success = m_TTransformers[i]->TransformTransaction(*T);
      if (!success) {
        break;
      }
    }

    m_CI->getDiagnostics().Reset(); // FIXME: Should be in rollback transaction.

    if (!success) {
      // Roll back on error in a transformer
      rollbackTransaction(T);
      return;
    }

    // Pull all template instantiations in that came from the consumers.
    getCI()->getSema().PerformPendingInstantiations();

    m_Consumer->HandleTranslationUnit(getCI()->getASTContext());

    if (T->getCompilationOpts().CodeGeneration && hasCodeGenerator()) {
      // Reset the module builder to clean up global initializers, c'tors, d'tors
      getCodeGenerator()->Initialize(getCI()->getASTContext());

      // codegen the transaction
      // We assume that there is no ordering of the calls to HandleXYZ, because
      // in clang they can happen in different order too, eg. coming from
      // template instatiator and so on.
      for (Transaction::iterator I = T->decls_begin(), E = T->decls_end();
           I != E; ++I) {
        switch (I->m_Call) {
        case Transaction::kCCIHandleTopLevelDecl :
          getCodeGenerator()->HandleTopLevelDecl(I->m_DGR);
          break;
        case Transaction::kCCIHandleInterestingDecl :
          getCodeGenerator()->HandleInterestingDecl(I->m_DGR);
          break;
        case Transaction::kCCIHandleTagDeclDefinition : {
          TagDecl* TD = cast<TagDecl>(I->m_DGR.getSingleDecl());
          getCodeGenerator()->HandleTagDeclDefinition(TD);
          break;
        }
        case Transaction::kCCIHandleVTable : {
          CXXRecordDecl* CXXRD = cast<CXXRecordDecl>(I->m_DGR.getSingleDecl());
          getCodeGenerator()->HandleVTable(CXXRD, /*isRequired*/true);
          break;
        }
        default:
          llvm_unreachable("We shouldn't have decl without call info.");
        }
      }
      getCodeGenerator()->HandleTranslationUnit(getCI()->getASTContext());
      // run the static initializers that came from codegenning
      if (m_Interpreter->runStaticInitializersOnce()
          >= Interpreter::kExeFirstError) {
        // Roll back on error in a transformer
        rollbackTransaction(T);
        return;
      }
    }

    T->setState(Transaction::kCommitted);
    InterpreterCallbacks* callbacks = m_Interpreter->getCallbacks();

    if (callbacks)
      callbacks->TransactionCommitted(*T);
  }

  void IncrementalParser::rollbackTransaction(Transaction* T) const {
    ASTNodeEraser NodeEraser(&getCI()->getSema());

    if (NodeEraser.RevertTransaction(T))
      T->setState(Transaction::kRolledBack);
    else
      T->setState(Transaction::kRolledBackWithErrors);
  }

  std::vector<const Transaction*> IncrementalParser::getAllTransactions() {
    std::vector<const Transaction*> result;
    const cling::Transaction* T = getFirstTransaction();
    while (T) {
      result.push_back(T);
      T = T->getNext();
    }
    return result;
  }

  // Each input line is contained in separate memory buffer. The SourceManager
  // assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry
  // for the MemoryBuffer's FileID. That in turn is problem because invalid
  // SourceLocations are given to the diagnostics. Thus the diagnostics cannot
  // order the overloads, for example
  //
  // Our work-around is creating a virtual file, which doesn't exist on the disk
  // with enormous size (no allocation is done). That file has valid FileEntry
  // and so on... We use it for generating valid SourceLocations with valid
  // offsets so that it doesn't cause any troubles to the diagnostics.
  //
  // +---------------------+
  // | Main memory buffer  |
  // +---------------------+
  // |  Virtual file SLoc  |
  // |    address space    |<-----------------+
  // |         ...         |<------------+    |
  // |         ...         |             |    |
  // |         ...         |<----+       |    |
  // |         ...         |     |       |    |
  // +~~~~~~~~~~~~~~~~~~~~~+     |       |    |
  // |     input_line_1    | ....+.......+..--+
  // +---------------------+     |       |
  // |     input_line_2    | ....+.....--+
  // +---------------------+     |
  // |          ...        |     |
  // +---------------------+     |
  // |     input_line_N    | ..--+
  // +---------------------+
  //
  void IncrementalParser::CreateSLocOffsetGenerator() {
    SourceManager& SM = getCI()->getSourceManager();
    FileManager& FM = SM.getFileManager();
    const FileEntry* FE
      = FM.getVirtualFile("InteractiveInputLineIncluder.h", 1U << 15U, time(0));
    m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);

    assert(!m_VirtualFileID.isInvalid() && "No VirtualFileID created?");
  }

  Transaction* IncrementalParser::Compile(llvm::StringRef input,
                                          const CompilationOptions& Opts) {

    Transaction* CurT = beginTransaction(Opts);
    EParseResult ParseRes = ParseInternal(input);

    if (ParseRes == kSuccessWithWarnings)
      CurT->setIssuedDiags(Transaction::kWarnings);
    else if (ParseRes == kFailed)
      CurT->setIssuedDiags(Transaction::kErrors);

    endTransaction();
    commitTransaction(CurT);

    return CurT;
  }

  Transaction* IncrementalParser::Parse(llvm::StringRef input,
                                        const CompilationOptions& Opts) {
    beginTransaction(Opts);
    ParseInternal(input);
    return endTransaction();
  }

  // Add the input to the memory buffer, parse it, and add it to the AST.
  IncrementalParser::EParseResult
  IncrementalParser::ParseInternal(llvm::StringRef input) {
    if (input.empty()) return IncrementalParser::kSuccess;

    PrettyStackTraceParserEntry CrashInfo(*m_Parser.get());

    // Recover resources if we crash before exiting this method.
    llvm::CrashRecoveryContextCleanupRegistrar<Parser>
      CleanupParser(m_Parser.get());

    Sema& S = getCI()->getSema();
    // Recover resources if we crash before exiting this method.
    llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(&S);

    Preprocessor& PP = m_CI->getPreprocessor();
    if (!PP.getCurrentLexer()) {
       PP.EnterSourceFile(m_CI->getSourceManager().getMainFileID(),
                          0, SourceLocation());
    }
    assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
    PP.enableIncrementalProcessing();

    std::ostringstream source_name;
    source_name << "input_line_" << (m_MemoryBuffers.size() + 1);

    // Create an uninitialized memory buffer, copy code in and append "\n"
    size_t InputSize = input.size(); // don't include trailing 0
    // MemBuffer size should *not* include terminating zero
    llvm::MemoryBuffer* MB
      = llvm::MemoryBuffer::getNewUninitMemBuffer(InputSize + 1,
                                                  source_name.str());
    char* MBStart = const_cast<char*>(MB->getBufferStart());
    memcpy(MBStart, input.data(), InputSize);
    memcpy(MBStart + InputSize, "\n", 2);

    m_MemoryBuffers.push_back(MB);
    SourceManager& SM = getCI()->getSourceManager();

    // Create SourceLocation, which will allow clang to order the overload
    // candidates for example
    SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);
    NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffers.size() + 1);

    // Create FileID for the current buffer
    FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffers.back(),
                                             /*LoadedID*/0,
                                             /*LoadedOffset*/0, NewLoc);

    PP.EnterSourceFile(FID, /*DirLookup*/0, NewLoc);

    Parser::DeclGroupPtrTy ADecl;

    while (!m_Parser->ParseTopLevelDecl(ADecl)) {
      // If we got a null return and something *was* parsed, ignore it.  This
      // is due to a top-level semicolon, an action override, or a parse error
      // skipping something.
      if (ADecl)
        m_Consumer->HandleTopLevelDecl(ADecl.getAsVal<DeclGroupRef>());
    };

    // Process any TopLevelDecls generated by #pragma weak.
    for (llvm::SmallVector<Decl*,2>::iterator I = S.WeakTopLevelDecls().begin(),
           E = S.WeakTopLevelDecls().end(); I != E; ++I) {
      m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
    }

    DiagnosticsEngine& Diag = S.getDiagnostics();
    if (Diag.hasErrorOccurred())
      return IncrementalParser::kFailed;
    else if (Diag.getNumWarnings())
      return IncrementalParser::kSuccessWithWarnings;

    return IncrementalParser::kSuccess;
  }

  void IncrementalParser::unloadTransaction(Transaction* T) {
    if (!T)
      T = getLastTransaction();

    assert(T->getState() == Transaction::kCommitted &&
           "Unloading not commited transaction?");
    assert(T->getModule() &&
           "Trying to uncodegen transaction taken in syntax only mode. ");

    ASTNodeEraser NodeEraser(&getCI()->getSema());
    NodeEraser.RevertTransaction(T);

    InterpreterCallbacks* callbacks = m_Interpreter->getCallbacks();
    if (callbacks)
      callbacks->TransactionUnloaded(*T);
  }

} // namespace cling
<commit_msg>We use kCCINone internally as delimiter in the Transaction<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "IncrementalParser.h"
#include "ASTDumper.h"
#include "ASTNodeEraser.h"
#include "DeclCollector.h"
#include "DeclExtractor.h"
#include "DynamicLookup.h"
#include "ReturnSynthesizer.h"
#include "ValuePrinterSynthesizer.h"
#include "cling/Interpreter/CIFactory.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Interpreter/Transaction.h"

#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclGroup.h"
#include "clang/Basic/FileManager.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Parse/Parser.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Serialization/ASTWriter.h"

#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_os_ostream.h"

#include <ctime>
#include <iostream>
#include <stdio.h>
#include <sstream>

using namespace clang;

namespace cling {
  IncrementalParser::IncrementalParser(Interpreter* interp,
                                       int argc, const char* const *argv,
                                       const char* llvmdir):
    m_Interpreter(interp), m_Consumer(0), m_FirstTransaction(0),
    m_LastTransaction(0) {

    CompilerInstance* CI
      = CIFactory::createCI(llvm::MemoryBuffer::getMemBuffer("", "CLING"),
                            argc, argv, llvmdir);
    assert(CI && "CompilerInstance is (null)!");

    m_Consumer = dyn_cast<DeclCollector>(&CI->getASTConsumer());
    assert(m_Consumer && "Expected ChainedConsumer!");

    m_CI.reset(CI);

    if (CI->getFrontendOpts().ProgramAction != clang::frontend::ParseSyntaxOnly){
      m_CodeGen.reset(CreateLLVMCodeGen(CI->getDiagnostics(), "cling input",
                                        CI->getCodeGenOpts(),
                                        *m_Interpreter->getLLVMContext()
                                        ));
    }

    CreateSLocOffsetGenerator();

    // Add transformers to the IncrementalParser, which owns them
    m_TTransformers.push_back(new EvaluateTSynthesizer(&CI->getSema()));

    m_TTransformers.push_back(new ValuePrinterSynthesizer(&CI->getSema(), 0));
    m_TTransformers.push_back(new ReturnSynthesizer(&CI->getSema()));
    m_TTransformers.push_back(new ASTDumper());
    m_TTransformers.push_back(new DeclExtractor(&getCI()->getSema()));

    m_Parser.reset(new Parser(CI->getPreprocessor(), CI->getSema(),
                              false /*skipFuncBodies*/));
    CI->getPreprocessor().EnterMainSourceFile();
    // Initialize the parser after we have entered the main source file.
    m_Parser->Initialize();
    // Perform initialization that occurs after the parser has been initialized
    // but before it parses anything. Initializes the consumers too.
    CI->getSema().Initialize();
  }

  IncrementalParser::~IncrementalParser() {
    if (hasCodeGenerator()) {
      getCodeGenerator()->ReleaseModule();
    }
    const Transaction* T = getFirstTransaction();
    const Transaction* nextT = 0;
    while (T) {
      nextT = T->getNext();
      delete T;
      T = nextT;
    }

    for (size_t i = 0; i < m_TTransformers.size(); ++i)
      delete m_TTransformers[i];
  }

  Transaction* IncrementalParser::beginTransaction(const CompilationOptions&
                                                   Opts) {
    llvm::Module* M = 0;
    if (hasCodeGenerator())
      M = getCodeGenerator()->GetModule();

    Transaction* NewCurT = new Transaction(Opts, M);
    Transaction* OldCurT = m_Consumer->getTransaction();
    m_Consumer->setTransaction(NewCurT);
    // If we are in the middle of transaction and we see another begin
    // transaction - it must be nested transaction.
    if (OldCurT && !OldCurT->isCompleted()) {
      OldCurT->addNestedTransaction(NewCurT); // takes the ownership
      return NewCurT;
    }

    if (!m_FirstTransaction) {
      m_FirstTransaction = NewCurT;
      m_LastTransaction = NewCurT;
    }
    else {
      m_LastTransaction->setNext(NewCurT);
      m_LastTransaction = NewCurT;
    }

    return NewCurT;
  }

  Transaction* IncrementalParser::endTransaction() const {
    Transaction* CurT = m_Consumer->getTransaction();
    CurT->setCompleted();
    const DiagnosticsEngine& Diags = getCI()->getSema().getDiagnostics();

    //TODO: Make the enum orable.
    if (Diags.getNumWarnings() > 0)
      CurT->setIssuedDiags(Transaction::kWarnings);

    if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred())
      CurT->setIssuedDiags(Transaction::kErrors);

    if (CurT->hasNestedTransactions()) {
      for(Transaction::const_nested_iterator I = CurT->nested_decls_begin(),
            E = CurT->nested_decls_end(); I != E; ++I)
        assert((*I)->isCompleted() && "Nested transaction not completed!?");
    }

    if (CurT->isNestedTransaction()) {
      // TODO: Add proper logic in the case where there are multiple nested
      // transaction. This now won't handle the case where there are more than
      // one level 1 nested transactions.
      m_Consumer->setTransaction(CurT->getParent());
    }

    return CurT;
  }

  void IncrementalParser::commitTransaction(Transaction* T) {
    //Transaction* CurT = m_Consumer->getTransaction();
    assert(T->isCompleted() && "Transaction not ended!?");

    // Check for errors...
    if (T->getIssuedDiags() == Transaction::kErrors) {
      rollbackTransaction(T);
      return;
    }

    if (T->hasNestedTransactions()) {
      for(Transaction::const_nested_iterator I = T->nested_decls_begin(),
            E = T->nested_decls_end(); I != E; ++I)
        commitTransaction(*I);
    }

    // We are sure it's safe to pipe it through the transformers
    bool success = true;
    for (size_t i = 0; i < m_TTransformers.size(); ++i) {
      success = m_TTransformers[i]->TransformTransaction(*T);
      if (!success) {
        break;
      }
    }

    m_CI->getDiagnostics().Reset(); // FIXME: Should be in rollback transaction.

    if (!success) {
      // Roll back on error in a transformer
      rollbackTransaction(T);
      return;
    }

    // Pull all template instantiations in that came from the consumers.
    getCI()->getSema().PerformPendingInstantiations();

    m_Consumer->HandleTranslationUnit(getCI()->getASTContext());

    if (T->getCompilationOpts().CodeGeneration && hasCodeGenerator()) {
      // Reset the module builder to clean up global initializers, c'tors, d'tors
      getCodeGenerator()->Initialize(getCI()->getASTContext());

      // codegen the transaction
      // We assume that there is no ordering of the calls to HandleXYZ, because
      // in clang they can happen in different order too, eg. coming from
      // template instatiator and so on.
      for (Transaction::iterator I = T->decls_begin(), E = T->decls_end();
           I != E; ++I) {
        switch (I->m_Call) {
        case Transaction::kCCIHandleTopLevelDecl :
          getCodeGenerator()->HandleTopLevelDecl(I->m_DGR);
          break;
        case Transaction::kCCIHandleInterestingDecl :
          getCodeGenerator()->HandleInterestingDecl(I->m_DGR);
          break;
        case Transaction::kCCIHandleTagDeclDefinition : {
          TagDecl* TD = cast<TagDecl>(I->m_DGR.getSingleDecl());
          getCodeGenerator()->HandleTagDeclDefinition(TD);
          break;
        }
        case Transaction::kCCIHandleVTable : {
          CXXRecordDecl* CXXRD = cast<CXXRecordDecl>(I->m_DGR.getSingleDecl());
          getCodeGenerator()->HandleVTable(CXXRD, /*isRequired*/true);
          break;
        }
        case Transaction::kCCINone:
          break; // We use that internally as delimiter in the Transaction.
        }
        default:
          llvm_unreachable("We shouldn't have decl without call info.");
        }
      }
      getCodeGenerator()->HandleTranslationUnit(getCI()->getASTContext());
      // run the static initializers that came from codegenning
      if (m_Interpreter->runStaticInitializersOnce()
          >= Interpreter::kExeFirstError) {
        // Roll back on error in a transformer
        rollbackTransaction(T);
        return;
      }
    }

    T->setState(Transaction::kCommitted);
    InterpreterCallbacks* callbacks = m_Interpreter->getCallbacks();

    if (callbacks)
      callbacks->TransactionCommitted(*T);
  }

  void IncrementalParser::rollbackTransaction(Transaction* T) const {
    ASTNodeEraser NodeEraser(&getCI()->getSema());

    if (NodeEraser.RevertTransaction(T))
      T->setState(Transaction::kRolledBack);
    else
      T->setState(Transaction::kRolledBackWithErrors);
  }

  std::vector<const Transaction*> IncrementalParser::getAllTransactions() {
    std::vector<const Transaction*> result;
    const cling::Transaction* T = getFirstTransaction();
    while (T) {
      result.push_back(T);
      T = T->getNext();
    }
    return result;
  }

  // Each input line is contained in separate memory buffer. The SourceManager
  // assigns sort-of invalid FileID for each buffer, i.e there is no FileEntry
  // for the MemoryBuffer's FileID. That in turn is problem because invalid
  // SourceLocations are given to the diagnostics. Thus the diagnostics cannot
  // order the overloads, for example
  //
  // Our work-around is creating a virtual file, which doesn't exist on the disk
  // with enormous size (no allocation is done). That file has valid FileEntry
  // and so on... We use it for generating valid SourceLocations with valid
  // offsets so that it doesn't cause any troubles to the diagnostics.
  //
  // +---------------------+
  // | Main memory buffer  |
  // +---------------------+
  // |  Virtual file SLoc  |
  // |    address space    |<-----------------+
  // |         ...         |<------------+    |
  // |         ...         |             |    |
  // |         ...         |<----+       |    |
  // |         ...         |     |       |    |
  // +~~~~~~~~~~~~~~~~~~~~~+     |       |    |
  // |     input_line_1    | ....+.......+..--+
  // +---------------------+     |       |
  // |     input_line_2    | ....+.....--+
  // +---------------------+     |
  // |          ...        |     |
  // +---------------------+     |
  // |     input_line_N    | ..--+
  // +---------------------+
  //
  void IncrementalParser::CreateSLocOffsetGenerator() {
    SourceManager& SM = getCI()->getSourceManager();
    FileManager& FM = SM.getFileManager();
    const FileEntry* FE
      = FM.getVirtualFile("InteractiveInputLineIncluder.h", 1U << 15U, time(0));
    m_VirtualFileID = SM.createFileID(FE, SourceLocation(), SrcMgr::C_User);

    assert(!m_VirtualFileID.isInvalid() && "No VirtualFileID created?");
  }

  Transaction* IncrementalParser::Compile(llvm::StringRef input,
                                          const CompilationOptions& Opts) {

    Transaction* CurT = beginTransaction(Opts);
    EParseResult ParseRes = ParseInternal(input);

    if (ParseRes == kSuccessWithWarnings)
      CurT->setIssuedDiags(Transaction::kWarnings);
    else if (ParseRes == kFailed)
      CurT->setIssuedDiags(Transaction::kErrors);

    endTransaction();
    commitTransaction(CurT);

    return CurT;
  }

  Transaction* IncrementalParser::Parse(llvm::StringRef input,
                                        const CompilationOptions& Opts) {
    beginTransaction(Opts);
    ParseInternal(input);
    return endTransaction();
  }

  // Add the input to the memory buffer, parse it, and add it to the AST.
  IncrementalParser::EParseResult
  IncrementalParser::ParseInternal(llvm::StringRef input) {
    if (input.empty()) return IncrementalParser::kSuccess;

    PrettyStackTraceParserEntry CrashInfo(*m_Parser.get());

    // Recover resources if we crash before exiting this method.
    llvm::CrashRecoveryContextCleanupRegistrar<Parser>
      CleanupParser(m_Parser.get());

    Sema& S = getCI()->getSema();
    // Recover resources if we crash before exiting this method.
    llvm::CrashRecoveryContextCleanupRegistrar<Sema> CleanupSema(&S);

    Preprocessor& PP = m_CI->getPreprocessor();
    if (!PP.getCurrentLexer()) {
       PP.EnterSourceFile(m_CI->getSourceManager().getMainFileID(),
                          0, SourceLocation());
    }
    assert(PP.isIncrementalProcessingEnabled() && "Not in incremental mode!?");
    PP.enableIncrementalProcessing();

    std::ostringstream source_name;
    source_name << "input_line_" << (m_MemoryBuffers.size() + 1);

    // Create an uninitialized memory buffer, copy code in and append "\n"
    size_t InputSize = input.size(); // don't include trailing 0
    // MemBuffer size should *not* include terminating zero
    llvm::MemoryBuffer* MB
      = llvm::MemoryBuffer::getNewUninitMemBuffer(InputSize + 1,
                                                  source_name.str());
    char* MBStart = const_cast<char*>(MB->getBufferStart());
    memcpy(MBStart, input.data(), InputSize);
    memcpy(MBStart + InputSize, "\n", 2);

    m_MemoryBuffers.push_back(MB);
    SourceManager& SM = getCI()->getSourceManager();

    // Create SourceLocation, which will allow clang to order the overload
    // candidates for example
    SourceLocation NewLoc = SM.getLocForStartOfFile(m_VirtualFileID);
    NewLoc = NewLoc.getLocWithOffset(m_MemoryBuffers.size() + 1);

    // Create FileID for the current buffer
    FileID FID = SM.createFileIDForMemBuffer(m_MemoryBuffers.back(),
                                             /*LoadedID*/0,
                                             /*LoadedOffset*/0, NewLoc);

    PP.EnterSourceFile(FID, /*DirLookup*/0, NewLoc);

    Parser::DeclGroupPtrTy ADecl;

    while (!m_Parser->ParseTopLevelDecl(ADecl)) {
      // If we got a null return and something *was* parsed, ignore it.  This
      // is due to a top-level semicolon, an action override, or a parse error
      // skipping something.
      if (ADecl)
        m_Consumer->HandleTopLevelDecl(ADecl.getAsVal<DeclGroupRef>());
    };

    // Process any TopLevelDecls generated by #pragma weak.
    for (llvm::SmallVector<Decl*,2>::iterator I = S.WeakTopLevelDecls().begin(),
           E = S.WeakTopLevelDecls().end(); I != E; ++I) {
      m_Consumer->HandleTopLevelDecl(DeclGroupRef(*I));
    }

    DiagnosticsEngine& Diag = S.getDiagnostics();
    if (Diag.hasErrorOccurred())
      return IncrementalParser::kFailed;
    else if (Diag.getNumWarnings())
      return IncrementalParser::kSuccessWithWarnings;

    return IncrementalParser::kSuccess;
  }

  void IncrementalParser::unloadTransaction(Transaction* T) {
    if (!T)
      T = getLastTransaction();

    assert(T->getState() == Transaction::kCommitted &&
           "Unloading not commited transaction?");
    assert(T->getModule() &&
           "Trying to uncodegen transaction taken in syntax only mode. ");

    ASTNodeEraser NodeEraser(&getCI()->getSema());
    NodeEraser.RevertTransaction(T);

    InterpreterCallbacks* callbacks = m_Interpreter->getCallbacks();
    if (callbacks)
      callbacks->TransactionUnloaded(*T);
  }

} // namespace cling
<|endoftext|>


<commit_before>#ifndef ALEPH_UTILITIES_EMPTY_FUNCTOR_HH__
#define ALEPH_UTILITIES_EMPTY_FUNCTOR_HH__

namespace aleph
{

namespace utilities
{

/**
  @class EmptyFunctor
  @brief Basic drop-in empty functor class

  This class is a generic drop-in replacement for functors taking an arbitrary
  number of arguments. This is useful when algorithms expect a functor but the
  client does not require providing one.
*/

class EmptyFunctor
{
public:
  template <class... T> bool operator()( T... /* arguments */ )
  {
    return true;
  }
};

} // namespace utilities

} // namespace aleph

#endif
<commit_msg>Extended empty functor interface<commit_after>#ifndef ALEPH_UTILITIES_EMPTY_FUNCTOR_HH__
#define ALEPH_UTILITIES_EMPTY_FUNCTOR_HH__

namespace aleph
{

namespace utilities
{

/**
  @class EmptyFunctor
  @brief Basic drop-in empty functor class

  This class is a generic drop-in replacement for functors taking an arbitrary
  number of arguments. This is useful when algorithms expect a functor but the
  client does not require providing one.
*/

class EmptyFunctor
{
public:
  template <class... T> bool operator()( T... /* arguments */ )
  {
    return true;
  }

  template <class... T> bool initialize( T... /* arguments */ )
  {
    return true;
  }
};

} // namespace utilities

} // namespace aleph

#endif
<|endoftext|>


<commit_before>#ifndef NETWORKING_H
#define NETWORKING_H

#include <iostream>
#include <set>

#ifdef _WIN32
	#include <windows.h>
	#include <tchar.h>
	#include <stdio.h>
	#include <strsafe.h>
#else
	#include <signal.h>
	#include <time.h>
	#include <sys/types.h>
	#include <sys/stat.h>
	#include <fcntl.h>
	#include <sys/select.h>
	#include <unistd.h>
#endif

#include "../core/hlt.hpp"

extern bool quiet_output;

class Networking {
public:
	void startAndConnectBot(std::string command);
	void handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playerMillis, std::string * playerName);
	void handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves);
	void killPlayer(unsigned char playerTag);
	bool isProcessDead(unsigned char playerTag);
	int numberOfPlayers();

	std::vector<std::string> player_logs;

private:
#ifdef _WIN32
	struct WinConnection {
		HANDLE write, read;
	};
	std::vector<WinConnection> connections;
	std::vector<HANDLE> processes;
#else
	struct UniConnection {
		int read, write;
	};
	std::vector< UniConnection > connections;
	std::vector<int> processes;
#endif

	std::string serializeMap(const hlt::Map & map);
	std::set<hlt::Move> deserializeMoveSet(std::string & inputString, const hlt::Map & m);

	void sendString(unsigned char playerTag, std::string &sendString);
	std::string getString(unsigned char playerTag, unsigned int timoutMillis);
};

#endif
<commit_msg>In hpp, changed player logs from vec of vec of strings to vec of strings<commit_after>#ifndef NETWORKING_H
#define NETWORKING_H

#include <iostream>
#include <set>

#ifdef _WIN32
	#include <windows.h>
	#include <tchar.h>
	#include <stdio.h>
	#include <strsafe.h>
#else
	#include <signal.h>
	#include <time.h>
	#include <sys/types.h>
	#include <sys/stat.h>
	#include <fcntl.h>
	#include <sys/select.h>
	#include <unistd.h>
#endif

#include "../core/hlt.hpp"

extern bool quiet_output;

class Networking {
public:
	void startAndConnectBot(std::string command);
	void handleInitNetworking(unsigned char playerTag, const hlt::Map & m, int * playerMillis, std::string * playerName);
	void handleFrameNetworking(unsigned char playerTag, const hlt::Map & m, int * playermillis, std::set<hlt::Move> * moves);
	void killPlayer(unsigned char playerTag);
	bool isProcessDead(unsigned char playerTag);
	int numberOfPlayers();

	std::vector< std::string> player_logs;

private:
#ifdef _WIN32
	struct WinConnection {
		HANDLE write, read;
	};
	std::vector<WinConnection> connections;
	std::vector<HANDLE> processes;
#else
	struct UniConnection {
		int read, write;
	};
	std::vector< UniConnection > connections;
	std::vector<int> processes;
#endif

	std::string serializeMap(const hlt::Map & map);
	std::set<hlt::Move> deserializeMoveSet(std::string & inputString, const hlt::Map & m);

	void sendString(unsigned char playerTag, std::string &sendString);
	std::string getString(unsigned char playerTag, unsigned int timoutMillis);
};

#endif
<|endoftext|>


<commit_before>#include "catch/catch.hpp"
#include "SQLiteXX.h"

#include <string>
#include <utility>
#include <vector>

TEST_CASE("Combinations of OpenMode flags with new database", "[DBConnection]") {
    remove("testDBConnection.db");

    SECTION("Open file as read only but file does not exist") {
        REQUIRE_THROWS_AS(SQLite::DBConnection("testDBConnection.db", SQLite::OpenMode::ReadOnly), SQLite::Exception);
    }

    SECTION("Open and create file with ReadOnly") {
        REQUIRE_THROWS_AS(SQLite::DBConnection("testDBConnection.db", SQLite::OpenMode::ReadOnly | SQLite::OpenMode::Create), SQLite::Exception);
    }

    SECTION("Open and create file with ReadWrite") {
        REQUIRE_NOTHROW(SQLite::DBConnection("testDBConnection.db", SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create));
    }

    SECTION("Open, create, and write to file") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create);

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }
}

TEST_CASE("Combinations of OpenMode flags with already existing database", "[DBConnection]") {
    remove("testDBConnection.db");
    {
        SQLite::DBConnection connection("testDBConnection.db");

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("Open ReadOnly") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadOnly);

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);

        REQUIRE_THROWS_AS(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"), SQLite::Exception);
    }

    SECTION("Open ReadWrite") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadWrite);

        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"two\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("Open ReadWrite and Create") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create);

        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"two\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }
}

TEST_CASE("Combinations of OpenMode mutex flags", "[DBConnection]") {
    remove("testDBConnection.db");

    SECTION("Opening database with no Mutex") {
        SQLite::DBConnection connection(
            "testDBConnection.db",
            SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create | SQLite::OpenMode::NoMutex);

        REQUIRE_THROWS_AS(connection.getMutex(), SQLite::SQLiteXXException);
    }
}

TEST_CASE("DBConnection UTF8 Support", "[DBConnection]") {
    remove("testDBConnection_utf8.db");

    SECTION("Memory database") {
        SQLite::DBConnection connection = SQLite::DBConnection::wideMemory();

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("File database using open") {
        SQLite::DBConnection connection;
        connection.open(L"testDBConnection_utf8.db");

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("File database from contructor") {
        SQLite::DBConnection connection(L"testDBConnection_utf8.db");

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }
}
<commit_msg>Fixed using wrong string literals for UTF16<commit_after>#include "catch/catch.hpp"
#include "SQLiteXX.h"

#include <string>
#include <utility>
#include <vector>

TEST_CASE("Combinations of OpenMode flags with new database", "[DBConnection]") {
    remove("testDBConnection.db");

    SECTION("Open file as read only but file does not exist") {
        REQUIRE_THROWS_AS(SQLite::DBConnection("testDBConnection.db", SQLite::OpenMode::ReadOnly), SQLite::Exception);
    }

    SECTION("Open and create file with ReadOnly") {
        REQUIRE_THROWS_AS(SQLite::DBConnection("testDBConnection.db", SQLite::OpenMode::ReadOnly | SQLite::OpenMode::Create), SQLite::Exception);
    }

    SECTION("Open and create file with ReadWrite") {
        REQUIRE_NOTHROW(SQLite::DBConnection("testDBConnection.db", SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create));
    }

    SECTION("Open, create, and write to file") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create);

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }
}

TEST_CASE("Combinations of OpenMode flags with already existing database", "[DBConnection]") {
    remove("testDBConnection.db");
    {
        SQLite::DBConnection connection("testDBConnection.db");

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("Open ReadOnly") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadOnly);

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);

        REQUIRE_THROWS_AS(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"), SQLite::Exception);
    }

    SECTION("Open ReadWrite") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadWrite);

        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"two\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("Open ReadWrite and Create") {
        SQLite::DBConnection connection("testDBConnection.db", SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create);

        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"two\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }
}

TEST_CASE("Combinations of OpenMode mutex flags", "[DBConnection]") {
    remove("testDBConnection.db");

    SECTION("Opening database with no Mutex") {
        SQLite::DBConnection connection(
            "testDBConnection.db",
            SQLite::OpenMode::ReadWrite | SQLite::OpenMode::Create | SQLite::OpenMode::NoMutex);

        REQUIRE_THROWS_AS(connection.getMutex(), SQLite::SQLiteXXException);
    }
}

TEST_CASE("DBConnection UTF8 Support", "[DBConnection]") {
    remove("testDBConnection_utf16.db");

    SECTION("Memory database") {
        SQLite::DBConnection connection = SQLite::DBConnection::wideMemory();

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("File database using open") {
        SQLite::DBConnection connection;
        connection.open(u"testDBConnection_utf16.db");

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }

    SECTION("File database from contructor") {
        SQLite::DBConnection connection(u"testDBConnection_utf16.db");

        REQUIRE_NOTHROW(Execute(connection, "CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)"));
        REQUIRE_NOTHROW(Execute(connection, "INSERT INTO test VALUES (NULL, \"one\")"));

        SQLite::Statement query(connection, "SELECT * FROM test");
        REQUIRE(query.getColumnCount() == 2);
    }
}
<|endoftext|>


<commit_before><commit_msg>Revert temporary and not properly ifdeffed Android stuff<commit_after><|endoftext|>


<commit_before>#include "test.h"

#include <cstdlib>

#include <QtCore/QTimer>

#include <TelepathyQt4/Types>
#include <TelepathyQt4/Debug>
#include <TelepathyQt4/DBus>
#include <TelepathyQt4/PendingVoid>

using Tp::PendingOperation;
using Tp::PendingVoid;
using Tp::Client::DBus::PeerInterface;

Test::Test(QObject *parent)
    : QObject(parent), mLoop(new QEventLoop(this))
{
    QTimer::singleShot(10 * 60 * 1000, this, SLOT(onWatchdog()));
}

Test::~Test()
{
    delete mLoop;
}

void Test::initTestCaseImpl()
{
    Tp::registerTypes();
    Tp::enableDebug(true);
    Tp::enableWarnings(true);

    QVERIFY(QDBusConnection::sessionBus().isConnected());
}

void Test::initImpl()
{
}

void Test::cleanupImpl()
{
}

void Test::cleanupTestCaseImpl()
{
}

void Test::expectSuccessfulCall(PendingOperation *op)
{
    if (op->isError()) {
        qWarning().nospace() << op->errorName()
            << ": " << op->errorMessage();
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void Test::expectSuccessfulCall(QDBusPendingCallWatcher *watcher)
{
    if (watcher->isError()) {
        qWarning().nospace() << watcher->error().name()
            << ": " << watcher->error().message();
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void Test::expectFailure(PendingOperation *op)
{
    if (!op->isError()) {
        qWarning() << "expectFailure(): should have been an error, but wasn't";
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void Test::processDBusQueue(Tp::DBusProxy *proxy)
{
    // Call method Ping on the D-Bus Peer interface
    PeerInterface peer(proxy);
    PendingVoid *call = new PendingVoid(peer.Ping(), this);

    // Wait for the reply to the Ping call
    QVERIFY(connect(call,
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
}

void Test::onWatchdog()
{
    // We can't use QFAIL because the test would then go to cleanup() and/or cleanupTestCase(),
    // which would often hang too - so let's just use abort
    qWarning() << "Test took over 10 minutes to finish, it's probably hung up - aborting";
    std::abort();
}
<commit_msg>tests/telepathyplugin: Removed trailing whitespace.<commit_after>#include "test.h"

#include <cstdlib>

#include <QtCore/QTimer>

#include <TelepathyQt4/Types>
#include <TelepathyQt4/Debug>
#include <TelepathyQt4/DBus>
#include <TelepathyQt4/PendingVoid>

using Tp::PendingOperation;
using Tp::PendingVoid;
using Tp::Client::DBus::PeerInterface;

Test::Test(QObject *parent)
    : QObject(parent), mLoop(new QEventLoop(this))
{
    QTimer::singleShot(10 * 60 * 1000, this, SLOT(onWatchdog()));
}

Test::~Test()
{
    delete mLoop;
}

void Test::initTestCaseImpl()
{
    Tp::registerTypes();
    Tp::enableDebug(true);
    Tp::enableWarnings(true);

    QVERIFY(QDBusConnection::sessionBus().isConnected());
}

void Test::initImpl()
{
}

void Test::cleanupImpl()
{
}

void Test::cleanupTestCaseImpl()
{
}

void Test::expectSuccessfulCall(PendingOperation *op)
{
    if (op->isError()) {
        qWarning().nospace() << op->errorName()
            << ": " << op->errorMessage();
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void Test::expectSuccessfulCall(QDBusPendingCallWatcher *watcher)
{
    if (watcher->isError()) {
        qWarning().nospace() << watcher->error().name()
            << ": " << watcher->error().message();
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void Test::expectFailure(PendingOperation *op)
{
    if (!op->isError()) {
        qWarning() << "expectFailure(): should have been an error, but wasn't";
        mLoop->exit(1);
        return;
    }

    mLoop->exit(0);
}

void Test::processDBusQueue(Tp::DBusProxy *proxy)
{
    // Call method Ping on the D-Bus Peer interface
    PeerInterface peer(proxy);
    PendingVoid *call = new PendingVoid(peer.Ping(), this);

    // Wait for the reply to the Ping call
    QVERIFY(connect(call,
                SIGNAL(finished(Tp::PendingOperation*)),
                SLOT(expectSuccessfulCall(Tp::PendingOperation*))));
    QCOMPARE(mLoop->exec(), 0);
}

void Test::onWatchdog()
{
    // We can't use QFAIL because the test would then go to cleanup() and/or cleanupTestCase(),
    // which would often hang too - so let's just use abort
    qWarning() << "Test took over 10 minutes to finish, it's probably hung up - aborting";
    std::abort();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: cvtgrf.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: kz $ $Date: 2003-11-18 14:33:10 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#define _SV_CVTGRF_CXX

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_METAACT_HXX
#include <metaact.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_CVTGRF_HXX
#include <cvtgrf.hxx>
#endif

// --------------
// - Callback   -
// --------------

// --------------------
// - GraphicConverter -
// --------------------

GraphicConverter::GraphicConverter() :
    mpConvertData( NULL )
{
}

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

GraphicConverter::~GraphicConverter()
{
}

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

ULONG GraphicConverter::ImplConvert( ULONG nInFormat, void* pInBuffer, ULONG nInBufSize,
                                     void** ppOutBuffer, ULONG nOutFormat )
{
    ULONG nRetBufSize = 0UL;

    if( ( nInFormat != nOutFormat ) && pInBuffer )
    {
        if( ( nInFormat == CVT_SVM ) || ( nInFormat == CVT_BMP ) )
        {
            SvMemoryStream  aIStm;
            Graphic         aGraphic;

            aIStm.SetBuffer( (char*) pInBuffer, nInBufSize, FALSE, nInBufSize );
            aIStm >> aGraphic;

            if( !aIStm.GetError() )
            {
                SvMemoryStream aOStm( 64535, 64535 );

                mpConvertData = new ConvertData( aGraphic, aOStm, nOutFormat );

                if( maFilterHdl.IsSet() && maFilterHdl.Call( mpConvertData ) )
                {
                    nRetBufSize = aOStm.Seek( STREAM_SEEK_TO_END );
                    *ppOutBuffer = (void*) aOStm.GetData();
                    aOStm.ObjectOwnsMemory( FALSE );
                }

                delete mpConvertData;
                mpConvertData = NULL;
            }
        }
        else if( ( nOutFormat == CVT_SVM ) || ( nOutFormat == CVT_BMP ) )
        {
            SvMemoryStream  aIStm;

            aIStm.SetBuffer( (char*) pInBuffer, nInBufSize, FALSE, nInBufSize );
            mpConvertData = new ConvertData( Graphic(), aIStm, nInFormat );

            if( maFilterHdl.IsSet() && maFilterHdl.Call( mpConvertData ) )
            {
                SvMemoryStream  aOStm( 645535, 64535 );
                Graphic&        rGraphic = mpConvertData->maGraphic;

                if( ( rGraphic.GetType() == GRAPHIC_BITMAP ) && ( CVT_SVM == nOutFormat ) )
                {
                    GDIMetaFile aMtf;

                    aMtf.SetPrefSize( rGraphic.GetPrefSize() );
                    aMtf.SetPrefMapMode( rGraphic.GetPrefMapMode() );
                    aMtf.AddAction( new MetaBmpExScaleAction( Point(), aMtf.GetPrefSize(), rGraphic.GetBitmapEx() ) );
                    rGraphic = aMtf;
                }
                else if( ( rGraphic.GetType() == GRAPHIC_GDIMETAFILE ) && ( CVT_BMP == nOutFormat ) )
                    rGraphic = rGraphic.GetBitmapEx();

                aOStm << rGraphic;

                if( !aOStm.GetError() )
                {
                    nRetBufSize = aOStm.Seek( STREAM_SEEK_TO_END );
                    *ppOutBuffer = (void*) aOStm.GetData();
                    aOStm.ObjectOwnsMemory( FALSE );
                }
            }

            delete mpConvertData;
            mpConvertData = NULL;
        }
    }

    return nRetBufSize;
}

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

ULONG GraphicConverter::Import( SvStream& rIStm, Graphic& rGraphic, ULONG nFormat )
{
    GraphicConverter*   pCvt = ImplGetSVData()->maGDIData.mpGrfConverter;
    ULONG               nRet = ERRCODE_IO_GENERAL;

    if( pCvt && pCvt->GetFilterHdl().IsSet() )
    {
        ConvertData aData( rGraphic, rIStm, nFormat );

        if( pCvt->GetFilterHdl().Call( &aData ) )
        {
            rGraphic = aData.maGraphic;
            nRet = ERRCODE_NONE;
        }
        else if( rIStm.GetError() )
            nRet = rIStm.GetError();
    }

    return nRet;
}

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

ULONG GraphicConverter::Export( SvStream& rOStm, const Graphic& rGraphic, ULONG nFormat )
{
    GraphicConverter*   pCvt = ImplGetSVData()->maGDIData.mpGrfConverter;
    ULONG               nRet = ERRCODE_IO_GENERAL;

    if( pCvt && pCvt->GetFilterHdl().IsSet() )
    {
        ConvertData aData( rGraphic, rOStm, nFormat );

        if( pCvt->GetFilterHdl().Call( &aData ) )
            nRet = ERRCODE_NONE;
        else if( rOStm.GetError() )
            nRet = rOStm.GetError();
    }

    return nRet;
}
<commit_msg>INTEGRATION: CWS vclcleanup02 (1.3.12); FILE MERGED 2003/12/17 16:04:15 mt 1.3.12.1: #i23061# header cleanup, remove #ifdef ???_CXX and #define ???_CXX, also removed .impl files and fixed soke windows compiler warnings<commit_after>/*************************************************************************
 *
 *  $RCSfile: cvtgrf.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: vg $ $Date: 2004-01-06 13:35:07 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SV_SVSYS_HXX
#include <svsys.h>
#endif
#ifndef _SV_METAACT_HXX
#include <metaact.hxx>
#endif
#ifndef _SV_SALINST_HXX
#include <salinst.hxx>
#endif
#ifndef _SV_SVDATA_HXX
#include <svdata.hxx>
#endif
#ifndef _SV_CVTGRF_HXX
#include <cvtgrf.hxx>
#endif

// --------------
// - Callback   -
// --------------

// --------------------
// - GraphicConverter -
// --------------------

GraphicConverter::GraphicConverter() :
    mpConvertData( NULL )
{
}

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

GraphicConverter::~GraphicConverter()
{
}

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

ULONG GraphicConverter::ImplConvert( ULONG nInFormat, void* pInBuffer, ULONG nInBufSize,
                                     void** ppOutBuffer, ULONG nOutFormat )
{
    ULONG nRetBufSize = 0UL;

    if( ( nInFormat != nOutFormat ) && pInBuffer )
    {
        if( ( nInFormat == CVT_SVM ) || ( nInFormat == CVT_BMP ) )
        {
            SvMemoryStream  aIStm;
            Graphic         aGraphic;

            aIStm.SetBuffer( (char*) pInBuffer, nInBufSize, FALSE, nInBufSize );
            aIStm >> aGraphic;

            if( !aIStm.GetError() )
            {
                SvMemoryStream aOStm( 64535, 64535 );

                mpConvertData = new ConvertData( aGraphic, aOStm, nOutFormat );

                if( maFilterHdl.IsSet() && maFilterHdl.Call( mpConvertData ) )
                {
                    nRetBufSize = aOStm.Seek( STREAM_SEEK_TO_END );
                    *ppOutBuffer = (void*) aOStm.GetData();
                    aOStm.ObjectOwnsMemory( FALSE );
                }

                delete mpConvertData;
                mpConvertData = NULL;
            }
        }
        else if( ( nOutFormat == CVT_SVM ) || ( nOutFormat == CVT_BMP ) )
        {
            SvMemoryStream  aIStm;

            aIStm.SetBuffer( (char*) pInBuffer, nInBufSize, FALSE, nInBufSize );
            mpConvertData = new ConvertData( Graphic(), aIStm, nInFormat );

            if( maFilterHdl.IsSet() && maFilterHdl.Call( mpConvertData ) )
            {
                SvMemoryStream  aOStm( 645535, 64535 );
                Graphic&        rGraphic = mpConvertData->maGraphic;

                if( ( rGraphic.GetType() == GRAPHIC_BITMAP ) && ( CVT_SVM == nOutFormat ) )
                {
                    GDIMetaFile aMtf;

                    aMtf.SetPrefSize( rGraphic.GetPrefSize() );
                    aMtf.SetPrefMapMode( rGraphic.GetPrefMapMode() );
                    aMtf.AddAction( new MetaBmpExScaleAction( Point(), aMtf.GetPrefSize(), rGraphic.GetBitmapEx() ) );
                    rGraphic = aMtf;
                }
                else if( ( rGraphic.GetType() == GRAPHIC_GDIMETAFILE ) && ( CVT_BMP == nOutFormat ) )
                    rGraphic = rGraphic.GetBitmapEx();

                aOStm << rGraphic;

                if( !aOStm.GetError() )
                {
                    nRetBufSize = aOStm.Seek( STREAM_SEEK_TO_END );
                    *ppOutBuffer = (void*) aOStm.GetData();
                    aOStm.ObjectOwnsMemory( FALSE );
                }
            }

            delete mpConvertData;
            mpConvertData = NULL;
        }
    }

    return nRetBufSize;
}

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

ULONG GraphicConverter::Import( SvStream& rIStm, Graphic& rGraphic, ULONG nFormat )
{
    GraphicConverter*   pCvt = ImplGetSVData()->maGDIData.mpGrfConverter;
    ULONG               nRet = ERRCODE_IO_GENERAL;

    if( pCvt && pCvt->GetFilterHdl().IsSet() )
    {
        ConvertData aData( rGraphic, rIStm, nFormat );

        if( pCvt->GetFilterHdl().Call( &aData ) )
        {
            rGraphic = aData.maGraphic;
            nRet = ERRCODE_NONE;
        }
        else if( rIStm.GetError() )
            nRet = rIStm.GetError();
    }

    return nRet;
}

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

ULONG GraphicConverter::Export( SvStream& rOStm, const Graphic& rGraphic, ULONG nFormat )
{
    GraphicConverter*   pCvt = ImplGetSVData()->maGDIData.mpGrfConverter;
    ULONG               nRet = ERRCODE_IO_GENERAL;

    if( pCvt && pCvt->GetFilterHdl().IsSet() )
    {
        ConvertData aData( rGraphic, rOStm, nFormat );

        if( pCvt->GetFilterHdl().Call( &aData ) )
            nRet = ERRCODE_NONE;
        else if( rOStm.GetError() )
            nRet = rOStm.GetError();
    }

    return nRet;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessibleEmptyEditSource.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2003-04-01 13:47:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef _SVX_ACCESSIBLEEMPTYEDITSOURCE_HXX
#define _SVX_ACCESSIBLEEMPTYEDITSOURCE_HXX

#ifndef _SFXBRDCST_HXX
#include <svtools/brdcst.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif

#include <memory>
#include "unoedsrc.hxx"

class SdrObject;
class SdrView;
class Window;

namespace accessibility
{
    /** Proxy edit source for shapes without text

        Extracted from old SvxDummyEditSource
     */
    class AccessibleEmptyEditSource : public SvxEditSource, public SfxListener, public SfxBroadcaster
    {
    public:
        /** Create proxy edit source for shapes without text

            Since the views don't broadcast their dying, make sure that
            this object gets destroyed if the view becomes invalid

            The window is necessary, since our views can display on multiple windows

            Make sure you only create such an object if the shape _really_
            does not contain text.
        */
        AccessibleEmptyEditSource(  SdrObject& rObj, SdrView& rView, const Window& rViewWindow );
        ~AccessibleEmptyEditSource();

        // from the SvxEditSource interface
        SvxTextForwarder*       GetTextForwarder();
        SvxViewForwarder*       GetViewForwarder();

        SvxEditSource*          Clone() const;

        // this method internally switches from empty to proxy mode,
        // creating an SvxTextEditSource for the functionality.
        SvxEditViewForwarder*   GetEditViewForwarder( sal_Bool bCreate = sal_False );

        void                    UpdateData();
        SfxBroadcaster&         GetBroadcaster() const;

        // from the SfxListener interface
        void                    Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    private:
        void Switch2ProxyEditSource();

        /** Pointer to edit source implementation. This is switched on
            a GetEditViewForwarder( true ) call, to actually create a
            SvxTextEditSource.

            @dyn
         */
        std::auto_ptr< SvxEditSource >  mpEditSource;

        SdrObject&                      mrObj;
        SdrView&                        mrView;
        const Window&                   mrViewWindow;

        bool                            mbEditSourceEmpty;
    };

} // namespace accessibility

#endif

<commit_msg>INTEGRATION: CWS ooo19126 (1.2.1478); FILE MERGED 2005/09/05 14:18:43 rt 1.2.1478.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AccessibleEmptyEditSource.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 20:14:53 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef _SVX_ACCESSIBLEEMPTYEDITSOURCE_HXX
#define _SVX_ACCESSIBLEEMPTYEDITSOURCE_HXX

#ifndef _SFXBRDCST_HXX
#include <svtools/brdcst.hxx>
#endif
#ifndef _SFXLSTNER_HXX
#include <svtools/lstner.hxx>
#endif

#include <memory>
#include "unoedsrc.hxx"

class SdrObject;
class SdrView;
class Window;

namespace accessibility
{
    /** Proxy edit source for shapes without text

        Extracted from old SvxDummyEditSource
     */
    class AccessibleEmptyEditSource : public SvxEditSource, public SfxListener, public SfxBroadcaster
    {
    public:
        /** Create proxy edit source for shapes without text

            Since the views don't broadcast their dying, make sure that
            this object gets destroyed if the view becomes invalid

            The window is necessary, since our views can display on multiple windows

            Make sure you only create such an object if the shape _really_
            does not contain text.
        */
        AccessibleEmptyEditSource(  SdrObject& rObj, SdrView& rView, const Window& rViewWindow );
        ~AccessibleEmptyEditSource();

        // from the SvxEditSource interface
        SvxTextForwarder*       GetTextForwarder();
        SvxViewForwarder*       GetViewForwarder();

        SvxEditSource*          Clone() const;

        // this method internally switches from empty to proxy mode,
        // creating an SvxTextEditSource for the functionality.
        SvxEditViewForwarder*   GetEditViewForwarder( sal_Bool bCreate = sal_False );

        void                    UpdateData();
        SfxBroadcaster&         GetBroadcaster() const;

        // from the SfxListener interface
        void                    Notify( SfxBroadcaster& rBC, const SfxHint& rHint );

    private:
        void Switch2ProxyEditSource();

        /** Pointer to edit source implementation. This is switched on
            a GetEditViewForwarder( true ) call, to actually create a
            SvxTextEditSource.

            @dyn
         */
        std::auto_ptr< SvxEditSource >  mpEditSource;

        SdrObject&                      mrObj;
        SdrView&                        mrView;
        const Window&                   mrViewWindow;

        bool                            mbEditSourceEmpty;
    };

} // namespace accessibility

#endif

<|endoftext|>


<commit_before><commit_msg>coverity#1266485 Untrusted value as argument<commit_after><|endoftext|>


<commit_before>#include "FireflyPathFinder.hpp"
#include "GreedyPathFinder.hpp"
#include <queue>
#include <iostream>
#include <limits>
#include <algorithm>
#include "Types.hpp"

using namespace FireflyAssembler;
using namespace std;

PathPointer FireflyPathFinder::findPath(IGraphConstPointer graph,
        FitnessFunctionPointer ff, DistanceMetricPointer dm)
{
	this->ff = ff;

    int populationSize = NUM_FIREFLIES * graph->sequenceCount();
    // generate random paths
	srand(time(0));
    for(int i=0 ; i<populationSize ; i++)
    {
    	vector<int> numbers;
    	for(int i=0 ; i<graph->sequenceCount() ; i++)
    		numbers.push_back(i);

    	random_shuffle(numbers.begin(), numbers.end());

    	fireflies.push_back(PathPointer(new Path(graph, numbers)));
    }
    int majority = (populationSize / 2) + 1;

    int equalFireflies = 0;
    int neededEqualities = (((graph->sequenceCount() * graph->sequenceCount()) -
        graph->sequenceCount()) * 2) / 3;
    for(int i=0 ; equalFireflies < neededEqualities && i<NUM_ITERATIONS ; i++)
    {
        equalFireflies = 0;

        for(vector<PathPointer>::iterator f1 = fireflies.begin();
                f1 != fireflies.end(); ++f1)
        {
            for(vector<PathPointer>::iterator f2 = fireflies.begin();
                    f2 != fireflies.end(); ++f2)
            {
                if (f1 != f2) {
                    double distance = dm->distance(**f1, **f2)+.0001;
                    double intensity = ff->rate(**f2)-ff->rate(**f1);
                    int movement = (int)floor(intensity/distance*MOVEMENT_RATE);
                    int moves_completed = 0;
                    int j=1;
                    while( j < graph->sequenceCount() && moves_completed < movement )
                    {
                        if((**f1)[j] != (**f2)[j]
                            && (*f2)->getGraph()->hasOverlap(j-1, j)
                            && (!(*f1)->getGraph()->hasOverlap(j-1, j) || (*f2)->getGraph()->getOverlap(j-1, j) > (*f1)->getGraph()->hasOverlap(j-1, j)))
                        {
                            (*f1)->swapSequences(j, (**f2)[j]);
                            moves_completed++;
                        }
                        j++;
                    }
                    if (**f1 == **f2)
                    {
                        equalFireflies++;
                    }
                }
            }
        }
    }
    printFireflies();
    vector<PathPointer>::iterator fittest = fireflies.begin();
    double fittest_rating = ff->rate(**fittest);
    for(vector<PathPointer>::iterator it = fireflies.begin() ; it != fireflies.end() ; ++it)
        if (ff->rate(**it) > fittest_rating)
        {
            fittest_rating = ff->rate(**it);
            fittest = it;
        }

	return *fittest;
}

void FireflyPathFinder::printFireflies()
{
	for(vector<PathPointer>::iterator firefly = fireflies.begin(); firefly != fireflies.end(); ++firefly)
    {
		cout << **firefly << "(rating: " << ff->rate(**firefly) << ") contigs: (" << (*firefly)->getContigs()->size() << ")" << endl;
    }
    cout << *fireflies[7] << endl;
}

<commit_msg>finder now only recalculates rating when necessary for efficiency<commit_after>#include "FireflyPathFinder.hpp"
#include "GreedyPathFinder.hpp"
#include <queue>
#include <iostream>
#include <limits>
#include <algorithm>
#include "Types.hpp"

using namespace FireflyAssembler;
using namespace std;

PathPointer FireflyPathFinder::findPath(IGraphConstPointer graph,
        FitnessFunctionPointer ff, DistanceMetricPointer dm)
{
	this->ff = ff;

    int populationSize = NUM_FIREFLIES * graph->sequenceCount();
    // generate random paths
	srand(time(0));
    for(int i=0 ; i<populationSize ; i++)
    {
    	vector<int> numbers;
    	for(int i=0 ; i<graph->sequenceCount() ; i++)
    		numbers.push_back(i);

    	random_shuffle(numbers.begin(), numbers.end());

        PathPointer path = PathPointer(new Path(graph, numbers));
        path->setRating(ff->rate(*path));
    	fireflies.push_back(path);
    }
    int majority = (populationSize / 2) + 1;

    int equalFireflies = 0;
    int neededEqualities = (((graph->sequenceCount() * graph->sequenceCount()) -
        graph->sequenceCount()) * 2) / 3;
    for(int i=0 ; equalFireflies < neededEqualities && i<NUM_ITERATIONS ; i++)
    {
        equalFireflies = 0;

        for(vector<PathPointer>::iterator f1 = fireflies.begin();
                f1 != fireflies.end(); ++f1)
        {
            for(vector<PathPointer>::iterator f2 = fireflies.begin();
                    f2 != fireflies.end(); ++f2)
            {
                if (f1 != f2) {
                    double distance = dm->distance(**f1, **f2)+.0001;
                    double intensity = (*f2)->getRating()-(*f1)->getRating();
                    int movement = (int)floor(intensity/distance*MOVEMENT_RATE);
                    int moves_completed = 0;
                    int j=1;
                    while( j < graph->sequenceCount() && moves_completed < movement )
                    {
                        if((**f1)[j] != (**f2)[j]
                            && (*f2)->getGraph()->hasOverlap(j-1, j)
                            && (!(*f1)->getGraph()->hasOverlap(j-1, j) || (*f2)->getGraph()->getOverlap(j-1, j) > (*f1)->getGraph()->hasOverlap(j-1, j)))
                        {
                            (*f1)->swapSequences(j, (**f2)[j]);
                            (*f1)->setRating(ff->rate(**f1));
                            moves_completed++;
                        }
                        j++;
                    }
                    if (**f1 == **f2)
                    {
                        equalFireflies++;
                    }
                }
            }
        }
    }
    printFireflies();
    vector<PathPointer>::iterator fittest = fireflies.begin();
    double fittest_rating = ff->rate(**fittest);
    for(vector<PathPointer>::iterator it = fireflies.begin() ; it != fireflies.end() ; ++it)
        if (ff->rate(**it) > fittest_rating)
        {
            fittest_rating = ff->rate(**it);
            fittest = it;
        }

	return *fittest;
}

void FireflyPathFinder::printFireflies()
{
	for(vector<PathPointer>::iterator firefly = fireflies.begin(); firefly != fireflies.end(); ++firefly)
    {
		cout << **firefly << "(rating: " << ff->rate(**firefly) << ") contigs: (" << (*firefly)->getContigs()->size() << ")" << endl;
    }
    cout << *fireflies[7] << endl;
}

<|endoftext|>


<commit_before><commit_msg>coverity#707564 Uninitialized scalar variable<commit_after><|endoftext|>


<commit_before>#include <cstdlib>
#include <iostream>
#include <algebra/infinite_vector.h>

using std::cout;
using std::endl;
using namespace MathTL;

int main()
{
  cout << "Testing the InfiniteVector class ..." << endl;

  InfiniteVector<float,long int> s;
  cout << "- a zero vector:" << endl
       << s << endl;

  cout << "- writing access on s:" << endl;
  s[1] = 2;
//  cout << "  (size after writing the first element: " << s.size() << ")" << endl;
  s[3] = 42;
//   cout << "  (size after writing the second element: " << s.size() << ")" << endl;
  cout << s;

  cout << "- copy constructor t(s):" << endl;
  InfiniteVector<float,long int> t(s);
  cout << t;

  cout << "- are the two vectors equal?" << endl;
  if (t == s)
    cout << "  ... yes!" << endl;
  else
    cout << "  ... no!" << endl;

  cout << "- are the two vectors inequal?" << endl;
  if (t != s)
    cout << "  ... yes!" << endl;
  else
    cout << "  ... no!" << endl;

  cout << "- in place summation s+=t:" << endl;
  s += t;
  cout << s;

  cout << "- in place subtraction t-=s:" << endl;
  t -= s;
  cout << t;

  cout << "- in place multiplication s*=2:" << endl;
  s *= 2;
  cout << s;

  cout << "- in place division s/=3:" << endl;
  s /= 3;
  cout << s;

  cout << "- ell_p norms of s:" << endl;
  cout << "  ||x||_2 = " << l2_norm(s)
       << ", ||x||_1 = " << l1_norm(s)
       << ", ||x||_infinity = " << linfty_norm(s) << endl;

  cout << "- external arithmetic functionality:" << endl;
  InfiniteVector<float,long int> sa, sb;
  sa[1] = 23; sa[2] = sa[3] = 10; sb[1] = -1.5; sb[3] = 3; sb[4] = 8;
  cout << "  a=" << endl << sa
       << "  b=" << endl << sb;
  swap(sa,sb);
  cout << "  after swapping, a=" << endl << sa << "  b=" << endl << sb;
  cout << "  a+b=" << endl << sa+sb
       << "  a-b=" << endl << sa-sb;
  cout << "  a*b=" << sa*sb << endl;
  cout << "  mean value of a: " << mean_value(sa) << endl;

  cout << "- preparing a large random vector for the NCOARSE routine with size ";
  InfiniteVector<float,int> v, w;
  for (unsigned int i=0; i < 1000; i++)
    {
      v[i] = (double)rand()/(double)RAND_MAX;
    }
  cout << v.size()
       << " and ||v||_2=" << l2_norm(v) << endl;

  double eps = 0.1;
  cout << "- NCOARSE(" << eps << ",w) yields w with ";
  v.n_coarse(eps,w);
  cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl;
  eps = 1.0;
  cout << "- NCOARSE(" << eps << ",w) yields w with ";
  v.n_coarse(eps,w);
  cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl;
  eps = 10.0;
  cout << "- NCOARSE(" << eps << ",w) yields w with ";
  v.n_coarse(eps,w);
  cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl;

  cout << "- some weak \\ell_\\tau norms of v:" << endl;
  for (double tau(1.8); tau >= 0.2; tau -= 0.2)
    {
      cout << "  tau=" << tau << ", ||v||_{\\ell^w_\\tau}=" << v.weak_norm(tau) << endl;
    }

  return 0;
}
<commit_msg>short size check in test program<commit_after>#include <cstdlib>
#include <iostream>
#include <algebra/infinite_vector.h>

using std::cout;
using std::endl;
using namespace MathTL;

int main()
{
  cout << "Testing the InfiniteVector class ..." << endl;

  InfiniteVector<float,long int> s;
  cout << "- a zero vector:" << endl
       << s << endl;

  cout << "- writing access on s:" << endl;
  s[1] = 2;
  cout << "  (size after writing the first element: " << s.size() << ")" << endl;
  s[3] = 42;
  cout << "  (size after writing the second element: " << s.size() << ")" << endl;
  cout << s;

  cout << "- copy constructor t(s):" << endl;
  InfiniteVector<float,long int> t(s);
  cout << t;

  cout << "- are the two vectors equal?" << endl;
  if (t == s)
    cout << "  ... yes!" << endl;
  else
    cout << "  ... no!" << endl;

  cout << "- are the two vectors inequal?" << endl;
  if (t != s)
    cout << "  ... yes!" << endl;
  else
    cout << "  ... no!" << endl;

  cout << "- in place summation s+=t:" << endl;
  s += t;
  cout << s;

  cout << "- in place subtraction t-=s:" << endl;
  t -= s;
  cout << t;

  cout << "- in place multiplication s*=2:" << endl;
  s *= 2;
  cout << s;

  cout << "- in place division s/=3:" << endl;
  s /= 3;
  cout << s;

  cout << "- ell_p norms of s:" << endl;
  cout << "  ||x||_2 = " << l2_norm(s)
       << ", ||x||_1 = " << l1_norm(s)
       << ", ||x||_infinity = " << linfty_norm(s) << endl;

  cout << "- external arithmetic functionality:" << endl;
  InfiniteVector<float,long int> sa, sb;
  sa[1] = 23; sa[2] = sa[3] = 10; sb[1] = -1.5; sb[3] = 3; sb[4] = 8;
  cout << "  a=" << endl << sa
       << "  b=" << endl << sb;
  swap(sa,sb);
  cout << "  after swapping, a=" << endl << sa << "  b=" << endl << sb;
  cout << "  a+b=" << endl << sa+sb
       << "  a-b=" << endl << sa-sb;
  cout << "  a*b=" << sa*sb << endl;
  cout << "  mean value of a: " << mean_value(sa) << endl;

  cout << "- preparing a large random vector for the NCOARSE routine with size ";
  InfiniteVector<float,int> v, w;
  for (unsigned int i=0; i < 1000; i++)
    {
      v[i] = (double)rand()/(double)RAND_MAX;
    }
  cout << v.size()
       << " and ||v||_2=" << l2_norm(v) << endl;

  double eps = 0.1;
  cout << "- NCOARSE(" << eps << ",w) yields w with ";
  v.n_coarse(eps,w);
  cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl;
  eps = 1.0;
  cout << "- NCOARSE(" << eps << ",w) yields w with ";
  v.n_coarse(eps,w);
  cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl;
  eps = 10.0;
  cout << "- NCOARSE(" << eps << ",w) yields w with ";
  v.n_coarse(eps,w);
  cout << w.size() << " entries and ||v-w||_2=" << l2_norm(v-w) << endl;

  cout << "- some weak \\ell_\\tau norms of v:" << endl;
  for (double tau(1.8); tau >= 0.2; tau -= 0.2)
    {
      cout << "  tau=" << tau << ", ||v||_{\\ell^w_\\tau}=" << v.weak_norm(tau) << endl;
    }

  return 0;
}
<|endoftext|>


<commit_before>#include "foreign.h"
#include "interp.hh"
#include "program.hh"

#include <initializer_list>
#include <list>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

Value::Value() : type(BOT) {}
Value::Value(const bool b) : type(BOOL) { value.b = b; }
Value::Value(const int i) : type(INT) { value.i = i; }
Value::Value(const float d) : type(FLOAT) { value.d = d; }
Value::Value(const Bool b) : type(BOOL) { value.b = b; }
Value::Value(const Int i) : type(INT) { value.i = i; }
Value::Value(const Float d) : type(FLOAT) { value.d = d; }
Value::Value(const Param &p) {
	switch (p.type) {
	case Param::INT:
		type = INT;
		value.i = p.value.i;
		break;
	case Param::FLOAT:
		type = FLOAT;
		value.d = p.value.d;
		break;
	case Param::STRING:
		throw (new InterpreterError())->with(_POS);
	default:
		throw (new InterpreterError())->with(_POS);
	}
}
Value::Value(const std::initializer_list <Value> &vs) : type(VEC) {
	v = vector<Value>(vs);
}
Value::Value(const vector <Value> &vs) : type(VEC), v(vs) {}
Value::Value(const list <Value> &vs) : type(LIST), l(vs) {}

Value::Value(const Foreign f) : type(FOREIGN) { value.f = f; }
Value::Value(const Vec_Int vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}
Value::Value(const Vec_Float vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}
Value::Value(const Vec_Bool vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}
Value::Value(const Vec_Foreign vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}

string Value::toString() const {
	switch (type) {
	case BOOL:
		return value.b ? "True" : "False";
	case INT:
		return asString<int>(value.i);
	case FLOAT:
		return asString<double>(value.d);
	case BOT:
		return "null";
	case VEC:
		{
			ostringstream oss;
			oss << "<vec>[ ";
			for (Value v : l.get())
				oss << v.toString() << ' ';
			oss << "]";
			return oss.str();
		}
	case LIST:
		{
			ostringstream oss;
			oss << "<list>[ ";
			for (Value v : l.get())
				oss << v.toString() << ' ';
			oss << "]";
			return oss.str();
		}
	case FOREIGN:
		return "<foreign>";
	default:
		throw (new impossible_error())->with(_POS);
	}
}

Value::operator int() const {
	if (type != INT)
		throw (new TypeMismatchError())->with(_POS);
	return value.i;
}

Value::operator float() const {
	if (type != FLOAT)
		throw (new TypeMismatchError())->with(_POS);
	return value.d;
}

Value::operator bool() const {
	if (type != BOOL)
		throw (new TypeMismatchError())->with(_POS);
	return value.b;
}

Value::operator Int() const {
	if (type != INT)
		throw (new TypeMismatchError())->with(_POS);
	return value.i;
}

Value::operator Float() const {
	if (type != FLOAT)
		throw (new TypeMismatchError())->with(_POS);
	return value.d;
}

Value::operator Bool() const {
	if (type != BOOL)
		throw (new TypeMismatchError())->with(_POS);
	return value.b;
}

Value::operator Foreign() const {
	if (type != FOREIGN)
		throw (new TypeMismatchError())->with(_POS);
	return value.f;
}

Value::operator Vec_Int() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	Vec_Int r;
	r.len = v.get().size();
	for (unsigned int i = 0; i < r.len; i++)
		r.data[i] = v.get()[i];
	return r;
}

Value::operator Vec_Bool() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	Vec_Bool r;
	r.len = v.get().size();
	for (unsigned int i = 0; i < r.len; i++)
		r.data[i] = v.get()[i];
	return r;
}

Value::operator Vec_Float() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	Vec_Float r;
	r.len = v.get().size();
	for (unsigned int i = 0; i < r.len; i++)
		r.data[i] = v.get()[i];
	return r;
}

Value Value::operator [](int i) const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	return v.get()[i];
}

vector<Value> Value::vec() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	return vector<Value>(v.get());
}

list<Value> Value::lst() const {
	if (type != LIST)
		throw (new TypeMismatchError())->with(_POS);
	return list<Value>(l.get());
}

double Value::asDouble() const {
	if (type == FLOAT)
		return value.d;
	else if (type == INT)
		return double(value.i);
	else throw (new TypeMismatchError())->with(_POS);
}

<commit_msg>Fixed other bug<commit_after>#include "foreign.h"
#include "interp.hh"
#include "program.hh"

#include <initializer_list>
#include <list>
#include <sstream>
#include <string>
#include <vector>
using namespace std;

Value::Value() : type(BOT) {}
Value::Value(const bool b) : type(BOOL) { value.b = b; }
Value::Value(const int i) : type(INT) { value.i = i; }
Value::Value(const float d) : type(FLOAT) { value.d = d; }
Value::Value(const Bool b) : type(BOOL) { value.b = b; }
Value::Value(const Int i) : type(INT) { value.i = i; }
Value::Value(const Float d) : type(FLOAT) { value.d = d; }
Value::Value(const Param &p) {
	switch (p.type) {
	case Param::INT:
		type = INT;
		value.i = p.value.i;
		break;
	case Param::FLOAT:
		type = FLOAT;
		value.d = p.value.d;
		break;
	case Param::STRING:
		throw (new InterpreterError())->with(_POS);
	default:
		throw (new InterpreterError())->with(_POS);
	}
}
Value::Value(const std::initializer_list <Value> &vs) : type(VEC) {
	v = vector<Value>(vs);
}
Value::Value(const vector <Value> &vs) : type(VEC), v(vs) {}
Value::Value(const list <Value> &vs) : type(LIST), l(vs) {}

Value::Value(const Foreign f) : type(FOREIGN) { value.f = f; }
Value::Value(const Vec_Int vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}
Value::Value(const Vec_Float vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}
Value::Value(const Vec_Bool vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}
Value::Value(const Vec_Foreign vi) : type(VEC) {
	auto res = vector<Value>{};
	for (unsigned int i = 0; i < vi.len; i++)
		res.push_back(vi.data[i]);
	v = res;
}

string Value::toString() const {
	switch (type) {
	case BOOL:
		return value.b ? "True" : "False";
	case INT:
		return asString<int>(value.i);
	case FLOAT:
		return asString<double>(value.d);
	case BOT:
		return "null";
	case VEC:
		{
			ostringstream oss;
			oss << "<vec>[ ";
			for (Value val : v.get())
				oss << val.toString() << ' ';
			oss << "]";
			return oss.str();
		}
	case LIST:
		{
			ostringstream oss;
			oss << "<list>[ ";
			for (Value val : l.get())
				oss << val.toString() << ' ';
			oss << "]";
			return oss.str();
		}
	case FOREIGN:
		return "<foreign>";
	default:
		throw (new impossible_error())->with(_POS);
	}
}

Value::operator int() const {
	if (type != INT)
		throw (new TypeMismatchError())->with(_POS);
	return value.i;
}

Value::operator float() const {
	if (type != FLOAT)
		throw (new TypeMismatchError())->with(_POS);
	return value.d;
}

Value::operator bool() const {
	if (type != BOOL)
		throw (new TypeMismatchError())->with(_POS);
	return value.b;
}

Value::operator Int() const {
	if (type != INT)
		throw (new TypeMismatchError())->with(_POS);
	return value.i;
}

Value::operator Float() const {
	if (type != FLOAT)
		throw (new TypeMismatchError())->with(_POS);
	return value.d;
}

Value::operator Bool() const {
	if (type != BOOL)
		throw (new TypeMismatchError())->with(_POS);
	return value.b;
}

Value::operator Foreign() const {
	if (type != FOREIGN)
		throw (new TypeMismatchError())->with(_POS);
	return value.f;
}

Value::operator Vec_Int() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	Vec_Int r;
	r.len = v.get().size();
	for (unsigned int i = 0; i < r.len; i++)
		r.data[i] = v.get()[i];
	return r;
}

Value::operator Vec_Bool() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	Vec_Bool r;
	r.len = v.get().size();
	for (unsigned int i = 0; i < r.len; i++)
		r.data[i] = v.get()[i];
	return r;
}

Value::operator Vec_Float() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	Vec_Float r;
	r.len = v.get().size();
	for (unsigned int i = 0; i < r.len; i++)
		r.data[i] = v.get()[i];
	return r;
}

Value Value::operator [](int i) const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	return v.get()[i];
}

vector<Value> Value::vec() const {
	if (type != VEC)
		throw (new TypeMismatchError())->with(_POS);
	return vector<Value>(v.get());
}

list<Value> Value::lst() const {
	if (type != LIST)
		throw (new TypeMismatchError())->with(_POS);
	return list<Value>(l.get());
}

double Value::asDouble() const {
	if (type == FLOAT)
		return value.d;
	else if (type == INT)
		return double(value.i);
	else throw (new TypeMismatchError())->with(_POS);
}

<|endoftext|>