| 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 | |
| 15 | #ifndef LLVM_CLANG_LIB_INDEX_SIMPLEFORMATCONTEXT_H |
| 16 | #define LLVM_CLANG_LIB_INDEX_SIMPLEFORMATCONTEXT_H |
| 17 | |
| 18 | #include "clang/Basic/Diagnostic.h" |
| 19 | #include "clang/Basic/DiagnosticOptions.h" |
| 20 | #include "clang/Basic/FileManager.h" |
| 21 | #include "clang/Basic/LangOptions.h" |
| 22 | #include "clang/Basic/SourceManager.h" |
| 23 | #include "clang/Rewrite/Core/Rewriter.h" |
| 24 | #include "llvm/Support/FileSystem.h" |
| 25 | #include "llvm/Support/Path.h" |
| 26 | #include "llvm/Support/raw_ostream.h" |
| 27 | |
| 28 | namespace clang { |
| 29 | namespace index { |
| 30 | |
| 31 | /// A small class to be used by libclang clients to format |
| 32 | /// a declaration string in memory. This object is instantiated once |
| 33 | /// and used each time a formatting is needed. |
| 34 | class SimpleFormatContext { |
| 35 | public: |
| 36 | SimpleFormatContext(LangOptions Options) |
| 37 | : DiagOpts(new DiagnosticOptions()), |
| 38 | Diagnostics(new DiagnosticsEngine(new DiagnosticIDs, DiagOpts.get())), |
| 39 | InMemoryFileSystem(new llvm::vfs::InMemoryFileSystem), |
| 40 | Files(FileSystemOptions(), InMemoryFileSystem), |
| 41 | Sources(*Diagnostics, Files), Rewrite(Sources, Options) { |
| 42 | Diagnostics->setClient(new IgnoringDiagConsumer, true); |
| 43 | } |
| 44 | |
| 45 | FileID createInMemoryFile(StringRef Name, StringRef Content) { |
| 46 | InMemoryFileSystem->addFile(Name, 0, |
| 47 | llvm::MemoryBuffer::getMemBuffer(Content)); |
| 48 | const FileEntry *Entry = Files.getFile(Name); |
| 49 | assert(Entry != nullptr); |
| 50 | return Sources.createFileID(Entry, SourceLocation(), SrcMgr::C_User); |
| 51 | } |
| 52 | |
| 53 | std::string getRewrittenText(FileID ID) { |
| 54 | std::string Result; |
| 55 | llvm::raw_string_ostream OS(Result); |
| 56 | Rewrite.getEditBuffer(ID).write(OS); |
| 57 | OS.flush(); |
| 58 | return Result; |
| 59 | } |
| 60 | |
| 61 | IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; |
| 62 | IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics; |
| 63 | IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem; |
| 64 | FileManager Files; |
| 65 | SourceManager Sources; |
| 66 | Rewriter Rewrite; |
| 67 | }; |
| 68 | |
| 69 | } // end namespace index |
| 70 | } // end namespace clang |
| 71 | |
| 72 | #endif |
| 73 | |