<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/page_transition_types.h"
#include "content/public/test/browser_test_utils.h"
#include "content/test/gpu/gpu_test_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gl/gl_implementation.h"

namespace {

void SimulateGPUCrash(Browser* browser) {
  // None of the ui_test_utils entry points supports what we need to
  // do here: navigate with the PAGE_TRANSITION_FROM_ADDRESS_BAR flag,
  // without waiting for the navigation. It would be painful to change
  // either of the NavigateToURL entry points to support these two
  // constraints, so we use chrome::Navigate directly.
  chrome::NavigateParams params(
      browser,
      GURL(content::kChromeUIGpuCrashURL),
      static_cast<content::PageTransition>(
          content::PAGE_TRANSITION_TYPED |
          content::PAGE_TRANSITION_FROM_ADDRESS_BAR));
  params.disposition = NEW_BACKGROUND_TAB;
  chrome::Navigate(&params);
}

} // namespace

class WebGLInfobarTest : public InProcessBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // GPU tests require gpu acceleration.
#if !defined(OS_MACOSX)
    command_line->AppendSwitchASCII(
        switches::kUseGL, gfx::kGLImplementationOSMesaName);
#endif
  }
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    base::FilePath test_dir;
    ASSERT_TRUE(PathService::Get(content::DIR_TEST_DATA, &test_dir));
    gpu_test_dir_ = test_dir.AppendASCII("gpu");
  }
  base::FilePath gpu_test_dir_;
};

// Test cannot run on ASAN because it is intentionally crashing the gpu
// process.
#if defined(ADDRESS_SANITIZER)
#define MAYBE_ContextLossRaisesInfobar DISABLED_ContextLossRaisesInfobar
#else
#define MAYBE_ContextLossRaisesInfobar ContextLossRaisesInfobar
#endif

IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, MAYBE_ContextLossRaisesInfobar) {
  if (GPUTestBotConfig::CurrentConfigMatches("XP"))
    return;

  // Load page and wait for it to load.
  content::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      content::NotificationService::AllSources());
  ui_test_utils::NavigateToURL(
      browser(),
      content::GetFileUrlWithQuery(
          gpu_test_dir_.AppendASCII("webgl.html"), "query=kill"));
  observer.Wait();

  content::WindowedNotificationObserver infobar_added(
        chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
        content::NotificationService::AllSources());
  SimulateGPUCrash(browser());
  infobar_added.Wait();
  EXPECT_EQ(1u,
            InfoBarService::FromWebContents(
                browser()->tab_strip_model()->GetActiveWebContents())->
                    infobar_count());
}

// Test cannot run on ASAN because it is intentionally crashing the gpu
// process.
#if defined(ADDRESS_SANITIZER)
#define MAYBE_ContextLossInfobarReload DISABLED_ContextLossInfobarReload
#else
#define MAYBE_ContextLossInfobarReload ContextLossInfobarReload
#endif

IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, MAYBE_ContextLossInfobarReload) {
  if (GPUTestBotConfig::CurrentConfigMatches("XP"))
    return;

  content::DOMMessageQueue message_queue;

  // Load page and wait for it to load.
  content::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      content::NotificationService::AllSources());
  ui_test_utils::NavigateToURL(
      browser(),
      content::GetFileUrlWithQuery(
          gpu_test_dir_.AppendASCII("webgl.html"),
          "query=kill_after_notification"));
  observer.Wait();

  std::string m;
  ASSERT_TRUE(message_queue.WaitForMessage(&m));
  EXPECT_EQ("\"LOADED\"", m);

  message_queue.ClearQueue();

  content::WindowedNotificationObserver infobar_added(
        chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
        content::NotificationService::AllSources());
  SimulateGPUCrash(browser());
  infobar_added.Wait();
  InfoBarService* infobar_service = InfoBarService::FromWebContents(
      browser()->tab_strip_model()->GetActiveWebContents());
  EXPECT_EQ(1u, infobar_service->infobar_count());
  InfoBarDelegate* delegate = infobar_service->infobar_at(0);
  ASSERT_TRUE(delegate);
  ASSERT_TRUE(delegate->AsThreeDAPIInfoBarDelegate());
  delegate->AsConfirmInfoBarDelegate()->Cancel();

  // The page should reload and another message sent to the
  // DomAutomationController.
  m = "";
  ASSERT_TRUE(message_queue.WaitForMessage(&m));
  EXPECT_EQ("\"LOADED\"", m);
}

// There isn't any point in adding a test which calls Accept() on the
// ThreeDAPIInfoBarDelegate; doing so doesn't remove the infobar, and
// there's no concrete event that could be observed in response.
<commit_msg>Enable WebGLInfobarTest on ASAN<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/command_line.h"
#include "base/path_service.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/infobars/confirm_infobar_delegate.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_commands.h"
#include "chrome/browser/ui/browser_navigator.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/url_constants.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/gpu_data_manager.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/common/content_paths.h"
#include "content/public/common/page_transition_types.h"
#include "content/public/test/browser_test_utils.h"
#include "content/test/gpu/gpu_test_config.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gl/gl_implementation.h"

namespace {

void SimulateGPUCrash(Browser* browser) {
  // None of the ui_test_utils entry points supports what we need to
  // do here: navigate with the PAGE_TRANSITION_FROM_ADDRESS_BAR flag,
  // without waiting for the navigation. It would be painful to change
  // either of the NavigateToURL entry points to support these two
  // constraints, so we use chrome::Navigate directly.
  chrome::NavigateParams params(
      browser,
      GURL(content::kChromeUIGpuCrashURL),
      static_cast<content::PageTransition>(
          content::PAGE_TRANSITION_TYPED |
          content::PAGE_TRANSITION_FROM_ADDRESS_BAR));
  params.disposition = NEW_BACKGROUND_TAB;
  chrome::Navigate(&params);
}

} // namespace

class WebGLInfobarTest : public InProcessBrowserTest {
 protected:
  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
    // GPU tests require gpu acceleration.
#if !defined(OS_MACOSX)
    command_line->AppendSwitchASCII(
        switches::kUseGL, gfx::kGLImplementationOSMesaName);
#endif
  }
  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
    base::FilePath test_dir;
    ASSERT_TRUE(PathService::Get(content::DIR_TEST_DATA, &test_dir));
    gpu_test_dir_ = test_dir.AppendASCII("gpu");
  }
  base::FilePath gpu_test_dir_;
};

IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, ContextLossRaisesInfobar) {
  if (GPUTestBotConfig::CurrentConfigMatches("XP"))
    return;

  // Load page and wait for it to load.
  content::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      content::NotificationService::AllSources());
  ui_test_utils::NavigateToURL(
      browser(),
      content::GetFileUrlWithQuery(
          gpu_test_dir_.AppendASCII("webgl.html"), "query=kill"));
  observer.Wait();

  content::WindowedNotificationObserver infobar_added(
        chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
        content::NotificationService::AllSources());
  SimulateGPUCrash(browser());
  infobar_added.Wait();
  EXPECT_EQ(1u,
            InfoBarService::FromWebContents(
                browser()->tab_strip_model()->GetActiveWebContents())->
                    infobar_count());
}

IN_PROC_BROWSER_TEST_F(WebGLInfobarTest, ContextLossInfobarReload) {
  if (GPUTestBotConfig::CurrentConfigMatches("XP"))
    return;

  content::DOMMessageQueue message_queue;

  // Load page and wait for it to load.
  content::WindowedNotificationObserver observer(
      content::NOTIFICATION_LOAD_STOP,
      content::NotificationService::AllSources());
  ui_test_utils::NavigateToURL(
      browser(),
      content::GetFileUrlWithQuery(
          gpu_test_dir_.AppendASCII("webgl.html"),
          "query=kill_after_notification"));
  observer.Wait();

  std::string m;
  ASSERT_TRUE(message_queue.WaitForMessage(&m));
  EXPECT_EQ("\"LOADED\"", m);

  message_queue.ClearQueue();

  content::WindowedNotificationObserver infobar_added(
        chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
        content::NotificationService::AllSources());
  SimulateGPUCrash(browser());
  infobar_added.Wait();
  InfoBarService* infobar_service = InfoBarService::FromWebContents(
      browser()->tab_strip_model()->GetActiveWebContents());
  EXPECT_EQ(1u, infobar_service->infobar_count());
  InfoBarDelegate* delegate = infobar_service->infobar_at(0);
  ASSERT_TRUE(delegate);
  ASSERT_TRUE(delegate->AsThreeDAPIInfoBarDelegate());
  delegate->AsConfirmInfoBarDelegate()->Cancel();

  // The page should reload and another message sent to the
  // DomAutomationController.
  m = "";
  ASSERT_TRUE(message_queue.WaitForMessage(&m));
  EXPECT_EQ("\"LOADED\"", m);
}

