80 lines · c
1//===--- VirtualFileHelper.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-exception6//7//===----------------------------------------------------------------------===//8///9/// This file defines an utility class for tests that needs a source10/// manager for a virtual file with customizable content.11///12//===----------------------------------------------------------------------===//13 14#ifndef CLANG_MODERNIZE_VIRTUAL_FILE_HELPER_H15#define CLANG_MODERNIZE_VIRTUAL_FILE_HELPER_H16 17#include "clang/Basic/Diagnostic.h"18#include "clang/Basic/DiagnosticOptions.h"19#include "clang/Basic/FileManager.h"20#include "clang/Basic/SourceManager.h"21#include "clang/Frontend/TextDiagnosticPrinter.h"22 23namespace clang {24 25/// Class that provides easy access to a SourceManager and that allows to26/// map virtual files conveniently.27class VirtualFileHelper {28 struct VirtualFile {29 std::string FileName;30 std::string Code;31 };32 33public:34 VirtualFileHelper()35 : Diagnostics(DiagnosticIDs::create(), DiagOpts),36 DiagnosticPrinter(llvm::outs(), DiagOpts),37 Files((FileSystemOptions())) {}38 39 /// Create a virtual file \p FileName, with content \p Code.40 void mapFile(llvm::StringRef FileName, llvm::StringRef Code) {41 VirtualFile VF = { FileName, Code };42 VirtualFiles.push_back(VF);43 }44 45 /// Create a new \c SourceManager with the virtual files and contents46 /// mapped to it.47 SourceManager &getNewSourceManager() {48 Sources.reset(new SourceManager(Diagnostics, Files));49 mapVirtualFiles(*Sources);50 return *Sources;51 }52 53 /// Map the virtual file contents in the given \c SourceManager.54 void mapVirtualFiles(SourceManager &SM) const {55 for (llvm::SmallVectorImpl<VirtualFile>::const_iterator56 I = VirtualFiles.begin(),57 E = VirtualFiles.end();58 I != E; ++I) {59 std::unique_ptr<llvm::MemoryBuffer> Buf =60 llvm::MemoryBuffer::getMemBuffer(I->Code);61 FileEntryRef Entry = SM.getFileManager().getVirtualFileRef(62 I->FileName, Buf->getBufferSize(), /*ModificationTime=*/0);63 SM.overrideFileContents(Entry, std::move(Buf));64 }65 }66 67private:68 DiagnosticOptions DiagOpts;69 DiagnosticsEngine Diagnostics;70 TextDiagnosticPrinter DiagnosticPrinter;71 FileManager Files;72 // most tests don't need more than one file73 llvm::SmallVector<VirtualFile, 1> VirtualFiles;74 std::unique_ptr<SourceManager> Sources;75};76 77} // end namespace clang78 79#endif // CLANG_MODERNIZE_VIRTUAL_FILE_HELPER_H80