コード例 #1
0
  Files IdfToModelJob::outputFilesImpl() const
  {
    openstudio::path outpath = outdir();

    if (!boost::filesystem::exists(outpath / toPath("out.osm")))
    {
      // no output file has been generated yet
      return Files();
    }

    QWriteLocker l(&m_mutex);

    if (!m_outputfiles)
    {
      // check if model has a weather file object
      boost::optional<QUrl> weatherFilePath;
      try {
        FileInfo idfFile = this->idfFile();

        try {
          std::pair<QUrl, openstudio::path> f = idfFile.getRequiredFile(toPath("in.epw"));
          LOG(Debug, "Setting user defined epw: " << toString(f.first.toString()));
          weatherFilePath = f.first;
        } catch (const std::exception &) {
        }

        // Specify the set of files we created so that the next Job in the chain (if there is one)
        // is able to pick them up
        Files outfiles;

        FileInfo osm(outpath / toPath("out.osm"), "osm");

        if (weatherFilePath){
          osm.addRequiredFile(*weatherFilePath, toPath("in.epw"));
        }else{
          LOG(Warn, "No weather file specified");
        }

        outfiles.append(osm);
        m_outputfiles = outfiles;
      } catch (const std::exception &) {
        LOG(Warn, "OSM file not yet available, outputfiles not known");
        return Files();
      }
    }

    return *m_outputfiles;
  }
コード例 #2
0
std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
    FileManager Files((FileSystemOptions()));
    DiagnosticsEngine Diagnostics(
        IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
        new DiagnosticOptions);
    SourceManager SourceMgr(Diagnostics, Files);
    Rewriter Rewrite(SourceMgr, LangOptions());
    std::unique_ptr<llvm::MemoryBuffer> Buf =
        llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>");
    const clang::FileEntry *Entry =
        Files.getVirtualFile("<stdin>", Buf->getBufferSize(), 0);
    SourceMgr.overrideFileContents(Entry, std::move(Buf));
    FileID ID =
        SourceMgr.createFileID(Entry, SourceLocation(), clang::SrcMgr::C_User);
    for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
            I != E; ++I) {
        Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
                            I->getReplacementText());
        if (!Replace.apply(Rewrite))
            return "";
    }
    std::string Result;
    llvm::raw_string_ostream OS(Result);
    Rewrite.getEditBuffer(ID).write(OS);
    OS.flush();
    return Result;
}
コード例 #3
0
ファイル: Tooling.cpp プロジェクト: parallaxe/clang
bool
runToolOnCodeWithArgs(clang::FrontendAction *ToolAction, const Twine &Code,
                      const std::vector<std::string> &Args,
                      const Twine &FileName,
                      const std::vector<std::pair<std::string, std::string>> &
                          VirtualMappedFiles) {

  SmallString<16> FileNameStorage;
  StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
  llvm::IntrusiveRefCntPtr<FileManager> Files(
      new FileManager(FileSystemOptions()));
  ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef),
                            ToolAction, Files.get());

  SmallString<1024> CodeStorage;
  Invocation.mapVirtualFile(FileNameRef,
                            Code.toNullTerminatedStringRef(CodeStorage));

  for (auto &FilenameWithContent : VirtualMappedFiles) {
    Invocation.mapVirtualFile(FilenameWithContent.first,
                              FilenameWithContent.second);
  }

  return Invocation.run();
}
コード例 #4
0
std::string SocketMultiplexer::ClearSocket(int uid) {
  LOG(INFO) << "ClearSocket(" << uid << ")";
  // NOTE: rwlock
  std::lock_guard<std::mutex> lock(slave_files_map_lock_);
  Files().swap(slave_files_map_[uid]);
  return std::string("CLEARed") + "\n";
}
コード例 #5
0
bool runToolOnCodeWithArgs(
    clang::FrontendAction *ToolAction, const Twine &Code,
    const std::vector<std::string> &Args, const Twine &FileName,
    std::shared_ptr<PCHContainerOperations> PCHContainerOps,
    const FileContentMappings &VirtualMappedFiles) {

  SmallString<16> FileNameStorage;
  StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
  llvm::IntrusiveRefCntPtr<vfs::OverlayFileSystem> OverlayFileSystem(
      new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
  llvm::IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
      new vfs::InMemoryFileSystem);
  OverlayFileSystem->pushOverlay(InMemoryFileSystem);
  llvm::IntrusiveRefCntPtr<FileManager> Files(
      new FileManager(FileSystemOptions(), OverlayFileSystem));
  ToolInvocation Invocation(getSyntaxOnlyToolArgs(Args, FileNameRef),
                            ToolAction, Files.get(), PCHContainerOps);

  SmallString<1024> CodeStorage;
  InMemoryFileSystem->addFile(FileNameRef, 0,
                              llvm::MemoryBuffer::getMemBuffer(
                                  Code.toNullTerminatedStringRef(CodeStorage)));

  for (auto &FilenameWithContent : VirtualMappedFiles) {
    InMemoryFileSystem->addFile(
        FilenameWithContent.first, 0,
        llvm::MemoryBuffer::getMemBuffer(FilenameWithContent.second));
  }

  return Invocation.run();
}
コード例 #6
0
  Files ModelToRadPreProcessJob::outputFilesImpl() const
  {
    openstudio::path outpath = outdir();
    if (!boost::filesystem::exists(outpath / toPath("out.osm")) || !m_osm)
    {
      // no output file has been generated yet
      return Files();
    }

    Files f;
    FileInfo fi(outpath / toPath("out.osm"), "osm");
    fi.requiredFiles = m_osm->requiredFiles;

    if (!fi.hasRequiredFile(openstudio::toPath("in.epw")))
    {
      /// \todo we need better handling of OSM files and their attachments
      // epw wasn't found, look for parent one
      openstudio::path possibleepw = m_osm->fullPath.parent_path() / openstudio::toPath("in.epw");

      if (boost::filesystem::exists(possibleepw))
      {
        LOG(Info, "Fixing up EPW file for incoming OSM attachment to " << openstudio::toString(possibleepw));
        fi.addRequiredFile(possibleepw, openstudio::toPath("in.epw"));
      }
    }

    f.append(fi);
    return f;
  }