// There isn't any point in adding a test which calls Accept() on the
// ThreeDAPIInfoBarDelegate; doing so doesn't remove the infobar, and
// there's no concrete event that could be observed in response.
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ASTNodeEraser.h"

#include "clang/AST/Decl.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DependentDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

using namespace clang;

namespace cling {

  ///\brief The class does the actual work of removing a declaration and
  /// resetting the internal structures of the compiler
  ///
  class DeclReverter : public DeclVisitor<DeclReverter, bool> {
  private:
    Sema* m_Sema;

  public:
    DeclReverter(Sema* S): m_Sema(S) {}

    ///\brief Function that contains common actions, done for every removal of
    /// declaration.
    ///
    /// For example: We must uncache the cached include, which brought that
    /// declaration in the AST.
    ///\param[in] D - A declaration.
    ///
    void PreVisitDecl(Decl* D);

    ///\brief If it falls back in the base class just remove the declaration
    /// only from the declaration context.
    /// @param[in] D - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitDecl(Decl* D);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context.
    /// @param[in] ND - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamedDecl(NamedDecl* ND);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] VD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitVarDecl(VarDecl* VD);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] FD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitFunctionDecl(FunctionDecl* FD);

    ///\brief Removes the enumerator and its enumerator constants.
    /// @param[in] ED - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitEnumDecl(EnumDecl* ED);

    ///\brief Removes the namespace.
    /// @param[in] NSD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamespaceDecl(NamespaceDecl* NSD);

    /// @name Helpers
    /// @{

    ///\brief Checks whether the declaration was pushed onto the declaration
    /// chains. Returns
    /// @param[in] ND - The declaration that is being checked
    ///
    ///\returns true if the ND was found in the lookup chain.
    ///
    bool isOnScopeChains(clang::NamedDecl* ND);

    ///\brief Removes given declaration from the chain of redeclarations.
    /// Rebuilds the chain and sets properly first and last redeclaration.
    /// @param[in] R - The redeclarable, its chain to be rebuilt
    ///
    ///\returns the most recent redeclaration in the new chain.
    ///
    template <typename T>
    T* RemoveFromRedeclChain(clang::Redeclarable<T>* R) {
      llvm::SmallVector<T*, 4> PrevDecls;
      T* PrevDecl = 0;

      // [0]=>C [1]=>B [2]=>A ...
      while ((PrevDecl = R->getPreviousDecl())) {
        PrevDecls.push_back(PrevDecl);
        R = PrevDecl;
      }

      if (!PrevDecls.empty()) {
        // Put 0 in the end of the array so that the loop will reset the
        // pointer to latest redeclaration in the chain to itself.
        //
        PrevDecls.push_back(0);

        // 0 <- A <- B <- C
        for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {
          PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);
        }
      }

      return PrevDecls.empty() ? 0 : PrevDecls[0]->getMostRecentDecl();
    }

    /// @}
  };

  void DeclReverter::PreVisitDecl(Decl *D) {
    SourceLocation Loc = D->getLocStart();
    SourceManager& SM = m_Sema->getSourceManager();
    FileManager& FM = SM.getFileManager();
    const FileEntry* OldEntry = SM.getFileEntryForID(SM.getFileID(Loc));
    //const FileEntry* NewEntry
    //  = FM.getFile(OldEntry->getName(), /*openFile*/ true);
    //std::string errStr = "";
    // SM.overrideFileContents(OldEntry, FM.getBufferForFile(NewEntry, &errStr));
  }

  // Gives us access to the protected members that we  need.
  class DeclContextExt : public DeclContext {
  public:
    static bool removeIfLast(DeclContext* DC, Decl* D) {
      if (!D->getNextDeclInContext()) {
        // Either last (remove!), or invalid (nothing to remove)
        if (((DeclContextExt*)DC)->LastDecl == D) {
          // Valid. Thus remove.
          DC->removeDecl(D);
          return true;
        }
      }
      else {
        DC->removeDecl(D);
        return true;
      }

      return false;
    }
  };

  bool DeclReverter::VisitDecl(Decl* D) {
    assert(D && "The Decl is null");
    PreVisitDecl(D);

    DeclContext* DC = D->getDeclContext();

    bool ExistsInDC = false;

    for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
         E !=I; ++I) {
      if (*I == D) {
        ExistsInDC = true;
        break;
      }
    }

    bool Successful = DeclContextExt::removeIfLast(DC, D);

    // ExistsInDC && Successful
    // true          false      -> false // In the context but cannot delete
    // false         false      -> true  // Not in the context cannot delete
    // true          true       -> true  // In the context and can delete
    // false         true       -> assert // Not in the context but can delete ?
    assert(!(!ExistsInDC && Successful) && "Not in the context but can delete?!");
    if (ExistsInDC && !Successful)
      return false;
    else // in release we'd want the assert to fall into true
      return true;
  }

  bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {
    bool Successful = VisitDecl(ND);

    DeclContext* DC = ND->getDeclContext();

    // If the decl was removed make sure that we fix the lookup
    if (Successful) {
      Scope* S = m_Sema->getScopeForContext(DC);
      if (S)
        S->RemoveDecl(ND);

      if (isOnScopeChains(ND))
        m_Sema->IdResolver.RemoveDecl(ND);

      return true;
    }

    return false;
  }

  bool DeclReverter::VisitVarDecl(VarDecl* VD) {
    bool Successful = VisitNamedDecl(VD);

    DeclContext* DC = VD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(VD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      // We need to rewire the list of the redeclarations in order to exclude
      // the reverted one, because it gets found for example by
      // Sema::MergeVarDecl and ends up in the lookup
      //
      if (VarDecl* MostRecentVD = RemoveFromRedeclChain(VD)) {

        Pos->second.setOnlyValue(MostRecentVD);
        if (S)
          S->AddDecl(MostRecentVD);
        m_Sema->IdResolver.AddDecl(MostRecentVD);
      }

    return Successful;
  }

  bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {
    bool Successful = true;

    DeclContext* DC = FD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Template instantiation of templated function first creates a canonical
    // declaration and after the actual template specialization. For example:
    // template<typename T> T TemplatedF(T t);
    // template<> int TemplatedF(int i) { return i + 1; } creates:
    // 1. Canonical decl: int TemplatedF(int i);
    // 2. int TemplatedF(int i){ return i + 1; }
    //
    // The template specialization is attached to the list of specialization of
    // the templated function.
    // When TemplatedF is looked up it finds the templated function and the
    // lookup is extended by the templated function with its specializations.
    // In the end we don't need to remove the canonical decl because, it
    // doesn't end up in the lookup table.
    //
    class FunctionTemplateDeclExt : public FunctionTemplateDecl {
    public:
      static llvm::FoldingSet<FunctionTemplateSpecializationInfo>&
      getSpecializationsExt(FunctionTemplateDecl* FTD) {
        assert(FTD && "Cannot be null!");
        return ((FunctionTemplateDeclExt*) FTD)->getSpecializations();
      }
    };

    if (FD->isFunctionTemplateSpecialization()) {
      // 1. Remove the canonical decl.
      // TODO: Can the cannonical has another DeclContext and Scope, different
      // from the specialization's implementation?
      FunctionDecl* CanFD = FD->getCanonicalDecl();
      FunctionTemplateDecl* FTD
        = FD->getTemplateSpecializationInfo()->getTemplate();
      llvm::FoldingSet<FunctionTemplateSpecializationInfo> &FS
        = FunctionTemplateDeclExt::getSpecializationsExt(FTD);
      FS.RemoveNode(CanFD->getTemplateSpecializationInfo());
    }

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(FD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.getAsDecl()) {
      Successful = VisitNamedDecl(FD) && Successful;

      Pos = Map->find(FD->getDeclName());
      assert(Pos != Map->end() && "no lookup entry for decl");

      if (Pos->second.isNull()) {
        // When we have template specialization we have to clean up
        if (FD->isFunctionTemplateSpecialization()) {
          while ((FD = FD->getPreviousDecl())) {
            Successful = VisitNamedDecl(FD) && Successful;
          }
          return true;
        }

        // We need to rewire the list of the redeclarations in order to exclude
        // the reverted one, because it gets found for example by
        // Sema::MergeVarDecl and ends up in the lookup
        //
        if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
          Pos->second.setOnlyValue(MostRecentFD);
          if (S)
            S->AddDecl(MostRecentFD);
          m_Sema->IdResolver.AddDecl(MostRecentFD);
        }
      }
    }
    else if (llvm::SmallVector<NamedDecl*, 4>* Decls
             = Pos->second.getAsVector()) {
      for(llvm::SmallVector<NamedDecl*, 4>::iterator I = Decls->begin();
          I != Decls->end(); ++I) {
        if ((*I) == FD) {
          if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
            Successful = VisitNamedDecl(*I) && Successful;
            Decls->insert(I, MostRecentFD);
          }
          else
            Decls->erase(I);
        }
      }
    }

    return Successful;
  }

  bool DeclReverter::VisitEnumDecl(EnumDecl* ED) {
    bool Successful = true;

    for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
           E = ED->enumerator_end(); I != E; ++I) {
      assert((*I)->getDeclName() && "EnumConstantDecl with no name?");
      Successful = VisitNamedDecl(*I) && Successful;
    }

    Successful = VisitNamedDecl(ED) && Successful;

    return Successful;
  }

  bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {
    bool Successful = VisitNamedDecl(NSD);

    //DeclContext* DC = NSD->getPrimaryContext();
    DeclContext* DC = NSD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      if (NSD != NSD->getOriginalNamespace()) {
        NamespaceDecl* NewNSD = NSD->getOriginalNamespace();
        Pos->second.setOnlyValue(NewNSD);
        if (S)
          S->AddDecl(NewNSD);
        m_Sema->IdResolver.AddDecl(NewNSD);
      }

    return Successful;
  }

  // See Sema::PushOnScopeChains
  bool DeclReverter::isOnScopeChains(NamedDecl* ND) {

    // Named decls without name shouldn't be in. Eg: struct {int a};
    if (!ND->getDeclName())
      return false;

    // Out-of-line definitions shouldn't be pushed into scope in C++.
    // Out-of-line variable and function definitions shouldn't even in C.
    if ((isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) && ND->isOutOfLine() &&
        !ND->getDeclContext()->getRedeclContext()->Equals(
                        ND->getLexicalDeclContext()->getRedeclContext()))
      return false;

    // Template instantiations should also not be pushed into scope.
    if (isa<FunctionDecl>(ND) &&
        cast<FunctionDecl>(ND)->isFunctionTemplateSpecialization())
      return false;

    IdentifierResolver::iterator
      IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),
      IDRiEnd = m_Sema->IdResolver.end();

    for (; IDRi != IDRiEnd; ++IDRi) {
      if (ND == *IDRi)
        return true;
    }

    // Check if the declaration is template instantiation, which is not in
    // any DeclContext yet, because it came from
    // Sema::PerformPendingInstantiations
    // if (isa<FunctionDecl>(D) &&
    //     cast<FunctionDecl>(D)->getTemplateInstantiationPattern())
    //   return false;ye

    return false;
  }

  ASTNodeEraser::ASTNodeEraser(Sema* S) : m_Sema(S) {
    m_DeclReverter = new DeclReverter(S);
  }

  ASTNodeEraser::~ASTNodeEraser() {
    delete m_DeclReverter;
    m_DeclReverter = 0;
  }

  bool ASTNodeEraser::RevertDecl(Decl* D) {
    return m_DeclReverter->Visit(D);
  }

} // end namespace cling
<commit_msg>Comment out the method. It was checked in by accident and caused an warning.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ASTNodeEraser.h"

