本文整理汇总了C++中SourceManager类的典型用法代码示例。如果您正苦于以下问题:C++ SourceManager类的具体用法?C++ SourceManager怎么用?C++ SourceManager使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了SourceManager类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: CheckLists
/// CheckLists - Compare expected to seen diagnostic lists and return the
/// the difference between them.
static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
const char *Label,
DirectiveList &Left,
const_diag_iterator d2_begin,
const_diag_iterator d2_end,
bool IgnoreUnexpected) {
std::vector<Directive *> LeftOnly;
DiagList Right(d2_begin, d2_end);
for (auto &Owner : Left) {
Directive &D = *Owner;
unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
for (unsigned i = 0; i < D.Max; ++i) {
DiagList::iterator II, IE;
for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
if (!D.MatchAnyLine) {
unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
if (LineNo1 != LineNo2)
continue;
}
if (!D.DiagnosticLoc.isInvalid() &&
!IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first))
continue;
const std::string &RightText = II->second;
if (D.match(RightText))
break;
}
if (II == IE) {
// Not found.
if (i >= D.Min) break;
LeftOnly.push_back(&D);
} else {
// Found. The same cannot be found twice.
Right.erase(II);
}
}
}
// Now all that's left in Right are those that were not matched.
unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
if (!IgnoreUnexpected)
num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
return num;
}
示例2: Initialize
void Initialize(ASTContext &context) {
//llvm::errs() << "initializing consumer\n";
Context = &context;
SM = &Context->getSourceManager();
// Get the ID and start/end of the main file.
MainFileID = SM->getMainFileID();
}
示例3: TEST
TEST(FileSpecificDiagnosticConsumer, SubConsumersFinishInOrder) {
SourceManager sourceMgr;
(void)sourceMgr.addMemBufferCopy("abcde", "A");
(void)sourceMgr.addMemBufferCopy("vwxyz", "B");
auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
nullptr, None);
auto consumerUnaffiliated = llvm::make_unique<ExpectationDiagnosticConsumer>(
consumerA.get(), None);
SmallVector<FileSpecificDiagnosticConsumer::ConsumerPair, 2> consumers;
consumers.emplace_back("A", std::move(consumerA));
consumers.emplace_back("", std::move(consumerUnaffiliated));
FileSpecificDiagnosticConsumer topConsumer(consumers);
topConsumer.finishProcessing();
}
示例4: setFromSourceRange
void Replacement::setFromSourceRange(const SourceManager &Sources,
const CharSourceRange &Range,
StringRef ReplacementText,
const LangOptions &LangOpts) {
setFromSourceLocation(Sources, Sources.getSpellingLoc(Range.getBegin()),
getRangeSize(Sources, Range, LangOpts),
ReplacementText);
}
示例5: emitImportStackRecursively
/// \brief Helper to recursivly walk up the import stack and print each layer
/// on the way back down.
void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc,
StringRef ModuleName,
const SourceManager &SM) {
if (ModuleName.empty()) {
return;
}
PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
// Emit the other import frames first.
std::pair<SourceLocation, StringRef> NextImportLoc
= SM.getModuleImportLoc(Loc);
emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
// Emit the inclusion text/note.
emitImportLocation(Loc, PLoc, ModuleName, SM);
}
示例6: ReportEvent
static void ReportEvent(raw_ostream &o, const PathDiagnosticPiece& P,
const FIDMap& FM,
const SourceManager &SM,
const LangOptions &LangOpts,
unsigned indent,
unsigned depth,
bool isKeyEvent = false) {
Indent(o, indent) << "<dict>\n";
++indent;
Indent(o, indent) << "<key>kind</key><string>event</string>\n";
if (isKeyEvent) {
Indent(o, indent) << "<key>key_event</key><true/>\n";
}
// Output the location.
FullSourceLoc L = P.getLocation().asLocation();
Indent(o, indent) << "<key>location</key>\n";
EmitLocation(o, SM, L, FM, indent);
// Output the ranges (if any).
ArrayRef<SourceRange> Ranges = P.getRanges();
if (!Ranges.empty()) {
Indent(o, indent) << "<key>ranges</key>\n";
Indent(o, indent) << "<array>\n";
++indent;
for (auto &R : Ranges)
EmitRange(o, SM,
Lexer::getAsCharRange(SM.getExpansionRange(R), SM, LangOpts),
FM, indent + 1);
--indent;
Indent(o, indent) << "</array>\n";
}
// Output the call depth.
Indent(o, indent) << "<key>depth</key>";
EmitInteger(o, depth) << '\n';
// Output the text.
assert(!P.getString().empty());
Indent(o, indent) << "<key>extended_message</key>\n";
Indent(o, indent);
EmitString(o, P.getString()) << '\n';
// Output the short text.
// FIXME: Really use a short string.
Indent(o, indent) << "<key>message</key>\n";
Indent(o, indent);
EmitString(o, P.getString()) << '\n';
// Finish up.
--indent;
Indent(o, indent); o << "</dict>\n";
}
示例7: emitDiagnosticMessage
void SerializedDiagnosticConsumer::
emitDiagnosticMessage(SourceManager &SM,
SourceLoc Loc,
DiagnosticKind Kind,
StringRef Text,
const DiagnosticInfo &Info) {
// Emit the diagnostic to bitcode.
llvm::BitstreamWriter &Stream = State->Stream;
RecordData &Record = State->Record;
AbbreviationMap &Abbrevs = State->Abbrevs;
StringRef filename = "";
if (Loc.isValid())
filename = SM.getDisplayNameForLoc(Loc);
// Emit the RECORD_DIAG record.
Record.clear();
Record.push_back(RECORD_DIAG);
Record.push_back(getDiagnosticLevel(Kind));
addLocToRecord(Loc, SM, filename, Record);
// FIXME: Swift diagnostics currently have no category.
Record.push_back(0);
// FIXME: Swift diagnostics currently have no flags.
Record.push_back(0);
// Emit the message.
Record.push_back(Text.size());
Stream.EmitRecordWithBlob(Abbrevs.get(RECORD_DIAG), Record, Text);
// If the location is invalid, do not emit source ranges or fixits.
if (Loc.isInvalid())
return;
// Emit source ranges.
auto RangeAbbrev = State->Abbrevs.get(RECORD_SOURCE_RANGE);
for (const auto &R : Info.Ranges) {
if (R.isInvalid())
continue;
State->Record.clear();
State->Record.push_back(RECORD_SOURCE_RANGE);
addRangeToRecord(R, SM, filename, State->Record);
State->Stream.EmitRecordWithAbbrev(RangeAbbrev, State->Record);
}
// Emit FixIts.
auto FixItAbbrev = State->Abbrevs.get(RECORD_FIXIT);
for (const auto &F : Info.FixIts) {
if (F.getRange().isValid()) {
State->Record.clear();
State->Record.push_back(RECORD_FIXIT);
addRangeToRecord(F.getRange(), SM, filename, State->Record);
State->Record.push_back(F.getText().size());
Stream.EmitRecordWithBlob(FixItAbbrev, Record, F.getText());
}
}
}
示例8: addParameters
static void addParameters(ArrayRef<Identifier> &ArgNames,
const Pattern *Pat,
TextEntity &Ent,
SourceManager &SM,
unsigned BufferID) {
if (auto ParenPat = dyn_cast<ParenPattern>(Pat)) {
addParameters(ArgNames, ParenPat->getSubPattern(), Ent, SM, BufferID);
return;
}
if (auto Tuple = dyn_cast<TuplePattern>(Pat)) {
for (const auto &Elt : Tuple->getElements())
addParameters(ArgNames, Elt.getPattern(), Ent, SM, BufferID);
return;
}
StringRef Arg;
if (!ArgNames.empty()) {
Identifier Id = ArgNames.front();
Arg = Id.empty() ? "_" : Id.str();
ArgNames = ArgNames.slice(1);
}
if (auto Typed = dyn_cast<TypedPattern>(Pat)) {
VarDecl *VD = nullptr;
if (auto Named = dyn_cast<NamedPattern>(Typed->getSubPattern())) {
VD = Named->getDecl();
}
SourceRange TypeRange = Typed->getTypeLoc().getSourceRange();
if (auto InOutTyR =
dyn_cast_or_null<InOutTypeRepr>(Typed->getTypeLoc().getTypeRepr())) {
TypeRange = InOutTyR->getBase()->getSourceRange();
}
if (TypeRange.isInvalid())
return;
unsigned StartOffs = SM.getLocOffsetInBuffer(TypeRange.Start, BufferID);
unsigned EndOffs =
SM.getLocOffsetInBuffer(Lexer::getLocForEndOfToken(SM, TypeRange.End),
BufferID);
TextRange TR{ StartOffs, EndOffs-StartOffs };
TextEntity Param(VD, Arg, TR, StartOffs);
Ent.SubEntities.push_back(std::move(Param));
}
}
示例9: CheckRemoval
// Checks if 'typedef' keyword can be removed - we do it only if
// it is the only declaration in a declaration chain.
static bool CheckRemoval(SourceManager &SM, SourceLocation StartLoc,
ASTContext &Context) {
assert(StartLoc.isFileID() && "StartLoc must not be in a macro");
std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(StartLoc);
StringRef File = SM.getBufferData(LocInfo.first);
const char *TokenBegin = File.data() + LocInfo.second;
Lexer DeclLexer(SM.getLocForStartOfFile(LocInfo.first), Context.getLangOpts(),
File.begin(), TokenBegin, File.end());
Token Tok;
int ParenLevel = 0;
bool FoundTypedef = false;
while (!DeclLexer.LexFromRawLexer(Tok) && !Tok.is(tok::semi)) {
switch (Tok.getKind()) {
case tok::l_brace:
case tok::r_brace:
// This might be the `typedef struct {...} T;` case.
return false;
case tok::l_paren:
ParenLevel++;
break;
case tok::r_paren:
ParenLevel--;
break;
case tok::comma:
if (ParenLevel == 0) {
// If there is comma and we are not between open parenthesis then it is
// two or more declarations in this chain.
return false;
}
break;
case tok::raw_identifier:
if (Tok.getRawIdentifier() == "typedef") {
FoundTypedef = true;
}
break;
default:
break;
}
}
// Sanity check against weird macro cases.
return FoundTypedef;
}
示例10: Scan
static void Scan(IvarUsageMap &M, const DeclContext *C, const FileID FID,
SourceManager &SM) {
for (const auto *I : C->decls())
if (const auto *FD = dyn_cast<FunctionDecl>(I)) {
SourceLocation L = FD->getLocStart();
if (SM.getFileID(L) == FID)
Scan(M, FD->getBody());
}
}
示例11: setFromSourceLocation
void Replacement::setFromSourceLocation(const SourceManager &Sources,
SourceLocation Start, unsigned Length,
StringRef ReplacementText) {
const std::pair<FileID, unsigned> DecomposedLocation =
Sources.getDecomposedLoc(Start);
const FileEntry *Entry = Sources.getFileEntryForID(DecomposedLocation.first);
if (Entry) {
// Make FilePath absolute so replacements can be applied correctly when
// relative paths for files are used.
llvm::SmallString<256> FilePath(Entry->getName());
std::error_code EC = llvm::sys::fs::make_absolute(FilePath);
this->FilePath = EC ? FilePath.c_str() : Entry->getName();
} else {
this->FilePath = InvalidLocation;
}
this->ReplacementRange = Range(DecomposedLocation.second, Length);
this->ReplacementText = ReplacementText;
}
示例12: print
void SourceLoc::print(raw_ostream &OS, const SourceManager &SM,
unsigned &LastBufferID) const {
if (isInvalid()) {
OS << "<invalid loc>";
return;
}
unsigned BufferID = SM.findBufferContainingLoc(*this);
if (BufferID != LastBufferID) {
OS << SM.getIdentifierForBuffer(BufferID);
LastBufferID = BufferID;
} else {
OS << "line";
}
auto LineAndCol = SM.getLineAndColumn(*this, BufferID);
OS << ':' << LineAndCol.first << ':' << LineAndCol.second;
}
示例13: getTopMostMacro
static SourceLocation getTopMostMacro(SourceLocation Loc, SourceManager &SM) {
assert(Loc.isMacroID());
SourceLocation Last;
while (Loc.isMacroID()) {
Last = Loc;
Loc = SM.getImmediateMacroCallerLoc(Loc);
}
return Last;
}
示例14: TEST
TEST(FileSpecificDiagnosticConsumer,
ErrorsInUnaffiliatedFilesGoToEveryConsumer) {
SourceManager sourceMgr;
// 01234
unsigned bufferA = sourceMgr.addMemBufferCopy("abcde", "A");
unsigned bufferB = sourceMgr.addMemBufferCopy("vwxyz", "B");
SourceLoc frontOfA = sourceMgr.getLocForOffset(bufferA, 0);
SourceLoc middleOfA = sourceMgr.getLocForOffset(bufferA, 2);
SourceLoc backOfA = sourceMgr.getLocForOffset(bufferA, 4);
SourceLoc frontOfB = sourceMgr.getLocForOffset(bufferB, 0);
SourceLoc middleOfB = sourceMgr.getLocForOffset(bufferB, 2);
SourceLoc backOfB = sourceMgr.getLocForOffset(bufferB, 4);
ExpectedDiagnostic expectedA[] = {
{frontOfA, "front"},
{frontOfB, "front"},
{middleOfA, "middle"},
{middleOfB, "middle"},
{backOfA, "back"},
{backOfB, "back"}
};
ExpectedDiagnostic expectedUnaffiliated[] = {
{frontOfB, "front"},
{middleOfB, "middle"},
{backOfB, "back"}
};
auto consumerA = llvm::make_unique<ExpectationDiagnosticConsumer>(
nullptr, expectedA);
auto consumerUnaffiliated = llvm::make_unique<ExpectationDiagnosticConsumer>(
consumerA.get(), expectedUnaffiliated);
SmallVector<FileSpecificDiagnosticConsumer::Subconsumer, 2> consumers;
consumers.emplace_back("A", std::move(consumerA));
consumers.emplace_back("", std::move(consumerUnaffiliated));
auto topConsumer =
FileSpecificDiagnosticConsumer::consolidateSubconsumers(consumers);
topConsumer->handleDiagnostic(sourceMgr, frontOfA, DiagnosticKind::Error,
"front", {}, DiagnosticInfo(), SourceLoc());
topConsumer->handleDiagnostic(sourceMgr, frontOfB, DiagnosticKind::Error,
"front", {}, DiagnosticInfo(), SourceLoc());
topConsumer->handleDiagnostic(sourceMgr, middleOfA, DiagnosticKind::Error,
"middle", {}, DiagnosticInfo(), SourceLoc());
topConsumer->handleDiagnostic(sourceMgr, middleOfB, DiagnosticKind::Error,
"middle", {}, DiagnosticInfo(), SourceLoc());
topConsumer->handleDiagnostic(sourceMgr, backOfA, DiagnosticKind::Error,
"back", {}, DiagnosticInfo(), SourceLoc());
topConsumer->handleDiagnostic(sourceMgr, backOfB, DiagnosticKind::Error,
"back", {}, DiagnosticInfo(), SourceLoc());
topConsumer->finishProcessing();
}
示例15: assert
bool CompilerInstance::InitializeSourceManager(const FrontendInputFile &Input,
DiagnosticsEngine &Diags,
FileManager &FileMgr,
SourceManager &SourceMgr,
const FrontendOptions &Opts) {
SrcMgr::CharacteristicKind
Kind = Input.isSystem() ? SrcMgr::C_System : SrcMgr::C_User;
if (Input.isBuffer()) {
SourceMgr.createMainFileIDForMemBuffer(Input.getBuffer(), Kind);
assert(!SourceMgr.getMainFileID().isInvalid() &&
"Couldn't establish MainFileID!");
return true;
}
StringRef InputFile = Input.getFile();
// Figure out where to get and map in the main file.
if (InputFile != "-") {
const FileEntry *File = FileMgr.getFile(InputFile);
if (!File) {
Diags.Report(diag::err_fe_error_reading) << InputFile;
return false;
}
// The natural SourceManager infrastructure can't currently handle named
// pipes, but we would at least like to accept them for the main
// file. Detect them here, read them with the more generic MemoryBuffer
// function, and simply override their contents as we do for STDIN.
if (File->isNamedPipe()) {
OwningPtr<llvm::MemoryBuffer> MB;
if (llvm::error_code ec = llvm::MemoryBuffer::getFile(InputFile, MB)) {
Diags.Report(diag::err_cannot_open_file) << InputFile << ec.message();
return false;
}
// Create a new virtual file that will have the correct size.
File = FileMgr.getVirtualFile(InputFile, MB->getBufferSize(), 0);
SourceMgr.overrideFileContents(File, MB.take());
}
SourceMgr.createMainFileID(File, Kind);
} else {
OwningPtr<llvm::MemoryBuffer> SB;
if (llvm::MemoryBuffer::getSTDIN(SB)) {
// FIXME: Give ec.message() in this diag.
Diags.Report(diag::err_fe_error_reading_stdin);
return false;
}
const FileEntry *File = FileMgr.getVirtualFile(SB->getBufferIdentifier(),
SB->getBufferSize(), 0);
SourceMgr.createMainFileID(File, Kind);
SourceMgr.overrideFileContents(File, SB.take());
}
assert(!SourceMgr.getMainFileID().isInvalid() &&
"Couldn't establish MainFileID!");
return true;
}