コード例 #7
0
ファイル: Replacement.cpp プロジェクト: Pear0/clang
std::string applyAllReplacements(StringRef Code, const Replacements &Replaces) {
  IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
      new vfs::InMemoryFileSystem);
  FileManager Files(FileSystemOptions(), InMemoryFileSystem);
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager SourceMgr(Diagnostics, Files);
  Rewriter Rewrite(SourceMgr, LangOptions());
  InMemoryFileSystem->addFile(
      "<stdin>", 0, llvm::MemoryBuffer::getMemBuffer(Code, "<stdin>"));
  FileID ID = SourceMgr.createFileID(Files.getFile("<stdin>"), SourceLocation(),
                                     clang::SrcMgr::C_User);
  for (Replacements::const_iterator I = Replaces.begin(), E = Replaces.end();
       I != E; ++I) {
    Replacement Replace("<stdin>", I->getOffset(), I->getLength(),
                        I->getReplacementText());
    if (!Replace.apply(Rewrite))
      return "";
  }
  std::string Result;
  llvm::raw_string_ostream OS(Result);
  Rewrite.getEditBuffer(ID).write(OS);
  OS.flush();
  return Result;
}
コード例 #8
0
ファイル: tpCollectImpl.cpp プロジェクト: PlusChie/CodeXL
bool tpCollectImpl::tpGetUndocAPI()
{
    bool retVal = false;

#if 0
    typedef unsigned long(__stdcall * PFN_CreateMergedETLFile)(unsigned short const * * const, unsigned long, unsigned short const*);

#ifndef _WIN64
    LPCSTR FNNAME_CreateMergeETLFile = "? CreateMergedETLFile@@YGKQAPBGKPBG@Z";
#else
    LPCSTR FNNAME_CreateMergeETLFile = "? CreateMergedETLFile@@YAKQEAPEBGKPEBG@Z";
#endif

    HMODULE hPerfCtrl = LoadLibrary(TEXT("C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\perfctrl.dll"));

    PFN_CreateMergedETLFile pfn = (PFN_CreateMergedETLFile)GetProcAddress(hPerfCtrl, FNNAME_CreateMergeETLFile);

    if (NULL != pfn)
    {
        LPCWSTR pszPathTraceNT = m_logFilePath;
        wchar_t pszPathTraceNTMerged[256];

        (*pfn)((unsigned short const **)&pszPathTraceNT, 1, (unsigned short const*)pszPathTraceNTMerged);
    }

    FreeLibrary(hPerfCtrl);
#endif //0

    return retVal;
} // tpGetUndocAPI
コード例 #9
0
ファイル: perf.c プロジェクト: rpreen/xcsf
void gplot_init()
{
	// set gnuplot title
	char buffer[20];
	char title[200];
	title[0] = '\0';
	sprintf(buffer, "%s", probname);
	strcat(title, buffer);

#if CON == 0
	strcat(title, " RECT COND");
#elif CON == 1
	strcat(title, " NEURAL COND");
#elif CON == 2
	strcat(title, " TREE-GP COND");
#elif CON == 3
	strcat(title, " GRAPH-DGP COND");
#endif

#ifdef SAM
	strcat(title, ", SAM");
#endif

#if PRE == 0
	strcat(title, ", LINEAR NLMS");
#elif PRE == 1
	strcat(title, ", QUADRATIC NLMS");
#elif PRE == 2
	strcat(title, ", LINEAR RLS");
#elif PRE == 3
	strcat(title, ", QUADRATIC RLS");
#elif PRE == 4
	strcat(title, ", NEURAL PRED");
#endif

	sprintf(buffer, ", P=%d", POP_SIZE);
	strcat(title, buffer);

	// execute gnuplot
#ifdef _WIN32
	gp = _popen("C:\Program Files (x86)\gnuplot\bin\pgnuplot.exe -persistent", "w");
#else
	gp = popen("gnuplot -persistent", "w");
#endif
	if(gp != NULL) {
		fprintf(gp, "set terminal wxt noraise enhanced font 'Arial,12'\n");
		fprintf(gp, "set grid\n");
		fprintf(gp, "set border linewidth 1\n");
		fprintf(gp, "set title \"%s\"\n", title);
		//fprintf(gp, "set nokey\n");
		fprintf(gp, "set xlabel 'trials'\n");
		fprintf(gp, "set ylabel 'system error'\n");
		fprintf(gp, "set style line 1 lt -1 lw 1 ps 1 lc rgb 'red'\n");
		fprintf(gp, "set style line 2 lt -1 lw 1 ps 1 lc rgb 'blue'\n");
	}
	else {
		printf("error starting gnuplot\n");
	}
}
コード例 #10
0
ファイル: ClangFormat.cpp プロジェクト: WizTeam/llvm-project
// Returns true on error.
static bool format(std::string FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  if (Code->getBufferSize() == 0)
    return true; // Empty files are formatted correctly.
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  std::vector<CharSourceRange> Ranges;
  if (fillRanges(Sources, ID, Code.get(), Ranges))
    return true;

  FormatStyle FormatStyle = getStyle(Style, FileName);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources,
            getFormattingLangOpts(FormatStyle.Standard));
  tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return false; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::sys::fs::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return true;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      if (Cursor.getNumOccurrences() != 0)
        outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
                                          Replaces, Cursor) << " }\n";
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
コード例 #11
0
    // Reads all materials from the materials assets folder.
    MaterialManager()
    {
      // Gather info about the path to the materials folder.
      auto pathInfo = PathInfo(config::Materials);
      if (!pathInfo.Valid() || pathInfo.Files().empty()) return;

      // Iterate over files in the materials folder.
      for (const string& file : pathInfo.Files())
      {
        // Emplace the material in the object map.
        auto fileInfo = PathInfo(file);
        string lowercaseName = fileInfo.BaseFilename();
        transform(lowercaseName.begin(), lowercaseName.end(), lowercaseName.begin(), tolower);
        objects.emplace(lowercaseName, lowercaseName);
      }

      objects.emplace("", string("default"));
    }