#include "clang/AST/Decl.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DependentDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

using namespace clang;

namespace cling {

  ///\brief The class does the actual work of removing a declaration and
  /// resetting the internal structures of the compiler
  ///
  class DeclReverter : public DeclVisitor<DeclReverter, bool> {
  private:
    Sema* m_Sema;

  public:
    DeclReverter(Sema* S): m_Sema(S) {}

    ///\brief Function that contains common actions, done for every removal of
    /// declaration.
    ///
    /// For example: We must uncache the cached include, which brought that
    /// declaration in the AST.
    ///\param[in] D - A declaration.
    ///
    void PreVisitDecl(Decl* D);

    ///\brief If it falls back in the base class just remove the declaration
    /// only from the declaration context.
    /// @param[in] D - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitDecl(Decl* D);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context.
    /// @param[in] ND - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamedDecl(NamedDecl* ND);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] VD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitVarDecl(VarDecl* VD);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] FD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitFunctionDecl(FunctionDecl* FD);

    ///\brief Removes the enumerator and its enumerator constants.
    /// @param[in] ED - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitEnumDecl(EnumDecl* ED);

    ///\brief Removes the namespace.
    /// @param[in] NSD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamespaceDecl(NamespaceDecl* NSD);

    /// @name Helpers
    /// @{

    ///\brief Checks whether the declaration was pushed onto the declaration
    /// chains. Returns
    /// @param[in] ND - The declaration that is being checked
    ///
    ///\returns true if the ND was found in the lookup chain.
    ///
    bool isOnScopeChains(clang::NamedDecl* ND);

    ///\brief Removes given declaration from the chain of redeclarations.
    /// Rebuilds the chain and sets properly first and last redeclaration.
    /// @param[in] R - The redeclarable, its chain to be rebuilt
    ///
    ///\returns the most recent redeclaration in the new chain.
    ///
    template <typename T>
    T* RemoveFromRedeclChain(clang::Redeclarable<T>* R) {
      llvm::SmallVector<T*, 4> PrevDecls;
      T* PrevDecl = 0;

      // [0]=>C [1]=>B [2]=>A ...
      while ((PrevDecl = R->getPreviousDecl())) {
        PrevDecls.push_back(PrevDecl);
        R = PrevDecl;
      }

      if (!PrevDecls.empty()) {
        // Put 0 in the end of the array so that the loop will reset the
        // pointer to latest redeclaration in the chain to itself.
        //
        PrevDecls.push_back(0);

        // 0 <- A <- B <- C
        for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {
          PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);
        }
      }

      return PrevDecls.empty() ? 0 : PrevDecls[0]->getMostRecentDecl();
    }

