SimpleFormatContext.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //===--- SimpleFormatContext.h ----------------------------------*- C++ -*-===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. /// \file
  11. ///
  12. /// \brief Defines a utility class for use of clang-format in libclang
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_CLANG_LIB_INDEX_SIMPLEFORMATCONTEXT_H
  16. #define LLVM_CLANG_LIB_INDEX_SIMPLEFORMATCONTEXT_H
  17. #include "clang/Basic/Diagnostic.h"
  18. #include "clang/Basic/DiagnosticOptions.h"
  19. #include "clang/Basic/FileManager.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Rewrite/Core/Rewriter.h"
  23. #include "llvm/Support/FileSystem.h"
  24. #include "llvm/Support/Path.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. namespace clang {
  27. namespace index {
  28. /// \brief A small class to be used by libclang clients to format
  29. /// a declaration string in memory. This object is instantiated once
  30. /// and used each time a formatting is needed.
  31. class SimpleFormatContext {
  32. public:
  33. SimpleFormatContext(LangOptions Options)
  34. : DiagOpts(new DiagnosticOptions()),
  35. Diagnostics(new DiagnosticsEngine(new DiagnosticIDs,
  36. DiagOpts.get())),
  37. Files((FileSystemOptions())),
  38. Sources(*Diagnostics, Files),
  39. Rewrite(Sources, Options) {
  40. Diagnostics->setClient(new IgnoringDiagConsumer, true);
  41. }
  42. FileID createInMemoryFile(StringRef Name, StringRef Content) {
  43. std::unique_ptr<llvm::MemoryBuffer> Source =
  44. llvm::MemoryBuffer::getMemBuffer(Content);
  45. const FileEntry *Entry =
  46. Files.getVirtualFile(Name, Source->getBufferSize(), 0);
  47. Sources.overrideFileContents(Entry, std::move(Source));
  48. assert(Entry != nullptr);
  49. return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User);
  50. }
  51. std::string getRewrittenText(FileID ID) {
  52. std::string Result;
  53. llvm::raw_string_ostream OS(Result);
  54. Rewrite.getEditBuffer(ID).write(OS);
  55. OS.flush();
  56. return Result;
  57. }
  58. IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
  59. IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
  60. FileManager Files;
  61. SourceManager Sources;
  62. Rewriter Rewrite;
  63. };
  64. } // end namespace index
  65. } // end namespace clang
  66. #endif