/*
 * ClangSourceIndex.cpp
 *
 * Copyright (C) 2022 by Posit Software, PBC
 *
 * Unless you have received this program directly from Posit Software pursuant
 * to the terms of a commercial license agreement with Posit Software, then
 * this program is licensed to you under the terms of version 3 of the
 * GNU Affero General Public License. This program is distributed WITHOUT
 * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
 * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
 * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
 *
 */

#include "SourceIndex.hpp"

#include <boost/algorithm/string/predicate.hpp>
#include <boost/bind/bind.hpp>

#include <core/FileInfo.hpp>
#include <shared_core/FilePath.hpp>

#include <session/prefs/UserPrefs.hpp>

#include <core/libclang/LibClang.hpp>

#include "CompilationDatabase.hpp"

using namespace rstudio::core;
using namespace rstudio::core::libclang;
using namespace boost::placeholders;

namespace rstudio {
namespace session {
namespace modules { 
namespace clang {

namespace {

class ClangSourceIndex : public SourceIndex
{
public:
   ClangSourceIndex()
      : SourceIndex(clangCompilationDatabase(), prefs::userPrefs().clangVerbose())
   {
   }
};

// store as a pointer so that it's never destructrued during shutdown
// (we observed at least one instance of libclang crashing when calling
// clang_disposeTranslationUnit during shutdown)
ClangSourceIndex* s_pClangSourceIndex = nullptr;

} // anonymous namespace

SourceIndex& sourceIndex()
{
   if (s_pClangSourceIndex == nullptr)
      s_pClangSourceIndex = new ClangSourceIndex();
   return *s_pClangSourceIndex;
}

bool isIndexableFile(const FileInfo& fileInfo,
                     const FilePath& pkgSrcDir,
                     const FilePath& pkgIncludeDir)
{
   FilePath filePath(fileInfo.absolutePath());

   if (pkgSrcDir.exists() &&
       filePath.isWithin(pkgSrcDir) &&
       SourceIndex::isSourceFile(filePath) &&
       !boost::algorithm::starts_with(filePath.getStem(), kCompilationDbPrefix) &&
       (filePath.getFilename() != "RcppExports.cpp"))
   {
      return true;
   }
   else if (pkgIncludeDir.exists() &&
            filePath.isWithin(pkgIncludeDir) &&
            SourceIndex::isSourceFile(filePath) &&
            !boost::algorithm::ends_with(filePath.getStem(), "_RcppExports"))
   {
      return true;
   }
   else
   {
      return false;
   }
}

} // namespace clang
} // namespace modules
} // namespace session
} // namespace rstudio