    /// @}
  };

  void DeclReverter::PreVisitDecl(Decl *D) {
    //SourceLocation Loc = D->getLocStart();
    //SourceManager& SM = m_Sema->getSourceManager();
    //FileManager& FM = SM.getFileManager();
    //const FileEntry* OldEntry = SM.getFileEntryForID(SM.getFileID(Loc));
    //const FileEntry* NewEntry
    //  = FM.getFile(OldEntry->getName(), /*openFile*/ true);
    //std::string errStr = "";
    // SM.overrideFileContents(OldEntry, FM.getBufferForFile(NewEntry, &errStr));
  }

  // Gives us access to the protected members that we  need.
  class DeclContextExt : public DeclContext {
  public:
    static bool removeIfLast(DeclContext* DC, Decl* D) {
      if (!D->getNextDeclInContext()) {
        // Either last (remove!), or invalid (nothing to remove)
        if (((DeclContextExt*)DC)->LastDecl == D) {
          // Valid. Thus remove.
          DC->removeDecl(D);
          return true;
        }
      }
      else {
        DC->removeDecl(D);
        return true;
      }

      return false;
    }
  };

  bool DeclReverter::VisitDecl(Decl* D) {
    assert(D && "The Decl is null");
    PreVisitDecl(D);

    DeclContext* DC = D->getDeclContext();

    bool ExistsInDC = false;

    for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
         E !=I; ++I) {
      if (*I == D) {
        ExistsInDC = true;
        break;
      }
    }

    bool Successful = DeclContextExt::removeIfLast(DC, D);

    // ExistsInDC && Successful
    // true          false      -> false // In the context but cannot delete
    // false         false      -> true  // Not in the context cannot delete
    // true          true       -> true  // In the context and can delete
    // false         true       -> assert // Not in the context but can delete ?
    assert(!(!ExistsInDC && Successful) && "Not in the context but can delete?!");
    if (ExistsInDC && !Successful)
      return false;
    else // in release we'd want the assert to fall into true
      return true;
  }

  bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {
    bool Successful = VisitDecl(ND);

    DeclContext* DC = ND->getDeclContext();

    // If the decl was removed make sure that we fix the lookup
    if (Successful) {
      Scope* S = m_Sema->getScopeForContext(DC);
      if (S)
        S->RemoveDecl(ND);

      if (isOnScopeChains(ND))
        m_Sema->IdResolver.RemoveDecl(ND);

      return true;
    }

    return false;
  }

  bool DeclReverter::VisitVarDecl(VarDecl* VD) {
    bool Successful = VisitNamedDecl(VD);

    DeclContext* DC = VD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(VD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      // We need to rewire the list of the redeclarations in order to exclude
      // the reverted one, because it gets found for example by
      // Sema::MergeVarDecl and ends up in the lookup
      //
      if (VarDecl* MostRecentVD = RemoveFromRedeclChain(VD)) {

        Pos->second.setOnlyValue(MostRecentVD);
        if (S)
          S->AddDecl(MostRecentVD);
        m_Sema->IdResolver.AddDecl(MostRecentVD);
      }

    return Successful;
  }

  bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {
    bool Successful = true;

    DeclContext* DC = FD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Template instantiation of templated function first creates a canonical
    // declaration and after the actual template specialization. For example:
    // template<typename T> T TemplatedF(T t);
    // template<> int TemplatedF(int i) { return i + 1; } creates:
    // 1. Canonical decl: int TemplatedF(int i);
    // 2. int TemplatedF(int i){ return i + 1; }
    //
    // The template specialization is attached to the list of specialization of
    // the templated function.
    // When TemplatedF is looked up it finds the templated function and the
    // lookup is extended by the templated function with its specializations.
    // In the end we don't need to remove the canonical decl because, it
    // doesn't end up in the lookup table.
    //
    class FunctionTemplateDeclExt : public FunctionTemplateDecl {
    public:
      static llvm::FoldingSet<FunctionTemplateSpecializationInfo>&
      getSpecializationsExt(FunctionTemplateDecl* FTD) {
        assert(FTD && "Cannot be null!");
        return ((FunctionTemplateDeclExt*) FTD)->getSpecializations();
      }
    };

    if (FD->isFunctionTemplateSpecialization()) {
      // 1. Remove the canonical decl.
      // TODO: Can the cannonical has another DeclContext and Scope, different
      // from the specialization's implementation?
      FunctionDecl* CanFD = FD->getCanonicalDecl();
      FunctionTemplateDecl* FTD
        = FD->getTemplateSpecializationInfo()->getTemplate();
      llvm::FoldingSet<FunctionTemplateSpecializationInfo> &FS
        = FunctionTemplateDeclExt::getSpecializationsExt(FTD);
      FS.RemoveNode(CanFD->getTemplateSpecializationInfo());
    }

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(FD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.getAsDecl()) {
      Successful = VisitNamedDecl(FD) && Successful;

      Pos = Map->find(FD->getDeclName());
      assert(Pos != Map->end() && "no lookup entry for decl");

      if (Pos->second.isNull()) {
        // When we have template specialization we have to clean up
        if (FD->isFunctionTemplateSpecialization()) {
          while ((FD = FD->getPreviousDecl())) {
            Successful = VisitNamedDecl(FD) && Successful;
          }
          return true;
        }

        // We need to rewire the list of the redeclarations in order to exclude
        // the reverted one, because it gets found for example by
        // Sema::MergeVarDecl and ends up in the lookup
        //
        if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
          Pos->second.setOnlyValue(MostRecentFD);
          if (S)
            S->AddDecl(MostRecentFD);
          m_Sema->IdResolver.AddDecl(MostRecentFD);
        }
      }
    }
    else if (llvm::SmallVector<NamedDecl*, 4>* Decls
             = Pos->second.getAsVector()) {
      for(llvm::SmallVector<NamedDecl*, 4>::iterator I = Decls->begin();
          I != Decls->end(); ++I) {
        if ((*I) == FD) {
          if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
            Successful = VisitNamedDecl(*I) && Successful;
            Decls->insert(I, MostRecentFD);
          }
          else
            Decls->erase(I);
        }
      }
    }

    return Successful;
  }

  bool DeclReverter::VisitEnumDecl(EnumDecl* ED) {
    bool Successful = true;

    for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
           E = ED->enumerator_end(); I != E; ++I) {
      assert((*I)->getDeclName() && "EnumConstantDecl with no name?");
      Successful = VisitNamedDecl(*I) && Successful;
    }

    Successful = VisitNamedDecl(ED) && Successful;

    return Successful;
  }

  bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {
    bool Successful = VisitNamedDecl(NSD);

    //DeclContext* DC = NSD->getPrimaryContext();
    DeclContext* DC = NSD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      if (NSD != NSD->getOriginalNamespace()) {
        NamespaceDecl* NewNSD = NSD->getOriginalNamespace();
        Pos->second.setOnlyValue(NewNSD);
        if (S)
          S->AddDecl(NewNSD);
        m_Sema->IdResolver.AddDecl(NewNSD);
      }

    return Successful;
  }

  // See Sema::PushOnScopeChains
  bool DeclReverter::isOnScopeChains(NamedDecl* ND) {

    // Named decls without name shouldn't be in. Eg: struct {int a};
    if (!ND->getDeclName())
      return false;

    // Out-of-line definitions shouldn't be pushed into scope in C++.
    // Out-of-line variable and function definitions shouldn't even in C.
    if ((isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) && ND->isOutOfLine() &&
        !ND->getDeclContext()->getRedeclContext()->Equals(
                        ND->getLexicalDeclContext()->getRedeclContext()))
      return false;

    // Template instantiations should also not be pushed into scope.
    if (isa<FunctionDecl>(ND) &&
        cast<FunctionDecl>(ND)->isFunctionTemplateSpecialization())
      return false;

    IdentifierResolver::iterator
      IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),
      IDRiEnd = m_Sema->IdResolver.end();

    for (; IDRi != IDRiEnd; ++IDRi) {
      if (ND == *IDRi)
        return true;
    }

    // Check if the declaration is template instantiation, which is not in
    // any DeclContext yet, because it came from
    // Sema::PerformPendingInstantiations
    // if (isa<FunctionDecl>(D) &&
    //     cast<FunctionDecl>(D)->getTemplateInstantiationPattern())
    //   return false;ye

    return false;
  }

  ASTNodeEraser::ASTNodeEraser(Sema* S) : m_Sema(S) {
    m_DeclReverter = new DeclReverter(S);
  }

  ASTNodeEraser::~ASTNodeEraser() {
    delete m_DeclReverter;
    m_DeclReverter = 0;
  }

  bool ASTNodeEraser::RevertDecl(Decl* D) {
    return m_DeclReverter->Visit(D);
  }

} // end namespace cling
<|endoftext|>


<commit_before>#ifndef AREAMANAGER_HPP
#define AREAMANAGER_HPP

#include <thread>
#include <vector>

#include "Area.hpp"

/* Manage Areas and delete them after a none use time */

namespace map
{

    template <class T>
    class AreaManager
    {
        public:
            AreaManager(const float sec_timeout);
            ~AreaManager();

            AreaManager(const AreaManager&) = delete;
            AreaManager& operator=(const AreaManager&) = delete;

            void add(Area<T*> area);
            void remove(Area<T*> area);

            void run();
            inline void stop(){running=false;};

        private:
            std::vector<Area<T>*> areas;
            std::mutex mutex;
            std::thread thread;

            const float timeout;

            volatile bool running;
    };

};

#include "AreaManager.tpl"

#endif
<commit_msg>commit bug code, but go to sleep<commit_after>#ifndef AREAMANAGER_HPP
#define AREAMANAGER_HPP

#include <thread>
#include <vector>

#include "Area.hpp"

/* Manage Areas and delete them after a none use time */

namespace map
{

    template <class T>
    class AreaManager
    {
        public:
            AreaManager(const float sec_timeout);
            ~AreaManager();

            AreaManager(const AreaManager&) = delete;
            AreaManager& operator=(const AreaManager&) = delete;

            void add(Area<T*> area);
            void remove(Area<T*> area);

            void run();
            inline void stop(){running=false;};

        private:
            std::vector<Area<T>*> areas;
            std::mutex mutex;
            std::thread thread;

            const sf::Time timeout;

            volatile bool running;
    };

};

#include "AreaManager.tpl"

#endif
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName			:    NFCActorModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCActorModule
//
// -------------------------------------------------------------------------

#include "NFCActorModule.h"
#include "NFComm/NFCore/NFIComponent.h"

NFCActorModule::NFCActorModule(NFIPluginManager* p)
{
	pPluginManager = p;

    srand((unsigned)time(NULL));

    m_pFramework = NF_NEW Theron::Framework(NF_ACTOR_THREAD_COUNT);

    m_pMainActor = NF_SHARE_PTR<NFIActor>(NF_NEW NFCActor(*m_pFramework, this));
}

NFCActorModule::~NFCActorModule()
{
    m_pMainActor.reset();
    m_pMainActor = nullptr;

    delete m_pFramework;
    m_pFramework = NULL;
}

bool NFCActorModule::Init()
{

    return true;
}

bool NFCActorModule::AfterInit()
{

    return true;
}

bool NFCActorModule::BeforeShut()
{
	mxActorMap.ClearAll();
    return true;
}

bool NFCActorModule::Shut()
{

    return true;
}

bool NFCActorModule::Execute()
{
	ExecuteEvent();
    return true;
}

int NFCActorModule::RequireActor()
{

    NF_SHARE_PTR<NFIActor> pActor(NF_NEW NFCActor(*m_pFramework, this));
	mxActorMap.AddElement(pActor->GetAddress().AsInteger(), pActor);

    return pActor->GetAddress().AsInteger();
}