コード例 #12
0
ファイル: FileInfo.hpp プロジェクト: ChengXinDL/OpenStudio
    Files complete(const openstudio::path &t_basePath) const
    {
      std::vector<FileInfo> files;

      for (const auto & file : m_files)
      {
        files.push_back(file.complete(t_basePath));
      }

      return Files(files);
    }
コード例 #13
0
ファイル: ToolingTest.cpp プロジェクト: doubleotoo/clang
TEST(ToolInvocation, TestMapVirtualFile) {
  clang::FileManager Files((clang::FileSystemOptions()));
  std::vector<std::string> Args;
  Args.push_back("tool-executable");
  Args.push_back("-Idef");
  Args.push_back("-fsyntax-only");
  Args.push_back("test.cpp");
  clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction, &Files);
  Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
  Invocation.mapVirtualFile("def/abc", "\n");
  EXPECT_TRUE(Invocation.run());
}
コード例 #14
0
ファイル: FileInfo.hpp プロジェクト: Rahjou/OpenStudio
    Files complete(const openstudio::path &t_basePath) const
    {
      std::vector<FileInfo> files;

      for (std::vector<FileInfo>::const_iterator itr = m_files.begin();
           itr != m_files.end();
           ++itr)
      {
        files.push_back(itr->complete(t_basePath));
      }

      return Files(files);
    }
コード例 #15
0
  Files OpenStudioPostProcessJob::outputFilesImpl() const
  {
    // Dan: what's the output files generated?
    if (!boost::filesystem::exists(outdir() / toPath("report.xml")))
    {
      // no output file has been generated yet
      return Files();
    }

    Files f;
    f.append(FileInfo(outdir() / toPath("report.xml"), "xml"));
    return f;
  }
