SimpleFormatContext.h 2.4 KB

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