NF_SHARE_PTR<NFIActor> NFCActorModule::GetActor(const int nActorIndex)
{
	return mxActorMap.GetElement(nActorIndex);
}

bool NFCActorModule::HandlerEx(const NFIActorMessage & message, const int from)
{
	mxQueue.Push(message);
	return true;
}

bool NFCActorModule::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (xMsg.nMsgID == 0)
		{
			xMsg.xEndFuncptr->operator()(xMsg.self, xMsg.nFormActor, xMsg.nMsgID, xMsg.data);
			//Actor can be reused in ActorPool mode, so we don't release it.
			//m_pActorManager->ReleaseActor(xMsg.nFormActor);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}

bool NFCActorModule::SendMsgToActor(const int nActorIndex, const NFGUID& objectID, const int nEventID, const std::string& strArg)
{
    NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
    if (nullptr != pActor)
    {
        NFIActorMessage xMessage;

		xMessage.bComponentMsg = true;
        xMessage.data = strArg;
        xMessage.nMsgID = nEventID;
        xMessage.nFormActor = m_pMainActor->GetAddress().AsInteger();
        xMessage.self = objectID;

        return m_pFramework->Send(xMessage, m_pMainActor->GetAddress(), pActor->GetAddress());
    }

    return false;
}

bool NFCActorModule::AddComponent(const int nActorIndex, NF_SHARE_PTR<NFIComponent> pComponent)
{
    NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
    if (nullptr != pActor)
    {
        pActor->AddComponent(pComponent);

        return true;
    }

    return false;
}

bool NFCActorModule::ReleaseActor(const int nActorIndex)
{
	return mxActorMap.RemoveElement(nActorIndex);
}

bool NFCActorModule::AddEndFunc(const int nActorIndex, EVENT_ASYNC_PROCESS_END_FUNCTOR_PTR functorPtr_end)
{
    NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
    if (nullptr != pActor)
    {
        pActor->AddEndFunc(functorPtr_end);

        return true;
    }

    return false;
}<commit_msg>fixed for actor module--can not reset message's id when return message to the main thread<commit_after>// -------------------------------------------------------------------------
//    @FileName			:    NFCActorModule.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :    2012-12-15
//    @Module           :    NFCActorModule
//
// -------------------------------------------------------------------------

#include "NFCActorModule.h"
#include "NFComm/NFCore/NFIComponent.h"

NFCActorModule::NFCActorModule(NFIPluginManager* p)
{
	pPluginManager = p;

    srand((unsigned)time(NULL));

    m_pFramework = NF_NEW Theron::Framework(NF_ACTOR_THREAD_COUNT);

    m_pMainActor = NF_SHARE_PTR<NFIActor>(NF_NEW NFCActor(*m_pFramework, this));
}

NFCActorModule::~NFCActorModule()
{
    m_pMainActor.reset();
    m_pMainActor = nullptr;

    delete m_pFramework;
    m_pFramework = NULL;
}

bool NFCActorModule::Init()
{

    return true;
}

bool NFCActorModule::AfterInit()
{

    return true;
}

bool NFCActorModule::BeforeShut()
{
	mxActorMap.ClearAll();
    return true;
}

bool NFCActorModule::Shut()
{

    return true;
}

bool NFCActorModule::Execute()
{
	ExecuteEvent();
    return true;
}

int NFCActorModule::RequireActor()
{

    NF_SHARE_PTR<NFIActor> pActor(NF_NEW NFCActor(*m_pFramework, this));
	mxActorMap.AddElement(pActor->GetAddress().AsInteger(), pActor);

    return pActor->GetAddress().AsInteger();
}

NF_SHARE_PTR<NFIActor> NFCActorModule::GetActor(const int nActorIndex)
{
	return mxActorMap.GetElement(nActorIndex);
}

bool NFCActorModule::HandlerEx(const NFIActorMessage & message, const int from)
{
	if (!message.bComponentMsg)
	{
		return mxQueue.Push(message);
	}

	return false;
}

bool NFCActorModule::ExecuteEvent()
{
	NFIActorMessage xMsg;
	bool bRet = false;
	bRet = mxQueue.Pop(xMsg);
	while (bRet)
	{
		if (!xMsg.bComponentMsg)
		{
			xMsg.xEndFuncptr->operator()(xMsg.self, xMsg.nFormActor, xMsg.nMsgID, xMsg.data);
			//Actor can be reused in ActorPool mode, so we don't release it.
			//m_pActorManager->ReleaseActor(xMsg.nFormActor);
		}

		bRet = mxQueue.Pop(xMsg);
	}

	return true;
}

bool NFCActorModule::SendMsgToActor(const int nActorIndex, const NFGUID& objectID, const int nEventID, const std::string& strArg)
{
    NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
    if (nullptr != pActor)
    {
        NFIActorMessage xMessage;

		xMessage.bComponentMsg = true;
        xMessage.data = strArg;
        xMessage.nMsgID = nEventID;
        xMessage.nFormActor = m_pMainActor->GetAddress().AsInteger();
        xMessage.self = objectID;

        return m_pFramework->Send(xMessage, m_pMainActor->GetAddress(), pActor->GetAddress());
    }

    return false;
}

bool NFCActorModule::AddComponent(const int nActorIndex, NF_SHARE_PTR<NFIComponent> pComponent)
{
    NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
    if (nullptr != pActor)
    {
        pActor->AddComponent(pComponent);

        return true;
    }

    return false;
}

bool NFCActorModule::ReleaseActor(const int nActorIndex)
{
	return mxActorMap.RemoveElement(nActorIndex);
}

bool NFCActorModule::AddEndFunc(const int nActorIndex, EVENT_ASYNC_PROCESS_END_FUNCTOR_PTR functorPtr_end)
{
    NF_SHARE_PTR<NFIActor> pActor = GetActor(nActorIndex);
    if (nullptr != pActor)
    {
        pActor->AddEndFunc(functorPtr_end);

        return true;
    }

    return false;
}<|endoftext|>


<commit_before>#include "Compression.h"

#include "components/debug/Debug.h"
#include "components/utilities/Bytes.h"

void Compression::decodeRLE(const uint8_t *src, int stopCount, uint8_t *dst, int dstSize)
{
	// Adapted from WinArena.
	int i = 0;
	int o = 0;

	while (o < stopCount)
	{
		const uint8_t sample = src[i];
		src++;

		// Is the selected byte part of a compressed packet?
		if ((sample & 0x80) != 0)
		{
			const uint8_t value = src[i];
			src++;

			const uint32_t count = static_cast<uint32_t>(sample) - 0x7F;

			DebugAssert(o >= 0);
			DebugAssert((o + count) <= dstSize);
			for (uint32_t j = 0; j < count; j++)
			{
				dst[o] = value;
				o++;
			}
		}
		else
		{
			const uint32_t count = static_cast<uint32_t>(sample) + 1;

			DebugAssert(o >= 0);
			DebugAssert((o + count) <= dstSize);
			for (uint32_t j = 0; j < count; j++)
			{
				dst[o] = src[i];
				o++;
				i++;
			}
		}
	}
}

void Compression::decodeRLEWords(const uint8_t *src, int stopCount,
	std::vector<uint8_t> &out)
{
	int i = 0;
	int o = 0;

	while (o < stopCount)
	{
		const int16_t sample = Bytes::getLE16(src + i);
		i += 2;

		// If "sample" is positive, then "sample" literal words follow. Otherwise,
		// repeat the next word "sample" times.
		if (sample > 0)
		{
			for (int16_t j = 0; j < sample; j++)
			{
				const uint16_t value = Bytes::getLE16(src + i);
				i += 2;

				out.at(o * 2) = value & 0x00FF;
				out.at((o * 2) + 1) = (value & 0xFF00) >> 8;
				o++;
			}
		}
		else
		{
			const uint16_t value = Bytes::getLE16(src + i);
			i += 2;

			const uint16_t count = -sample;

			for (uint16_t j = 0; j < count; j++)
			{
				out.at(o * 2) = value & 0x00FF;
				out.at((o * 2) + 1) = (value & 0xFF00) >> 8;
				o++;
			}
		}
	}
}
<commit_msg>Fixed signed/unsigned warning.<commit_after>#include "Compression.h"

#include "components/debug/Debug.h"
#include "components/utilities/Bytes.h"

void Compression::decodeRLE(const uint8_t *src, int stopCount, uint8_t *dst, int dstSize)
{
	// Adapted from WinArena.
	int i = 0;
	int o = 0;

	while (o < stopCount)
	{
		const uint8_t sample = src[i];
		src++;

		// Is the selected byte part of a compressed packet?
		if ((sample & 0x80) != 0)
		{
			const uint8_t value = src[i];
			src++;

			const uint32_t count = static_cast<uint32_t>(sample) - 0x7F;

			DebugAssert(o >= 0);
			DebugAssert((o + static_cast<int>(count)) <= dstSize);
			for (uint32_t j = 0; j < count; j++)
			{
				dst[o] = value;
				o++;
			}
		}
		else
		{
			const uint32_t count = static_cast<uint32_t>(sample) + 1;

			DebugAssert(o >= 0);
			DebugAssert((o + static_cast<int>(count)) <= dstSize);
			for (uint32_t j = 0; j < count; j++)
			{
				dst[o] = src[i];
				o++;
				i++;
			}
		}
	}
}

void Compression::decodeRLEWords(const uint8_t *src, int stopCount,
	std::vector<uint8_t> &out)
{
	int i = 0;
	int o = 0;

	while (o < stopCount)
	{
		const int16_t sample = Bytes::getLE16(src + i);
		i += 2;

		// If "sample" is positive, then "sample" literal words follow. Otherwise,
		// repeat the next word "sample" times.
		if (sample > 0)
		{
			for (int16_t j = 0; j < sample; j++)
			{
				const uint16_t value = Bytes::getLE16(src + i);
				i += 2;

				out.at(o * 2) = value & 0x00FF;
				out.at((o * 2) + 1) = (value & 0xFF00) >> 8;
				o++;
			}
		}
		else
		{
			const uint16_t value = Bytes::getLE16(src + i);
			i += 2;

			const uint16_t count = -sample;

			for (uint16_t j = 0; j < count; j++)
			{
				out.at(o * 2) = value & 0x00FF;
				out.at((o * 2) + 1) = (value & 0xFF00) >> 8;
				o++;
			}
		}
	}
}
<|endoftext|>


<commit_before>//
// *** Class AliRsnPairFunctions ***
//
// "Core" method for defining the work on a pari of particles.
// For one analysis, one must setup one of this for each pair he wants to analyze,
// adding to it all analysis which he desires to do.
// Here he defines the cuts, and the particle types and charges, and can add
// functions which do different operations on the same pair, and some binning
// with respect to some kinematic variables (eta, momentum)
//
// authors: A. Pulvirenti (email: alberto.pulvirenti@ct.infn.it)
//          M. Vala (email: martin.vala@cern.ch)
//

#include <TList.h>

#include "AliLog.h"

#include "AliRsnMother.h"
#include "AliRsnEvent.h"
#include "AliRsnFunction.h"
#include "AliRsnCutSet.h"
#include "AliRsnValue.h"

#include "AliRsnPairFunctions.h"

ClassImp(AliRsnPairFunctions)

//_____________________________________________________________________________
AliRsnPairFunctions::AliRsnPairFunctions(const char *name, AliRsnPairDef *def) :
   AliRsnPair(name, def),
   fFunctions("AliRsnFunction", 0)
{
//
// Default constructor
//

   AliDebug(AliLog::kDebug + 2, "<-");
   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
AliRsnPairFunctions::AliRsnPairFunctions(const AliRsnPairFunctions& copy) :
   AliRsnPair(copy),
   fFunctions(copy.fFunctions)
{
//
// Default constructor
//

   AliDebug(AliLog::kDebug + 2, "<-");
   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
AliRsnPairFunctions& AliRsnPairFunctions::operator=(const AliRsnPairFunctions& copy)
{
   AliRsnPair::operator=(copy);

   Int_t i, n = copy.fFunctions.GetEntries();
   for (i = 0; i < n; i++) {
      AliRsnFunction *fcn = (AliRsnFunction*)copy.fFunctions[i];
      if (fcn) AddFunction(fcn);
   }

   return (*this);
}

//_____________________________________________________________________________
AliRsnPairFunctions::~AliRsnPairFunctions()
{
//
// Destructor
//

   AliDebug(AliLog::kDebug + 2, "<-");
   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
void AliRsnPairFunctions::Compute()
{
//
// Makes computations using the two passed daughter objects.
// Checks all cuts and then computes the corresponding pair object
// and then fill the list of required values using it.
//

   AliDebug(AliLog::kDebug + 2, "<-");

   TObjArrayIter   nextFcn(&fFunctions);
   AliRsnFunction *fcn = 0x0;

   while ((fcn = (AliRsnFunction*)nextFcn())) {
      fcn->SetPairDef(fPairDef);
      fcn->SetPair(&fMother);
      fcn->Fill();
   }

   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
void AliRsnPairFunctions::Init(const char *prefix, TList *list)
{
//
// Generates needed histograms, giving them a name based on
// the flags defined here, on the pair definition, and attaches
// a prefix to it, according to the argument.
//
// All generated histograms are stored into the output TList.
//

   AliDebug(AliLog::kDebug + 2, "<-");

   Int_t  i;
   TString hName("");
   AliRsnFunction *fcn = 0;
   for (i = 0; i < fFunctions.GetEntries(); i++) {
      fcn = (AliRsnFunction*)fFunctions.At(i);
      hName += prefix;
      hName += '_';
      hName += GetName();
      hName += '_';
      hName += fcn->GetName();
      if (fcn->IsUsingTH1()) list->Add(fcn->CreateHistogram(hName.Data(), ""));
      else list->Add(fcn->CreateHistogramSparse(hName.Data(), ""));
   }

   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
void AliRsnPairFunctions::AddFunction(AliRsnFunction *const fcn)
{
//
// Adds a new computing function
//

   AliDebug(AliLog::kDebug + 2, "<-");

   fFunctions.Print();
   Int_t size = fFunctions.GetEntries();
   new(fFunctions[size]) AliRsnFunction(*fcn);

   AliDebug(AliLog::kDebug + 2, "->");
}
<commit_msg>Fix of a bug that arises when adding more than 1 function to AliRsnPairFunctions<commit_after>//
// *** Class AliRsnPairFunctions ***
//
// "Core" method for defining the work on a pari of particles.
// For one analysis, one must setup one of this for each pair he wants to analyze,
// adding to it all analysis which he desires to do.
// Here he defines the cuts, and the particle types and charges, and can add
// functions which do different operations on the same pair, and some binning
// with respect to some kinematic variables (eta, momentum)
//
// authors: A. Pulvirenti (email: alberto.pulvirenti@ct.infn.it)
//          M. Vala (email: martin.vala@cern.ch)
//

#include <TList.h>

#include "AliLog.h"

#include "AliRsnMother.h"
#include "AliRsnEvent.h"
#include "AliRsnFunction.h"
#include "AliRsnCutSet.h"
#include "AliRsnValue.h"

#include "AliRsnPairFunctions.h"

ClassImp(AliRsnPairFunctions)

//_____________________________________________________________________________
AliRsnPairFunctions::AliRsnPairFunctions(const char *name, AliRsnPairDef *def) :
   AliRsnPair(name, def),
   fFunctions("AliRsnFunction", 0)
{
//
// Default constructor
//

   AliDebug(AliLog::kDebug + 2, "<-");
   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
AliRsnPairFunctions::AliRsnPairFunctions(const AliRsnPairFunctions& copy) :
   AliRsnPair(copy),
   fFunctions(copy.fFunctions)
{
//
// Default constructor
//

   AliDebug(AliLog::kDebug + 2, "<-");
   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
AliRsnPairFunctions& AliRsnPairFunctions::operator=(const AliRsnPairFunctions& copy)
{
   AliRsnPair::operator=(copy);

   Int_t i, n = copy.fFunctions.GetEntries();
   for (i = 0; i < n; i++) {
      AliRsnFunction *fcn = (AliRsnFunction*)copy.fFunctions[i];
      if (fcn) AddFunction(fcn);
   }

   return (*this);
}

//_____________________________________________________________________________
AliRsnPairFunctions::~AliRsnPairFunctions()
{
//
// Destructor
//

   AliDebug(AliLog::kDebug + 2, "<-");
   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
void AliRsnPairFunctions::Compute()
{
//
// Makes computations using the two passed daughter objects.
// Checks all cuts and then computes the corresponding pair object
// and then fill the list of required values using it.
//

   AliDebug(AliLog::kDebug + 2, "<-");

   TObjArrayIter   nextFcn(&fFunctions);
   AliRsnFunction *fcn = 0x0;

   while ((fcn = (AliRsnFunction*)nextFcn())) {
      fcn->SetPairDef(fPairDef);
      fcn->SetPair(&fMother);
      fcn->Fill();
   }

   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
void AliRsnPairFunctions::Init(const char *prefix, TList *list)
{
//
// Generates needed histograms, giving them a name based on
// the flags defined here, on the pair definition, and attaches
// a prefix to it, according to the argument.
//
// All generated histograms are stored into the output TList.
//

   AliDebug(AliLog::kDebug + 2, "<-");

   Int_t  i;
   TString hName("");
   AliRsnFunction *fcn = 0;
   for (i = 0; i < fFunctions.GetEntries(); i++) {
      fcn = (AliRsnFunction*)fFunctions.At(i);
      hName  = prefix;
      hName += '_';
      hName += GetName();
      hName += '_';
      hName += fcn->GetName();
      if (fcn->IsUsingTH1()) list->Add(fcn->CreateHistogram(hName.Data(), ""));
      else list->Add(fcn->CreateHistogramSparse(hName.Data(), ""));
   }

   AliDebug(AliLog::kDebug + 2, "->");
}

//_____________________________________________________________________________
void AliRsnPairFunctions::AddFunction(AliRsnFunction *const fcn)
{
//
// Adds a new computing function
//

   AliDebug(AliLog::kDebug + 2, "<-");

   fFunctions.Print();
   Int_t size = fFunctions.GetEntries();
   new(fFunctions[size]) AliRsnFunction(*fcn);

   AliDebug(AliLog::kDebug + 2, "->");
}
<|endoftext|>


<commit_before>/*     Copyright 2015-2018 Egor Yusov
 *
 *  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

#include <stdio.h>
#include <unistd.h>
#include <cstdio>
#include <CoreFoundation/CoreFoundation.h>

#include "CFObjectWrapper.h"

#include "MacOSFileSystem.h"
#include "Errors.h"
#include "DebugUtilities.h"

namespace
{
    std::string FindResource(std::string FilePath)
    {
        std::string dir, name;
        BasicFileSystem::SplitFilePath(FilePath, &dir, &name);
        auto dotPos = name.find(".");
        std::string type = (dotPos != std::string::npos) ? name.substr(dotPos+1) : "";
        if(dotPos != std::string::npos)
            name.erase(dotPos);

        // Naming convention established by Core Foundation library:
        // * If a function name contains the word "Create" or "Copy", you own the object.
        // * If a function name contains the word "Get", you do not own the object.
        // If you own an object, it is your responsibility to relinquish ownership
        // (using CFRelease) when you have finished with it.
        // https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html

        // get bundle and CFStrings
        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFStringWrapper cf_resource_path = CFStringCreateWithCString(NULL, dir.c_str(), kCFStringEncodingUTF8);
        CFStringWrapper cf_filename = CFStringCreateWithCString(NULL, name.c_str(), kCFStringEncodingUTF8);
        CFStringWrapper cf_file_type = CFStringCreateWithCString(NULL, type.c_str(), kCFStringEncodingUTF8);
        CFURLWrapper cf_url_resource = CFBundleCopyResourceURL(mainBundle, cf_filename, cf_file_type, cf_resource_path);
        std::string resource_path;
        if(cf_url_resource != NULL)
        {
            CFStringWrapper cf_url_string = CFURLCopyFileSystemPath(cf_url_resource, kCFURLPOSIXPathStyle);
            const char* url_string = CFStringGetCStringPtr(cf_url_string, kCFStringEncodingUTF8);
            resource_path = url_string;
        }
        return resource_path;
    }
}
MacOSFile* MacOSFileSystem::OpenFile( const FileOpenAttribs &OpenAttribs )
{
    // Try to find the file in the bundle first
    auto resource_path = FindResource(OpenAttribs.strFilePath);
    MacOSFile *pFile = nullptr;
    if(!resource_path.empty())
    {
        try
        {
            FileOpenAttribs BundleResourceOpenAttribs = OpenAttribs;
            BundleResourceOpenAttribs.strFilePath = resource_path.c_str();
            pFile = new MacOSFile(BundleResourceOpenAttribs, MacOSFileSystem::GetSlashSymbol());
        }
        catch( const std::runtime_error &err )
        {
        }
    }

    if(pFile == nullptr)
    {
        try
        {
            pFile = new MacOSFile(OpenAttribs, MacOSFileSystem::GetSlashSymbol());
        }
        catch( const std::runtime_error &err )
        {
        }
    }
    return pFile;
}

bool MacOSFileSystem::FileExists( const Diligent::Char *strFilePath )
{
    if(!FindResource(strFilePath).empty())
        return true;

    auto res = access(strFilePath, F_OK);
    return res == 0;
}

bool MacOSFileSystem::PathExists( const Diligent::Char *strPath )
{
    UNSUPPORTED( "Not implemented" );
    return false;
}

bool MacOSFileSystem::CreateDirectory( const Diligent::Char *strPath )
{
    UNSUPPORTED( "Not implemented" );
    return false;
}

void MacOSFileSystem::ClearDirectory( const Diligent::Char *strPath )
{
    UNSUPPORTED( "Not implemented" );
}

void MacOSFileSystem::DeleteFile( const Diligent::Char *strPath )
{
    remove(strPath);
}

std::vector<std::unique_ptr<FindFileData>> MacOSFileSystem::Search(const Diligent::Char *SearchPattern)
{
    UNSUPPORTED( "Not implemented" );
    return std::vector<std::unique_ptr<FindFileData>>();
}
<commit_msg>Fixed forward/backward slash issue when opening files on MacOS<commit_after>/*     Copyright 2015-2018 Egor Yusov
 *
 *  Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF ANY PROPRIETARY RIGHTS.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

#include <stdio.h>
#include <unistd.h>
#include <cstdio>
#include <CoreFoundation/CoreFoundation.h>

#include "CFObjectWrapper.h"

#include "MacOSFileSystem.h"
#include "Errors.h"
#include "DebugUtilities.h"

namespace
{
    std::string FindResource(const std::string &FilePath)
    {
        std::string dir, name;
        BasicFileSystem::SplitFilePath(FilePath, &dir, &name);
        auto dotPos = name.find(".");
        std::string type = (dotPos != std::string::npos) ? name.substr(dotPos+1) : "";
        if(dotPos != std::string::npos)
            name.erase(dotPos);

        // Naming convention established by Core Foundation library:
        // * If a function name contains the word "Create" or "Copy", you own the object.
        // * If a function name contains the word "Get", you do not own the object.
        // If you own an object, it is your responsibility to relinquish ownership
        // (using CFRelease) when you have finished with it.
        // https://developer.apple.com/library/content/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Concepts/Ownership.html

        // get bundle and CFStrings
        CFBundleRef mainBundle = CFBundleGetMainBundle();
        CFStringWrapper cf_resource_path = CFStringCreateWithCString(NULL, dir.c_str(), kCFStringEncodingUTF8);
        CFStringWrapper cf_filename = CFStringCreateWithCString(NULL, name.c_str(), kCFStringEncodingUTF8);
        CFStringWrapper cf_file_type = CFStringCreateWithCString(NULL, type.c_str(), kCFStringEncodingUTF8);
        CFURLWrapper cf_url_resource = CFBundleCopyResourceURL(mainBundle, cf_filename, cf_file_type, cf_resource_path);
        std::string resource_path;
        if(cf_url_resource != NULL)
        {
            CFStringWrapper cf_url_string = CFURLCopyFileSystemPath(cf_url_resource, kCFURLPOSIXPathStyle);
            const char* url_string = CFStringGetCStringPtr(cf_url_string, kCFStringEncodingUTF8);
            resource_path = url_string;
        }
        return resource_path;
    }
}
MacOSFile* MacOSFileSystem::OpenFile( const FileOpenAttribs &OpenAttribs )
{
    // Try to find the file in the bundle first
    std::string path(OpenAttribs.strFilePath);
    CorrectSlashes(path, MacOSFileSystem::GetSlashSymbol());
    auto resource_path = FindResource(path);

    MacOSFile *pFile = nullptr;
    if(!resource_path.empty())
    {
        try
        {
            FileOpenAttribs BundleResourceOpenAttribs = OpenAttribs;
            BundleResourceOpenAttribs.strFilePath = resource_path.c_str();
            pFile = new MacOSFile(BundleResourceOpenAttribs, MacOSFileSystem::GetSlashSymbol());
        }
        catch( const std::runtime_error &err )
        {
        }
    }

    if(pFile == nullptr)
    {
        try
        {
            pFile = new MacOSFile(OpenAttribs, MacOSFileSystem::GetSlashSymbol());
        }
        catch( const std::runtime_error &err )
        {
        }
    }
    return pFile;
}

bool MacOSFileSystem::FileExists( const Diligent::Char *strFilePath )
{
    std::string path(strFilePath);
    CorrectSlashes(path, MacOSFileSystem::GetSlashSymbol());
    auto resource_path = FindResource(path);

    if(!FindResource(path).empty())
        return true;

    auto res = access(path.c_str(), F_OK);
    return res == 0;
}

bool MacOSFileSystem::PathExists( const Diligent::Char *strPath )
{
    UNSUPPORTED( "Not implemented" );
    return false;
}

bool MacOSFileSystem::CreateDirectory( const Diligent::Char *strPath )
{
    UNSUPPORTED( "Not implemented" );
    return false;
}

void MacOSFileSystem::ClearDirectory( const Diligent::Char *strPath )
{
    UNSUPPORTED( "Not implemented" );
}

void MacOSFileSystem::DeleteFile( const Diligent::Char *strPath )
{
    remove(strPath);
}

std::vector<std::unique_ptr<FindFileData>> MacOSFileSystem::Search(const Diligent::Char *SearchPattern)
{
    UNSUPPORTED( "Not implemented" );
    return std::vector<std::unique_ptr<FindFileData>>();
}
<|endoftext|>


<commit_before>/* This file is part of VoltDB.
 * Copyright (C) 2008-2013 VoltDB Inc.
 *
 * This file contains original code and/or modifications of original code.
 * Any modifications made by VoltDB Inc. are licensed under the following
 * terms and conditions:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with VoltDB.  If not, see <http://www.gnu.org/licenses/>.
 */
/* Copyright (C) 2008 by H-Store Project
 * Brown University
 * Massachusetts Institute of Technology
 * Yale University
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <cstdlib>
#include <sstream>
#include <cassert>
#include "common/tabletuple.h"
#include "common/common.h"
#include "common/debuglog.h"
#include "common/FatalException.hpp"

namespace voltdb {

std::string TableTuple::debug(const std::string& tableName) { // ) const
    assert(m_schema);
    assert(m_data);

    std::ostringstream buffer;
    if (tableName.empty()) {
        buffer << "TableTuple(no table) ->";
    } else {
        buffer << "TableTuple(" << tableName << ") ->";
    }

	//if( isTuple ) {
    //      setCSI(1);
    // }

    if (isActive() == false) {
        buffer << " <DELETED>";
    } else {
        for (int ctr = 0; ctr < m_schema->columnCount(); ctr++) {
            buffer << "(";
            if (isNull(ctr)) {
                buffer << "<NULL>";
            } else {
                buffer << getNValue(ctr).debug();
            }
            buffer << ")";
        }
    }

    uint64_t addressNum = (uint64_t)address();
    buffer << " @" << addressNum;

    std::string ret(buffer.str());
    return ret;
}

std::string TableTuple::debugNoHeader() const {
    assert(m_schema);
    assert(m_data);

    std::ostringstream buffer;
    buffer << "TableTuple(notable) ->";

    for (int ctr = 0; ctr < m_schema->columnCount(); ctr++) {
        if (isNull(ctr)) {
            buffer << "<NULL>";
        } else {
            buffer << "(" << getNValue(ctr).debug() << ")";
        }
    }
    std::string ret(buffer.str());
    return ret;
}

bool TableTuple::compatibleForCopy(const TableTuple &source) {
    if (m_schema->columnCount() != source.m_schema->columnCount()) {
        VOLT_ERROR("Can not copy tuple: incompatible column count.");
        return false;
    }

    for (int i = 0; i < m_schema->columnCount(); ++i) {
        const ValueType mType = m_schema->columnType(i);
        const ValueType sType = source.m_schema->columnType(i);
        if (mType != sType) {
            VOLT_ERROR("Can not copy tuple: incompatible column types.");
            return false;
        }
        const bool mAllowInlinedObjects = m_schema->allowInlinedObjects();
        const bool sAllowInlinedObjects = source.m_schema->allowInlinedObjects();
        if (mAllowInlinedObjects && sAllowInlinedObjects) {
            const bool mIsInlined = m_schema->columnIsInlined(i);
            const bool sIsInlined = source.m_schema->columnIsInlined(i);
            if (mIsInlined != sIsInlined) {
                VOLT_ERROR("Can not copy tuple: incompatible column inlining.");
                return false;
            }
        }
        else {
            const int32_t mColumnLength = m_schema->columnLength(i);
            const int32_t sColumnLength = source.m_schema->columnLength(i);
            if (mColumnLength < sColumnLength) {
                VOLT_ERROR("Can not copy tuple: incompatible column lengths.");
                return false;
            }
        }
    }
    return true;
}

void TableTuple::setCSI(int newCSI) {
	if( isTuple ) {
		m_CSI = newCSI;
		m_data[1] = m_CSI;
		//std::cout << "Ustawiono nowa wartosc CSI:" << m_CSI << std::endl;
	} else {
		std::cout << "To nie tuple, a wolaja setCSI" << std::endl;
	}

}
int TableTuple::getCSI() {
	return (int) m_data[1];
}

void TableTuple::incrementCSI() {
	int current = (int) m_data[1];
	setCSI( current + 1 );
}

}
<commit_msg>tabletuple.cpp - rozwiązanie problemu z kompilacją z powodu rzutowania int na char<commit_after>/* This file is part of VoltDB.
 * Copyright (C) 2008-2013 VoltDB Inc.
 *
 * This file contains original code and/or modifications of original code.
 * Any modifications made by VoltDB Inc. are licensed under the following
 * terms and conditions:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with VoltDB.  If not, see <http://www.gnu.org/licenses/>.
 */
/* Copyright (C) 2008 by H-Store Project
 * Brown University
 * Massachusetts Institute of Technology
 * Yale University
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
 * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
 * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 */

#include <cstdlib>
#include <sstream>
#include <cassert>
#include "common/tabletuple.h"
#include "common/common.h"
#include "common/debuglog.h"
#include "common/FatalException.hpp"

namespace voltdb {

std::string TableTuple::debug(const std::string& tableName) { // ) const
    assert(m_schema);
    assert(m_data);

    std::ostringstream buffer;
    if (tableName.empty()) {
        buffer << "TableTuple(no table) ->";
    } else {
        buffer << "TableTuple(" << tableName << ") ->";
    }

	//if( isTuple ) {
    //      setCSI(1);
    // }

    if (isActive() == false) {
        buffer << " <DELETED>";
    } else {
        for (int ctr = 0; ctr < m_schema->columnCount(); ctr++) {
            buffer << "(";
            if (isNull(ctr)) {
                buffer << "<NULL>";
            } else {
                buffer << getNValue(ctr).debug();
            }
            buffer << ")";
        }
    }

    uint64_t addressNum = (uint64_t)address();
    buffer << " @" << addressNum;

    std::string ret(buffer.str());
    return ret;
}

std::string TableTuple::debugNoHeader() const {
    assert(m_schema);
    assert(m_data);

    std::ostringstream buffer;
    buffer << "TableTuple(notable) ->";

    for (int ctr = 0; ctr < m_schema->columnCount(); ctr++) {
        if (isNull(ctr)) {
            buffer << "<NULL>";
        } else {
            buffer << "(" << getNValue(ctr).debug() << ")";
        }
    }
    std::string ret(buffer.str());
    return ret;
}

bool TableTuple::compatibleForCopy(const TableTuple &source) {
    if (m_schema->columnCount() != source.m_schema->columnCount()) {
        VOLT_ERROR("Can not copy tuple: incompatible column count.");
        return false;
    }

    for (int i = 0; i < m_schema->columnCount(); ++i) {
        const ValueType mType = m_schema->columnType(i);
        const ValueType sType = source.m_schema->columnType(i);
        if (mType != sType) {
            VOLT_ERROR("Can not copy tuple: incompatible column types.");
            return false;
        }
        const bool mAllowInlinedObjects = m_schema->allowInlinedObjects();
        const bool sAllowInlinedObjects = source.m_schema->allowInlinedObjects();
        if (mAllowInlinedObjects && sAllowInlinedObjects) {
            const bool mIsInlined = m_schema->columnIsInlined(i);
            const bool sIsInlined = source.m_schema->columnIsInlined(i);
            if (mIsInlined != sIsInlined) {
                VOLT_ERROR("Can not copy tuple: incompatible column inlining.");
                return false;
            }
        }
        else {
            const int32_t mColumnLength = m_schema->columnLength(i);
            const int32_t sColumnLength = source.m_schema->columnLength(i);
            if (mColumnLength < sColumnLength) {
                VOLT_ERROR("Can not copy tuple: incompatible column lengths.");
                return false;
            }
        }
    }
    return true;
}

void TableTuple::setCSI(int newCSI) {
	if( isTuple ) {
		m_CSI = newCSI;
		m_data[1] = static_cast<char>(m_CSI);
		//std::cout << "Ustawiono nowa wartosc CSI:" << m_CSI << std::endl;
	} else {
		std::cout << "To nie tuple, a wolaja setCSI" << std::endl;
	}

}
int TableTuple::getCSI() {
	return (int) m_data[1];
}

void TableTuple::incrementCSI() {
	int current = (int) m_data[1];
	setCSI( current + 1 );
}

}
<|endoftext|>