summaryrefslogtreecommitdiffstats
path: root/lib/Basic/SourceManager.cpp
diff options
context:
space:
mode:
authorEric Liu <ioeric@google.com>2018-05-09 21:35:52 +0000
committerEric Liu <ioeric@google.com>2018-05-09 21:35:52 +0000
commit617cf1a3b9bfef2c31efb67deb91d9d886e72615 (patch)
treeedc1aab452ab4e5c887db602db5b6b32a947bb60 /lib/Basic/SourceManager.cpp
parent6a37651bb30339e60ea617d510b4703bcd2e89e8 (diff)
Add SourceManagerForFile helper which sets up SourceManager and dependencies for a single file with code snippet
Summary: This can be used to create a virtual environment (incl. VFS, source manager) for code snippets. Reviewers: sammccall, klimek Reviewed By: sammccall Subscribers: klimek, mgorny, cfe-commits Differential Revision: https://reviews.llvm.org/D46176 git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@331923 91177308-0d34-0410-b5e6-96231b3b80d8
Diffstat (limited to 'lib/Basic/SourceManager.cpp')
-rw-r--r--lib/Basic/SourceManager.cpp26
1 files changed, 26 insertions, 0 deletions
diff --git a/lib/Basic/SourceManager.cpp b/lib/Basic/SourceManager.cpp
index c05dfeaa8a..ae76817826 100644
--- a/lib/Basic/SourceManager.cpp
+++ b/lib/Basic/SourceManager.cpp
@@ -2258,3 +2258,29 @@ size_t SourceManager::getDataStructureSizes() const {
return size;
}
+
+SourceManagerForFile::SourceManagerForFile(StringRef FileName,
+ StringRef Content) {
+ // This is referenced by `FileMgr` and will be released by `FileMgr` when it
+ // is deleted.
+ IntrusiveRefCntPtr<vfs::InMemoryFileSystem> InMemoryFileSystem(
+ new vfs::InMemoryFileSystem);
+ InMemoryFileSystem->addFile(
+ FileName, 0,
+ llvm::MemoryBuffer::getMemBuffer(Content, FileName,
+ /*RequiresNullTerminator=*/false));
+ // This is passed to `SM` as reference, so the pointer has to be referenced
+ // in `Environment` so that `FileMgr` can out-live this function scope.
+ FileMgr =
+ llvm::make_unique<FileManager>(FileSystemOptions(), InMemoryFileSystem);
+ // This is passed to `SM` as reference, so the pointer has to be referenced
+ // by `Environment` due to the same reason above.
+ Diagnostics = llvm::make_unique<DiagnosticsEngine>(
+ IntrusiveRefCntPtr<DiagnosticIDs>(new DiagnosticIDs),
+ new DiagnosticOptions);
+ SourceMgr = llvm::make_unique<SourceManager>(*Diagnostics, *FileMgr);
+ FileID ID = SourceMgr->createFileID(FileMgr->getFile(FileName),
+ SourceLocation(), clang::SrcMgr::C_User);
+ assert(ID.isValid());
+ SourceMgr->setMainFileID(ID);
+}