コード例 #16
0
ファイル: ClangFormat.cpp プロジェクト: ADonut/LLVM-GPGPU
// Returns true on error.
static bool format(StringRef FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  std::unique_ptr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  if (Code->getBufferSize() == 0)
    return false; // Empty files are formatted correctly.
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  std::vector<CharSourceRange> Ranges;
  if (fillRanges(Sources, ID, Code.get(), Ranges))
    return true;

  FormatStyle FormatStyle = getStyle(
      Style, (FileName == "-") ? AssumeFilename : FileName, FallbackStyle);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources,
            getFormattingLangOpts(FormatStyle.Standard));
  tooling::Replacements Replaces = reformat(FormatStyle, Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>";
      outputReplacementXML(I->getReplacementText());
      llvm::outs() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Rewrite.overwriteChangedFiles())
        return true;
    } else {
      if (Cursor.getNumOccurrences() != 0)
        outs() << "{ \"Cursor\": "
               << tooling::shiftedCodePosition(Replaces, Cursor) << " }\n";
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
コード例 #17
0
  Files ModelToRadJob::outputFilesImpl() const
  {
    openstudio::path outpath = outdir();

    QReadLocker l(&m_mutex);

    if (!boost::filesystem::exists(outpath / toPath("model.rad")) || !m_outputfiles)
    {
      // no output file has been generated yet
      return Files();
    }


    return *m_outputfiles;
  }
コード例 #18
0
  Files ModelToRadPreProcessJob::outputFilesImpl() const
  {
    openstudio::path outpath = outdir();
    if (!boost::filesystem::exists(outpath / toPath("out.osm")) || !m_osm)
    {
      // no output file has been generated yet
      return Files();
    }

    Files f;
    FileInfo fi(outpath / toPath("out.osm"), "osm");
    fi.requiredFiles = m_osm->requiredFiles;
    f.append(fi);
    return f;
  }
コード例 #19
0
  Files EnergyPlusPreProcessJob::outputFilesImpl() const
  {
    openstudio::path outpath = outdir();
    if (!boost::filesystem::exists(outpath / toPath("out.idf")))
    {
      // no output file has been generated yet
      return Files();
    }

    Files f;
    FileInfo fi(outpath / toPath("out.idf"), "idf");
    if (m_idf)
    {
      fi.requiredFiles = m_idf->requiredFiles;
    }
    f.append(fi);
    return f;
  }
コード例 #20
0
ファイル: Tooling.cpp プロジェクト: socantre/Clang
bool runToolOnCode(clang::FrontendAction *ToolAction, const Twine &Code,
                   const Twine &FileName) {
  SmallString<16> FileNameStorage;
  StringRef FileNameRef = FileName.toNullTerminatedStringRef(FileNameStorage);
  const char *const CommandLine[] = {
      "clang-tool", "-fsyntax-only", FileNameRef.data()
  };
  FileManager Files((FileSystemOptions()));
  ToolInvocation Invocation(
      std::vector<std::string>(
          CommandLine,
          CommandLine + llvm::array_lengthof(CommandLine)),
      ToolAction, &Files);

  SmallString<1024> CodeStorage;
  Invocation.mapVirtualFile(FileNameRef,
                            Code.toNullTerminatedStringRef(CodeStorage));
  return Invocation.run();
}
コード例 #21
0
int WINAPI WinMain( __in HINSTANCE hInstance, __in_opt HINSTANCE hPrevInstance, __in_opt LPSTR lpCmdLine, __in int nShowCmd )
{//S$-c
	char* dxPlacementEnvVarValue("DXSDK_DIR=C:\Program Files (x86)\Microsoft DirectX SDK (August 2007)");		//S$-a
	_putenv(dxPlacementEnvVarValue);																			//S$-a

	if (false != CGame::GetInst().Create("Arkanoid.xml"))
	{
		CGame::GetInst().SetSettings(new CBaseSettings("PIPE Studio", "Arkanoid"));
		CGame::GetInst().OnShow();
		new CArkanoidController(SC_01);
		CPreloadManager::GetInst().LoadFonts();
		CGame::GetInst().StartScene();
		CGame::GetInst().Run();
		
		delete CRndGen::GetPtr();
	}
	delete CGame::GetPtr();
	return 0;
}
コード例 #22
0
ファイル: ToolingTest.cpp プロジェクト: CODECOMMUNITY/clang
TEST(ToolInvocation, TestVirtualModulesCompilation) {
  // FIXME: Currently, this only tests that we don't exit with an error if a
  // mapped module.map is found on the include path. In the future, expand this
  // test to run a full modules enabled compilation, so we make sure we can
  // rerun modules compilations with a virtual file system.
  IntrusiveRefCntPtr<clang::FileManager> Files(
      new clang::FileManager(clang::FileSystemOptions()));
  std::vector<std::string> Args;
  Args.push_back("tool-executable");
  Args.push_back("-Idef");
  Args.push_back("-fsyntax-only");
  Args.push_back("test.cpp");
  clang::tooling::ToolInvocation Invocation(Args, new SyntaxOnlyAction,
                                            Files.get());
  Invocation.mapVirtualFile("test.cpp", "#include <abc>\n");
  Invocation.mapVirtualFile("def/abc", "\n");
  // Add a module.map file in the include directory of our header, so we trigger
  // the module.map header search logic.
  Invocation.mapVirtualFile("def/module.map", "\n");
  EXPECT_TRUE(Invocation.run());
}
コード例 #23
0
ファイル: NullJob.cpp プロジェクト: MatthewSteen/OpenStudio
 Files NullJob::outputFilesImpl() const
 {
   return Files();
 }
コード例 #24
0
ファイル: ClangFormat.cpp プロジェクト: PolyJIT/clang
// Returns true on error.
static bool format(StringRef FileName) {
  if (!OutputXML && Inplace && FileName == "-") {
    errs() << "error: cannot use -i when reading from stdin.\n";
    return false;
  }
  // On Windows, overwriting a file with an open file mapping doesn't work,
  // so read the whole file into memory when formatting in-place.
  ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
      !OutputXML && Inplace ? MemoryBuffer::getFileAsStream(FileName) :
                              MemoryBuffer::getFileOrSTDIN(FileName);
  if (std::error_code EC = CodeOrErr.getError()) {
    errs() << EC.message() << "\n";
    return true;
  }
  std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
  if (Code->getBufferSize() == 0)
    return false; // Empty files are formatted correctly.
  std::vector<tooling::Range> Ranges;
  if (fillRanges(Code.get(), Ranges))
    return true;
  StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;

  llvm::Expected<FormatStyle> FormatStyle =
      getStyle(Style, AssumedFileName, FallbackStyle, Code->getBuffer());
  if (!FormatStyle) {
    llvm::errs() << llvm::toString(FormatStyle.takeError()) << "\n";
    return true;
  }

  if (SortIncludes.getNumOccurrences() != 0)
    FormatStyle->SortIncludes = SortIncludes;
  unsigned CursorPosition = Cursor;
  Replacements Replaces = sortIncludes(*FormatStyle, Code->getBuffer(), Ranges,
                                       AssumedFileName, &CursorPosition);
  auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
  if (!ChangedCode) {
    llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
    return true;
  }
  // Get new affected ranges after sorting `#includes`.
  Ranges = tooling::calculateRangesAfterReplacements(Replaces, Ranges);
  FormattingAttemptStatus Status;
  Replacements FormatChanges = reformat(*FormatStyle, *ChangedCode, Ranges,
                                        AssumedFileName, &Status);
  Replaces = Replaces.merge(FormatChanges);
  if (OutputXML) {
    outs() << "<?xml version='1.0'?>\n<replacements "
              "xml:space='preserve' incomplete_format='"
           << (Status.FormatComplete ? "false" : "true") << "'";
    if (!Status.FormatComplete)
      outs() << " line='" << Status.Line << "'";
    outs() << ">\n";
    if (Cursor.getNumOccurrences() != 0)
      outs() << "<cursor>"
             << FormatChanges.getShiftedCodePosition(CursorPosition)
             << "</cursor>\n";

    outputReplacementsXML(Replaces);
    outs() << "</replacements>\n";
  } else {
    IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
        new vfs::InMemoryFileSystem);
    FileManager Files(FileSystemOptions(), InMemoryFileSystem);
    DiagnosticsEngine Diagnostics(
        IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
        new DiagnosticOptions);
    SourceManager Sources(Diagnostics, Files);
    FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
                                   InMemoryFileSystem.get());
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Rewrite.overwriteChangedFiles())
        return true;
    } else {
      if (Cursor.getNumOccurrences() != 0) {
        outs() << "{ \"Cursor\": "
               << FormatChanges.getShiftedCodePosition(CursorPosition)
               << ", \"IncompleteFormat\": "
               << (Status.FormatComplete ? "false" : "true");
        if (!Status.FormatComplete)
          outs() << ", \"Line\": " << Status.Line;
        outs() << " }\n";
      }
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
コード例 #25
0
  void RunManagerWatcher::jobFinishedExtInternal(const openstudio::UUID &t_id, const openstudio::runmanager::JobErrors& t_errors, 
      const openstudio::DateTime &t_lastRun, const std::vector<openstudio::runmanager::FileInfo> &t_outputfiles)
  {
    jobFinishedExt(t_id, t_errors, t_lastRun, t_outputfiles);

    try {
      Job job = m_runManager.getJob(t_id);

      boost::optional<openstudio::runmanager::Job> parent = job;
      while (parent->parent())
      {
        parent = parent->parent();
      }

      TreeStatusEnum status = parent->treeStatus();
      if (status == TreeStatusEnum::Finished || status == TreeStatusEnum::Failed || status == TreeStatusEnum::Canceled)
      {
        LOG(Debug, "Calling treeFinished");
        treeFinished(*parent);
      }

      if (job.hasMergedJobs())
      {
        std::vector<MergedJobResults> mergedJobs = job.mergedJobResults();
        openstudio::runmanager::JobType jobtype = job.jobType();
        openstudio::DateTime lastRun = t_lastRun;
        openstudio::UUID mergedIntoJobId = t_id;
        JobParams inputParams = job.params();

        std::vector<JobParams> params;

        if (jobtype == JobType::Ruby)
        {
          RubyJobBuilder rjb(inputParams);
          std::vector<RubyJobBuilder> mergedRubyJobs = rjb.mergedJobs();
          OS_ASSERT(mergedRubyJobs.size() + 1 == mergedJobs.size());
          params.push_back(inputParams);

          for (std::vector<RubyJobBuilder>::const_iterator itr = mergedRubyJobs.begin();
               itr != mergedRubyJobs.end();
               ++itr)
          {
            params.push_back(itr->toParams());
          }

        }

        OS_ASSERT(params.empty() || params.size() == mergedJobs.size());

        for (size_t pos = 0; pos < mergedJobs.size(); ++pos)
        {
          openstudio::UUID jobId = mergedJobs[pos].uuid;
          JobErrors errors = mergedJobs[pos].errors;
          Files outputFiles = mergedJobs[pos].outputFiles;

          bool isMergedJob = true;

          jobFinishedDetails(jobId, jobtype, lastRun, errors, outputFiles, params.empty()?inputParams:params.at(pos),
              isMergedJob, mergedIntoJobId);
        }
      } else {
        // no merged jobs
        jobFinishedDetails(t_id, job.jobType(), t_lastRun, t_errors, Files(job.outputFiles()), JobParams(job.params()),
            false, openstudio::UUID());
      }
    } catch (const std::runtime_error &e) {
      LOG(Error, "Error extracting job finished details " << e.what());
    }
  }
コード例 #26
0
ファイル: driver.cpp プロジェクト: it3ration/opcpp
bool opDriver::ValidateFiles(const opParameters& p) {
    /*=== files ===*/

    const vector<opString>& tmpFiles = p.Files.GetValues();
    opList<opString> Files(tmpFiles.begin(), tmpFiles.end());
    opList<opString>::iterator i = Files.Begin();
    opList<opString>::iterator end = Files.End();
    opList<opString>::iterator old;

    while (i != end) {
        path filepath = (*i).GetString();

        if (exists(filepath)) {
            filepath = to_relative_path(filepath);
            OhFiles.insert(filepath);
            old = i;
            ++i;
            Files.Erase(old);
            continue;
        }

        ++i;
    }

    /*=== files in -d locations ===*/

    const vector<opString>& Dirs = p.Directories.GetValues();

    for (size_t d = 0; d < Dirs.size(); d++) {
        i = Files.Begin();
        end = Files.End();

        while (i != end) {
            path filepath =
                Dirs[d].GetString() / to_relative_path((*i).GetString());

            if (exists(filepath)) {
                filepath = to_relative_path(filepath);
                OhFiles.insert(filepath);
                old = i;
                ++i;
                Files.Erase(old);
                continue;
            }

            ++i;
        }
    }

    /*=== error if files were not found ===*/

    if (!Files.IsEmpty()) {
        Log("Error: The following files were not found:");

        i = Files.Begin();
        end = Files.End();

        while (i != end) {
            Log("\t'" + *i + "'");

            ++i;
        }

        Log("");

        return false;
    }

    /*=== files in -ohd locations ===*/

    const vector<opString>& FileDirs = p.FileDirectories.GetValues();

    for (size_t d = 0; d < FileDirs.size(); d++)
        FindFilesInDirectory(FileDirs[d], ".oh", OhFiles);

    return true;
}
コード例 #27
0
 Files CalculateEconomicsJob::outputFilesImpl() const
 {
   assert(!"Not implemented");
   return Files();
 }
コード例 #28
0
ファイル: ClangFormat.cpp プロジェクト: CSI-LLVM/clang
static bool fillRanges(MemoryBuffer *Code,
                       std::vector<tooling::Range> &Ranges) {
  IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
      new vfs::InMemoryFileSystem);
  FileManager Files(FileSystemOptions(), InMemoryFileSystem);
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  FileID ID = createInMemoryFile("<irrelevant>", Code, Sources, Files,
                                 InMemoryFileSystem.get());
  if (!LineRanges.empty()) {
    if (!Offsets.empty() || !Lengths.empty()) {
      errs() << "error: cannot use -lines with -offset/-length\n";
      return true;
    }

    for (unsigned i = 0, e = LineRanges.size(); i < e; ++i) {
      unsigned FromLine, ToLine;
      if (parseLineRange(LineRanges[i], FromLine, ToLine)) {
        errs() << "error: invalid <start line>:<end line> pair\n";
        return true;
      }
      if (FromLine > ToLine) {
        errs() << "error: start line should be less than end line\n";
        return true;
      }
      SourceLocation Start = Sources.translateLineCol(ID, FromLine, 1);
      SourceLocation End = Sources.translateLineCol(ID, ToLine, UINT_MAX);
      if (Start.isInvalid() || End.isInvalid())
        return true;
      unsigned Offset = Sources.getFileOffset(Start);
      unsigned Length = Sources.getFileOffset(End) - Offset;
      Ranges.push_back(tooling::Range(Offset, Length));
    }
    return false;
  }

  if (Offsets.empty())
    Offsets.push_back(0);
  if (Offsets.size() != Lengths.size() &&
      !(Offsets.size() == 1 && Lengths.empty())) {
    errs() << "error: number of -offset and -length arguments must match.\n";
    return true;
  }
  for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
    if (Offsets[i] >= Code->getBufferSize()) {
      errs() << "error: offset " << Offsets[i] << " is outside the file\n";
      return true;
    }
    SourceLocation Start =
        Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
    SourceLocation End;
    if (i < Lengths.size()) {
      if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
        errs() << "error: invalid length " << Lengths[i]
               << ", offset + length (" << Offsets[i] + Lengths[i]
               << ") is outside the file.\n";
        return true;
      }
      End = Start.getLocWithOffset(Lengths[i]);
    } else {
      End = Sources.getLocForEndOfFile(ID);
    }
    unsigned Offset = Sources.getFileOffset(Start);
    unsigned Length = Sources.getFileOffset(End) - Offset;
    Ranges.push_back(tooling::Range(Offset, Length));
  }
  return false;
}
コード例 #29
0
ファイル: ClangFormat.cpp プロジェクト: CSI-LLVM/clang
// Returns true on error.
static bool format(StringRef FileName) {
  ErrorOr<std::unique_ptr<MemoryBuffer>> CodeOrErr =
      MemoryBuffer::getFileOrSTDIN(FileName);
  if (std::error_code EC = CodeOrErr.getError()) {
    errs() << EC.message() << "\n";
    return true;
  }
  std::unique_ptr<llvm::MemoryBuffer> Code = std::move(CodeOrErr.get());
  if (Code->getBufferSize() == 0)
    return false; // Empty files are formatted correctly.
  std::vector<tooling::Range> Ranges;
  if (fillRanges(Code.get(), Ranges))
    return true;
  StringRef AssumedFileName = (FileName == "-") ? AssumeFileName : FileName;
  FormatStyle FormatStyle = getStyle(Style, AssumedFileName, FallbackStyle);
  if (SortIncludes.getNumOccurrences() != 0)
    FormatStyle.SortIncludes = SortIncludes;
  unsigned CursorPosition = Cursor;
  Replacements Replaces = sortIncludes(FormatStyle, Code->getBuffer(), Ranges,
                                       AssumedFileName, &CursorPosition);
  auto ChangedCode = tooling::applyAllReplacements(Code->getBuffer(), Replaces);
  if (!ChangedCode) {
    llvm::errs() << llvm::toString(ChangedCode.takeError()) << "\n";
    return true;
  }
  for (const auto &R : Replaces)
    Ranges.push_back({R.getOffset(), R.getLength()});

  bool IncompleteFormat = false;
  Replacements FormatChanges = reformat(FormatStyle, *ChangedCode, Ranges,
                                        AssumedFileName, &IncompleteFormat);
  Replaces = tooling::mergeReplacements(Replaces, FormatChanges);
  if (OutputXML) {
    outs() << "<?xml version='1.0'?>\n<replacements "
              "xml:space='preserve' incomplete_format='"
           << (IncompleteFormat ? "true" : "false") << "'>\n";
    if (Cursor.getNumOccurrences() != 0)
      outs() << "<cursor>"
             << tooling::shiftedCodePosition(FormatChanges, CursorPosition)
             << "</cursor>\n";

    outputReplacementsXML(Replaces); 
    outs() << "</replacements>\n";
  } else {
    IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
        new vfs::InMemoryFileSystem);
    FileManager Files(FileSystemOptions(), InMemoryFileSystem);
    DiagnosticsEngine Diagnostics(
        IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
        new DiagnosticOptions);
    SourceManager Sources(Diagnostics, Files);
    FileID ID = createInMemoryFile(AssumedFileName, Code.get(), Sources, Files,
                                   InMemoryFileSystem.get());
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (FileName == "-")
        errs() << "error: cannot use -i when reading from stdin.\n";
      else if (Rewrite.overwriteChangedFiles())
        return true;
    } else {
      if (Cursor.getNumOccurrences() != 0)
        outs() << "{ \"Cursor\": "
               << tooling::shiftedCodePosition(FormatChanges, CursorPosition)
               << ", \"IncompleteFormat\": "
               << (IncompleteFormat ? "true" : "false") << " }\n";
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}
コード例 #30
0
ファイル: ClangFormat.cpp プロジェクト: zygoloid/clang
// Returns true on error.
static bool format(std::string FileName) {
  FileManager Files((FileSystemOptions()));
  DiagnosticsEngine Diagnostics(
      IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
      new DiagnosticOptions);
  SourceManager Sources(Diagnostics, Files);
  OwningPtr<MemoryBuffer> Code;
  if (error_code ec = MemoryBuffer::getFileOrSTDIN(FileName, Code)) {
    llvm::errs() << ec.message() << "\n";
    return true;
  }
  FileID ID = createInMemoryFile(FileName, Code.get(), Sources, Files);
  Lexer Lex(ID, Sources.getBuffer(ID), Sources, getFormattingLangOpts());
  if (Offsets.empty())
    Offsets.push_back(0);
  if (Offsets.size() != Lengths.size() &&
      !(Offsets.size() == 1 && Lengths.empty())) {
    llvm::errs()
        << "error: number of -offset and -length arguments must match.\n";
    return true;
  }
  std::vector<CharSourceRange> Ranges;
  for (unsigned i = 0, e = Offsets.size(); i != e; ++i) {
    if (Offsets[i] >= Code->getBufferSize()) {
      llvm::errs() << "error: offset " << Offsets[i]
                   << " is outside the file\n";
      return true;
    }
    SourceLocation Start =
        Sources.getLocForStartOfFile(ID).getLocWithOffset(Offsets[i]);
    SourceLocation End;
    if (i < Lengths.size()) {
      if (Offsets[i] + Lengths[i] > Code->getBufferSize()) {
        llvm::errs() << "error: invalid length " << Lengths[i]
                     << ", offset + length (" << Offsets[i] + Lengths[i]
                     << ") is outside the file.\n";
        return true;
      }
      End = Start.getLocWithOffset(Lengths[i]);
    } else {
      End = Sources.getLocForEndOfFile(ID);
    }
    Ranges.push_back(CharSourceRange::getCharRange(Start, End));
  }
  tooling::Replacements Replaces = reformat(getStyle(), Lex, Sources, Ranges);
  if (OutputXML) {
    llvm::outs()
        << "<?xml version='1.0'?>\n<replacements xml:space='preserve'>\n";
    for (tooling::Replacements::const_iterator I = Replaces.begin(),
                                               E = Replaces.end();
         I != E; ++I) {
      llvm::outs() << "<replacement "
                   << "offset='" << I->getOffset() << "' "
                   << "length='" << I->getLength() << "'>"
                   << I->getReplacementText() << "</replacement>\n";
    }
    llvm::outs() << "</replacements>\n";
  } else {
    Rewriter Rewrite(Sources, LangOptions());
    tooling::applyAllReplacements(Replaces, Rewrite);
    if (Inplace) {
      if (Replaces.size() == 0)
        return false; // Nothing changed, don't touch the file.

      std::string ErrorInfo;
      llvm::raw_fd_ostream FileStream(FileName.c_str(), ErrorInfo,
                                      llvm::raw_fd_ostream::F_Binary);
      if (!ErrorInfo.empty()) {
        llvm::errs() << "Error while writing file: " << ErrorInfo << "\n";
        return true;
      }
      Rewrite.getEditBuffer(ID).write(FileStream);
      FileStream.flush();
    } else {
      Rewrite.getEditBuffer(ID).write(outs());
    }
  }
  return false;
}