blob: 302067a2fb05d29a74eb256d7a6481e0ebdcdfad [file] [log] [blame]
Ted Kremenekc4bbd852011-12-17 05:26:04 +00001//===--- DiagnosticRenderer.cpp - Diagnostic Pretty-Printing --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/DiagnosticRenderer.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000011#include "clang/Basic/DiagnosticOptions.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000012#include "clang/Basic/FileManager.h"
13#include "clang/Basic/SourceManager.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000014#include "clang/Edit/Commit.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/Edit/EditedSource.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000016#include "clang/Edit/EditsReceiver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Lex/Lexer.h"
Eli Friedman34ff0ea2012-11-03 03:36:51 +000018#include "llvm/ADT/SmallSet.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000019#include "llvm/ADT/SmallString.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "llvm/Support/ErrorHandling.h"
21#include "llvm/Support/MemoryBuffer.h"
22#include "llvm/Support/raw_ostream.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000023#include <algorithm>
24using namespace clang;
25
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000026DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
Douglas Gregor811db4e2012-10-23 22:26:28 +000027 DiagnosticOptions *DiagOpts)
28 : LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000029
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000030DiagnosticRenderer::~DiagnosticRenderer() {}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000031
Ted Kremenekf7639e12012-03-06 20:06:33 +000032namespace {
33
34class FixitReceiver : public edit::EditsReceiver {
35 SmallVectorImpl<FixItHint> &MergedFixits;
36
37public:
38 FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
39 : MergedFixits(MergedFixits) { }
Craig Topperafa7cb32014-03-13 06:07:04 +000040 void insert(SourceLocation loc, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000041 MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
42 }
Craig Topperafa7cb32014-03-13 06:07:04 +000043 void replace(CharSourceRange range, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000044 MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
45 }
46};
47
Alexander Kornienkoab9db512015-06-22 23:07:51 +000048}
Ted Kremenekf7639e12012-03-06 20:06:33 +000049
50static void mergeFixits(ArrayRef<FixItHint> FixItHints,
51 const SourceManager &SM, const LangOptions &LangOpts,
52 SmallVectorImpl<FixItHint> &MergedFixits) {
53 edit::Commit commit(SM, LangOpts);
54 for (ArrayRef<FixItHint>::const_iterator
55 I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) {
56 const FixItHint &Hint = *I;
57 if (Hint.CodeToInsert.empty()) {
58 if (Hint.InsertFromRange.isValid())
59 commit.insertFromRange(Hint.RemoveRange.getBegin(),
60 Hint.InsertFromRange, /*afterToken=*/false,
61 Hint.BeforePreviousInsertions);
62 else
63 commit.remove(Hint.RemoveRange);
64 } else {
65 if (Hint.RemoveRange.isTokenRange() ||
66 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
67 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
68 else
69 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
70 /*afterToken=*/false, Hint.BeforePreviousInsertions);
71 }
72 }
73
74 edit::EditedSource Editor(SM, LangOpts);
75 if (Editor.commit(commit)) {
76 FixitReceiver Rec(MergedFixits);
77 Editor.applyRewrites(Rec);
78 }
79}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000080
81void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
82 DiagnosticsEngine::Level Level,
83 StringRef Message,
84 ArrayRef<CharSourceRange> Ranges,
85 ArrayRef<FixItHint> FixItHints,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000086 const SourceManager *SM,
Ted Kremenek0964cca2012-02-14 02:46:00 +000087 DiagOrStoredDiag D) {
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000088 assert(SM || Loc.isInvalid());
Richard Smithc01cca22012-12-05 09:47:49 +000089
Ted Kremenek0964cca2012-02-14 02:46:00 +000090 beginDiagnostic(D, Level);
Richard Smithc01cca22012-12-05 09:47:49 +000091
92 if (!Loc.isValid())
93 // If we have no source location, just emit the diagnostic message.
94 emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, SM, D);
95 else {
Ted Kremenekc4bbd852011-12-17 05:26:04 +000096 // Get the ranges into a local array we can hack on.
97 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
98 Ranges.end());
Richard Smithc01cca22012-12-05 09:47:49 +000099
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000100 SmallVector<FixItHint, 8> MergedFixits;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000101 if (!FixItHints.empty()) {
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000102 mergeFixits(FixItHints, *SM, LangOpts, MergedFixits);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000103 FixItHints = MergedFixits;
104 }
105
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000106 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
107 E = FixItHints.end();
108 I != E; ++I)
109 if (I->RemoveRange.isValid())
110 MutableRanges.push_back(I->RemoveRange);
Richard Smithaebee682012-12-05 06:20:58 +0000111
Richard Smithc01cca22012-12-05 09:47:49 +0000112 SourceLocation UnexpandedLoc = Loc;
Richard Smithaebee682012-12-05 06:20:58 +0000113
Ted Kremenek372735f2012-12-19 01:16:49 +0000114 // Find the ultimate expansion location for the diagnostic.
115 Loc = SM->getFileLoc(Loc);
Richard Smithc01cca22012-12-05 09:47:49 +0000116
117 PresumedLoc PLoc = SM->getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
118
119 // First, if this diagnostic is not in the main file, print out the
120 // "included from" lines.
121 emitIncludeStack(Loc, PLoc, Level, *SM);
122
123 // Next, emit the actual diagnostic message and caret.
124 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, SM, D);
125 emitCaret(Loc, Level, MutableRanges, FixItHints, *SM);
126
127 // If this location is within a macro, walk from UnexpandedLoc up to Loc
128 // and produce a macro backtrace.
129 if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
Richard Trieu97c45b62015-07-28 20:53:46 +0000130 emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints, *SM);
Richard Smithaebee682012-12-05 06:20:58 +0000131 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000132 }
Richard Smithc01cca22012-12-05 09:47:49 +0000133
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000134 LastLoc = Loc;
135 LastLevel = Level;
Richard Smithc01cca22012-12-05 09:47:49 +0000136
Ted Kremenek0964cca2012-02-14 02:46:00 +0000137 endDiagnostic(D, Level);
138}
139
140
141void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
142 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
143 Diag.getRanges(), Diag.getFixIts(),
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000144 Diag.getLocation().isValid() ? &Diag.getLocation().getManager()
Craig Topper49a27902014-05-22 04:46:25 +0000145 : nullptr,
Ted Kremenek0964cca2012-02-14 02:46:00 +0000146 &Diag);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000147}
148
Alp Toker4db87ab2014-06-21 23:31:59 +0000149void DiagnosticRenderer::emitBasicNote(StringRef Message) {
150 emitDiagnosticMessage(
151 SourceLocation(), PresumedLoc(), DiagnosticsEngine::Note, Message,
Craig Topper5fc8fc22014-08-27 06:28:36 +0000152 None, nullptr, DiagOrStoredDiag());
Alp Toker4db87ab2014-06-21 23:31:59 +0000153}
154
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000155/// \brief Prints an include stack when appropriate for a particular
156/// diagnostic level and location.
157///
158/// This routine handles all the logic of suppressing particular include
159/// stacks (such as those for notes) and duplicate include stacks when
160/// repeated warnings occur within the same file. It also handles the logic
161/// of customizing the formatting and display of the include stack.
162///
Douglas Gregor22103e32012-11-30 21:58:49 +0000163/// \param Loc The diagnostic location.
164/// \param PLoc The presumed location of the diagnostic location.
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000165/// \param Level The diagnostic level of the message this stack pertains to.
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000166void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
Douglas Gregor22103e32012-11-30 21:58:49 +0000167 PresumedLoc PLoc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000168 DiagnosticsEngine::Level Level,
169 const SourceManager &SM) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000170 SourceLocation IncludeLoc = PLoc.getIncludeLoc();
171
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000172 // Skip redundant include stacks altogether.
Douglas Gregor22103e32012-11-30 21:58:49 +0000173 if (LastIncludeLoc == IncludeLoc)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000174 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000175
176 LastIncludeLoc = IncludeLoc;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000177
Douglas Gregor811db4e2012-10-23 22:26:28 +0000178 if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000179 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000180
181 if (IncludeLoc.isValid())
182 emitIncludeStackRecursively(IncludeLoc, SM);
183 else {
Douglas Gregor63365432012-11-30 22:11:57 +0000184 emitModuleBuildStack(SM);
Douglas Gregor22103e32012-11-30 21:58:49 +0000185 emitImportStack(Loc, SM);
186 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000187}
188
189/// \brief Helper to recursivly walk up the include stack and print each layer
190/// on the way back down.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000191void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc,
192 const SourceManager &SM) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000193 if (Loc.isInvalid()) {
Douglas Gregor63365432012-11-30 22:11:57 +0000194 emitModuleBuildStack(SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000195 return;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000196 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000197
Richard Smith0b50cb72012-11-14 23:55:25 +0000198 PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000199 if (PLoc.isInvalid())
200 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000201
202 // If this source location was imported from a module, print the module
203 // import stack rather than the
204 // FIXME: We want submodule granularity here.
205 std::pair<SourceLocation, StringRef> Imported = SM.getModuleImportLoc(Loc);
Richard Smitha24ff552015-08-11 00:05:21 +0000206 if (!Imported.second.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000207 // This location was imported by a module. Emit the module import stack.
208 emitImportStackRecursively(Imported.first, Imported.second, SM);
209 return;
210 }
211
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000212 // Emit the other include frames first.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000213 emitIncludeStackRecursively(PLoc.getIncludeLoc(), SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000214
215 // Emit the inclusion text/note.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000216 emitIncludeLocation(Loc, PLoc, SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000217}
218
Douglas Gregor22103e32012-11-30 21:58:49 +0000219/// \brief Emit the module import stack associated with the current location.
220void DiagnosticRenderer::emitImportStack(SourceLocation Loc,
221 const SourceManager &SM) {
222 if (Loc.isInvalid()) {
Douglas Gregor63365432012-11-30 22:11:57 +0000223 emitModuleBuildStack(SM);
Douglas Gregor22103e32012-11-30 21:58:49 +0000224 return;
225 }
226
227 std::pair<SourceLocation, StringRef> NextImportLoc
228 = SM.getModuleImportLoc(Loc);
229 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
230}
231
232/// \brief Helper to recursivly walk up the import stack and print each layer
233/// on the way back down.
234void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc,
235 StringRef ModuleName,
236 const SourceManager &SM) {
Richard Smitha24ff552015-08-11 00:05:21 +0000237 if (ModuleName.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000238 return;
239 }
240
241 PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000242
243 // Emit the other import frames first.
244 std::pair<SourceLocation, StringRef> NextImportLoc
245 = SM.getModuleImportLoc(Loc);
246 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
247
248 // Emit the inclusion text/note.
249 emitImportLocation(Loc, PLoc, ModuleName, SM);
250}
251
Douglas Gregor63365432012-11-30 22:11:57 +0000252/// \brief Emit the module build stack, for cases where a module is (re-)built
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000253/// on demand.
Douglas Gregor63365432012-11-30 22:11:57 +0000254void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
255 ModuleBuildStack Stack = SM.getModuleBuildStack();
256 for (unsigned I = 0, N = Stack.size(); I != N; ++I) {
257 const SourceManager &CurSM = Stack[I].second.getManager();
258 SourceLocation CurLoc = Stack[I].second;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000259 emitBuildingModuleLocation(CurLoc,
260 CurSM.getPresumedLoc(CurLoc,
261 DiagOpts->ShowPresumedLoc),
Douglas Gregor63365432012-11-30 22:11:57 +0000262 Stack[I].first,
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000263 CurSM);
264 }
265}
266
Richard Trieuc3096242015-09-24 01:21:01 +0000267/// A recursive function to trace all possible backtrace locations
268/// to match the \p CaretLocFileID.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000269static SourceLocation
270retrieveMacroLocation(SourceLocation Loc, FileID MacroFileID,
271 FileID CaretFileID,
272 const SmallVectorImpl<FileID> &CommonArgExpansions,
273 bool IsBegin, const SourceManager *SM) {
274 assert(SM->getFileID(Loc) == MacroFileID);
275 if (MacroFileID == CaretFileID)
276 return Loc;
277 if (!Loc.isMacroID())
278 return SourceLocation();
Richard Trieuc3096242015-09-24 01:21:01 +0000279
280 SourceLocation MacroLocation, MacroArgLocation;
281
282 if (SM->isMacroArgExpansion(Loc)) {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000283 // Only look at the immediate spelling location of this macro argument if
284 // the other location in the source range is also present in that expansion.
285 if (std::binary_search(CommonArgExpansions.begin(),
286 CommonArgExpansions.end(), MacroFileID))
287 MacroLocation = SM->getImmediateSpellingLoc(Loc);
288 MacroArgLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
289 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000290 } else {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000291 MacroLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
292 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000293 MacroArgLocation = SM->getImmediateSpellingLoc(Loc);
294 }
295
Reid Klecknerda30cff2015-12-08 01:08:09 +0000296 if (MacroLocation.isValid()) {
297 MacroFileID = SM->getFileID(MacroLocation);
298 MacroLocation =
299 retrieveMacroLocation(MacroLocation, MacroFileID, CaretFileID,
300 CommonArgExpansions, IsBegin, SM);
301 if (MacroLocation.isValid())
302 return MacroLocation;
303 }
Richard Trieuc3096242015-09-24 01:21:01 +0000304
305 MacroFileID = SM->getFileID(MacroArgLocation);
306 return retrieveMacroLocation(MacroArgLocation, MacroFileID, CaretFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000307 CommonArgExpansions, IsBegin, SM);
308}
309
310/// Walk up the chain of macro expansions and collect the FileIDs identifying the
311/// expansions.
312static void getMacroArgExpansionFileIDs(SourceLocation Loc,
313 SmallVectorImpl<FileID> &IDs,
314 bool IsBegin, const SourceManager *SM) {
315 while (Loc.isMacroID()) {
316 if (SM->isMacroArgExpansion(Loc)) {
317 IDs.push_back(SM->getFileID(Loc));
318 Loc = SM->getImmediateSpellingLoc(Loc);
319 } else {
320 auto ExpRange = SM->getImmediateExpansionRange(Loc);
321 Loc = IsBegin ? ExpRange.first : ExpRange.second;
322 }
323 }
324}
325
326/// Collect the expansions of the begin and end locations and compute the set
327/// intersection. Produces a sorted vector of FileIDs in CommonArgExpansions.
328static void computeCommonMacroArgExpansionFileIDs(
329 SourceLocation Begin, SourceLocation End, const SourceManager *SM,
330 SmallVectorImpl<FileID> &CommonArgExpansions) {
331 SmallVector<FileID, 4> BeginArgExpansions;
332 SmallVector<FileID, 4> EndArgExpansions;
333 getMacroArgExpansionFileIDs(Begin, BeginArgExpansions, /*IsBegin=*/true, SM);
334 getMacroArgExpansionFileIDs(End, EndArgExpansions, /*IsBegin=*/false, SM);
335 std::sort(BeginArgExpansions.begin(), BeginArgExpansions.end());
336 std::sort(EndArgExpansions.begin(), EndArgExpansions.end());
337 std::set_intersection(BeginArgExpansions.begin(), BeginArgExpansions.end(),
338 EndArgExpansions.begin(), EndArgExpansions.end(),
339 std::back_inserter(CommonArgExpansions));
Richard Trieuc3096242015-09-24 01:21:01 +0000340}
341
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000342// Helper function to fix up source ranges. It takes in an array of ranges,
343// and outputs an array of ranges where we want to draw the range highlighting
344// around the location specified by CaretLoc.
345//
346// To find locations which correspond to the caret, we crawl the macro caller
347// chain for the beginning and end of each range. If the caret location
348// is in a macro expansion, we search each chain for a location
349// in the same expansion as the caret; otherwise, we crawl to the top of
350// each chain. Two locations are part of the same macro expansion
351// iff the FileID is the same.
352static void mapDiagnosticRanges(
353 SourceLocation CaretLoc,
Richard Smithaebee682012-12-05 06:20:58 +0000354 ArrayRef<CharSourceRange> Ranges,
Richard Smithc01cca22012-12-05 09:47:49 +0000355 SmallVectorImpl<CharSourceRange> &SpellingRanges,
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000356 const SourceManager *SM) {
357 FileID CaretLocFileID = SM->getFileID(CaretLoc);
358
Richard Trieuc3096242015-09-24 01:21:01 +0000359 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
360 if (I->isInvalid()) continue;
361
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000362 SourceLocation Begin = I->getBegin(), End = I->getEnd();
363 bool IsTokenRange = I->isTokenRange();
364
Eli Friedmandea98de2012-11-30 06:19:40 +0000365 FileID BeginFileID = SM->getFileID(Begin);
Nadav Rotemb8937342012-12-13 19:58:10 +0000366 FileID EndFileID = SM->getFileID(End);
Eli Friedmandea98de2012-11-30 06:19:40 +0000367
Nadav Rotemb8937342012-12-13 19:58:10 +0000368 // Find the common parent for the beginning and end of the range.
369
370 // First, crawl the expansion chain for the beginning of the range.
371 llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
372 while (Begin.isMacroID() && BeginFileID != EndFileID) {
373 BeginLocsMap[BeginFileID] = Begin;
374 Begin = SM->getImmediateExpansionRange(Begin).first;
375 BeginFileID = SM->getFileID(Begin);
376 }
377
378 // Then, crawl the expansion chain for the end of the range.
379 if (BeginFileID != EndFileID) {
380 while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000381 End = SM->getImmediateExpansionRange(End).second;
Nadav Rotemb8937342012-12-13 19:58:10 +0000382 EndFileID = SM->getFileID(End);
383 }
384 if (End.isMacroID()) {
385 Begin = BeginLocsMap[EndFileID];
386 BeginFileID = EndFileID;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000387 }
Eli Friedmancdb135a2012-12-13 00:14:59 +0000388 }
389
Richard Trieuc3096242015-09-24 01:21:01 +0000390 // Do the backtracking.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000391 SmallVector<FileID, 4> CommonArgExpansions;
392 computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);
Richard Trieuc3096242015-09-24 01:21:01 +0000393 Begin = retrieveMacroLocation(Begin, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000394 CommonArgExpansions, /*IsBegin=*/true, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000395 End = retrieveMacroLocation(End, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000396 CommonArgExpansions, /*IsBegin=*/false, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000397 if (Begin.isInvalid() || End.isInvalid()) continue;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000398
399 // Return the spelling location of the beginning and end of the range.
400 Begin = SM->getSpellingLoc(Begin);
401 End = SM->getSpellingLoc(End);
Richard Trieuc3096242015-09-24 01:21:01 +0000402
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000403 SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
404 IsTokenRange));
405 }
406}
407
Richard Smithaebee682012-12-05 06:20:58 +0000408void DiagnosticRenderer::emitCaret(SourceLocation Loc,
409 DiagnosticsEngine::Level Level,
410 ArrayRef<CharSourceRange> Ranges,
411 ArrayRef<FixItHint> Hints,
412 const SourceManager &SM) {
413 SmallVector<CharSourceRange, 4> SpellingRanges;
414 mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
415 emitCodeContext(Loc, Level, SpellingRanges, Hints, SM);
416}
417
Richard Trieu97c45b62015-07-28 20:53:46 +0000418/// \brief A helper function for emitMacroExpansion to print the
419/// macro expansion message
420void DiagnosticRenderer::emitSingleMacroExpansion(
421 SourceLocation Loc,
422 DiagnosticsEngine::Level Level,
423 ArrayRef<CharSourceRange> Ranges,
424 const SourceManager &SM) {
Richard Smith7a2d40d2012-12-05 03:18:16 +0000425 // Find the spelling location for the macro definition. We must use the
Richard Trieu97c45b62015-07-28 20:53:46 +0000426 // spelling location here to avoid emitting a macro backtrace for the note.
Richard Trieua1d7ece2015-08-27 23:38:45 +0000427 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
Richard Smith7a2d40d2012-12-05 03:18:16 +0000428
429 // Map the ranges into the FileID of the diagnostic location.
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000430 SmallVector<CharSourceRange, 4> SpellingRanges;
Richard Smith7a2d40d2012-12-05 03:18:16 +0000431 mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000432
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000433 SmallString<100> MessageStorage;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000434 llvm::raw_svector_ostream Message(MessageStorage);
Richard Trieu3a5c9582016-01-26 02:51:55 +0000435 StringRef MacroName =
436 Lexer::getImmediateMacroNameForDiagnostics(Loc, SM, LangOpts);
Richard Smithf89e2e22012-12-05 11:04:55 +0000437 if (MacroName.empty())
438 Message << "expanded from here";
439 else
440 Message << "expanded from macro '" << MacroName << "'";
Richard Trieu97c45b62015-07-28 20:53:46 +0000441
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000442 emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
443 SpellingRanges, None, &SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000444}
445
Richard Trieuc3096242015-09-24 01:21:01 +0000446/// Check that the macro argument location of Loc starts with ArgumentLoc.
447/// The starting location of the macro expansions is used to differeniate
448/// different macro expansions.
449static bool checkLocForMacroArgExpansion(SourceLocation Loc,
450 const SourceManager &SM,
451 SourceLocation ArgumentLoc) {
452 SourceLocation MacroLoc;
453 if (SM.isMacroArgExpansion(Loc, &MacroLoc)) {
454 if (ArgumentLoc == MacroLoc) return true;
455 }
456
457 return false;
458}
459
460/// Check if all the locations in the range have the same macro argument
461/// expansion, and that that expansion starts with ArgumentLoc.
Richard Trieuecd36ee2015-08-12 18:24:59 +0000462static bool checkRangeForMacroArgExpansion(CharSourceRange Range,
Richard Trieuc3096242015-09-24 01:21:01 +0000463 const SourceManager &SM,
464 SourceLocation ArgumentLoc) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000465 SourceLocation BegLoc = Range.getBegin(), EndLoc = Range.getEnd();
466 while (BegLoc != EndLoc) {
Richard Trieuc3096242015-09-24 01:21:01 +0000467 if (!checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000468 return false;
469 BegLoc.getLocWithOffset(1);
470 }
471
Richard Trieuc3096242015-09-24 01:21:01 +0000472 return checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000473}
474
Richard Trieuc3096242015-09-24 01:21:01 +0000475/// A helper function to check if the current ranges are all inside the same
476/// macro argument expansion as Loc.
Richard Trieuecd36ee2015-08-12 18:24:59 +0000477static bool checkRangesForMacroArgExpansion(SourceLocation Loc,
478 ArrayRef<CharSourceRange> Ranges,
479 const SourceManager &SM) {
480 assert(Loc.isMacroID() && "Must be a macro expansion!");
481
482 SmallVector<CharSourceRange, 4> SpellingRanges;
483 mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
484
Richard Trieuc3096242015-09-24 01:21:01 +0000485 /// Count all valid ranges.
486 unsigned ValidCount = 0;
487 for (auto I : Ranges)
488 if (I.isValid()) ValidCount++;
489
490 if (ValidCount > SpellingRanges.size())
Richard Trieuecd36ee2015-08-12 18:24:59 +0000491 return false;
492
Richard Trieuc3096242015-09-24 01:21:01 +0000493 /// To store the source location of the argument location.
494 SourceLocation ArgumentLoc;
495
496 /// Set the ArgumentLoc to the beginning location of the expansion of Loc
497 /// so to check if the ranges expands to the same beginning location.
498 if (!SM.isMacroArgExpansion(Loc,&ArgumentLoc))
499 return false;
500
501 for (auto I = SpellingRanges.begin(), E = SpellingRanges.end(); I != E; ++I) {
502 if (!checkRangeForMacroArgExpansion(*I, SM, ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000503 return false;
Richard Trieuc3096242015-09-24 01:21:01 +0000504 }
Richard Trieuecd36ee2015-08-12 18:24:59 +0000505
506 return true;
507}
508
Richard Trieu97c45b62015-07-28 20:53:46 +0000509/// \brief Recursively emit notes for each macro expansion and caret
510/// diagnostics where appropriate.
511///
512/// Walks up the macro expansion stack printing expansion notes, the code
513/// snippet, caret, underlines and FixItHint display as appropriate at each
514/// level.
515///
516/// \param Loc The location for this caret.
517/// \param Level The diagnostic level currently being emitted.
518/// \param Ranges The underlined ranges for this code snippet.
519/// \param Hints The FixIt hints active for this diagnostic.
520void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc,
521 DiagnosticsEngine::Level Level,
522 ArrayRef<CharSourceRange> Ranges,
523 ArrayRef<FixItHint> Hints,
524 const SourceManager &SM) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000525 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000526
527 // Produce a stack of macro backtraces.
528 SmallVector<SourceLocation, 8> LocationStack;
Richard Trieuecd36ee2015-08-12 18:24:59 +0000529 unsigned IgnoredEnd = 0;
Richard Trieu97c45b62015-07-28 20:53:46 +0000530 while (Loc.isMacroID()) {
Richard Trieua1d7ece2015-08-27 23:38:45 +0000531 // If this is the expansion of a macro argument, point the caret at the
532 // use of the argument in the definition of the macro, not the expansion.
533 if (SM.isMacroArgExpansion(Loc))
534 LocationStack.push_back(SM.getImmediateExpansionRange(Loc).first);
535 else
536 LocationStack.push_back(Loc);
537
Richard Trieuecd36ee2015-08-12 18:24:59 +0000538 if (checkRangesForMacroArgExpansion(Loc, Ranges, SM))
539 IgnoredEnd = LocationStack.size();
540
Richard Trieu97c45b62015-07-28 20:53:46 +0000541 Loc = SM.getImmediateMacroCallerLoc(Loc);
Richard Trieua1d7ece2015-08-27 23:38:45 +0000542
543 // Once the location no longer points into a macro, try stepping through
544 // the last found location. This sometimes produces additional useful
545 // backtraces.
546 if (Loc.isFileID())
547 Loc = SM.getImmediateMacroCallerLoc(LocationStack.back());
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000548 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000549 }
550
Richard Trieuecd36ee2015-08-12 18:24:59 +0000551 LocationStack.erase(LocationStack.begin(),
552 LocationStack.begin() + IgnoredEnd);
553
Richard Trieu97c45b62015-07-28 20:53:46 +0000554 unsigned MacroDepth = LocationStack.size();
555 unsigned MacroLimit = DiagOpts->MacroBacktraceLimit;
556 if (MacroDepth <= MacroLimit || MacroLimit == 0) {
557 for (auto I = LocationStack.rbegin(), E = LocationStack.rend();
558 I != E; ++I)
559 emitSingleMacroExpansion(*I, Level, Ranges, SM);
560 return;
561 }
562
563 unsigned MacroStartMessages = MacroLimit / 2;
564 unsigned MacroEndMessages = MacroLimit / 2 + MacroLimit % 2;
565
566 for (auto I = LocationStack.rbegin(),
567 E = LocationStack.rbegin() + MacroStartMessages;
568 I != E; ++I)
569 emitSingleMacroExpansion(*I, Level, Ranges, SM);
570
571 SmallString<200> MessageStorage;
572 llvm::raw_svector_ostream Message(MessageStorage);
573 Message << "(skipping " << (MacroDepth - MacroLimit)
574 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
575 "see all)";
576 emitBasicNote(Message.str());
577
578 for (auto I = LocationStack.rend() - MacroEndMessages,
579 E = LocationStack.rend();
580 I != E; ++I)
581 emitSingleMacroExpansion(*I, Level, Ranges, SM);
582}
583
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000584DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
Ted Kremenek0964cca2012-02-14 02:46:00 +0000585
586void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000587 PresumedLoc PLoc,
588 const SourceManager &SM) {
Ted Kremenek0964cca2012-02-14 02:46:00 +0000589 // Generate a note indicating the include location.
590 SmallString<200> MessageStorage;
591 llvm::raw_svector_ostream Message(MessageStorage);
592 Message << "in file included from " << PLoc.getFilename() << ':'
593 << PLoc.getLine() << ":";
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000594 emitNote(Loc, Message.str(), &SM);
Ted Kremenek0964cca2012-02-14 02:46:00 +0000595}
596
Douglas Gregor22103e32012-11-30 21:58:49 +0000597void DiagnosticNoteRenderer::emitImportLocation(SourceLocation Loc,
598 PresumedLoc PLoc,
599 StringRef ModuleName,
600 const SourceManager &SM) {
601 // Generate a note indicating the include location.
602 SmallString<200> MessageStorage;
603 llvm::raw_svector_ostream Message(MessageStorage);
Richard Smitha24ff552015-08-11 00:05:21 +0000604 Message << "in module '" << ModuleName;
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000605 if (PLoc.isValid())
Richard Smitha24ff552015-08-11 00:05:21 +0000606 Message << "' imported from " << PLoc.getFilename() << ':'
607 << PLoc.getLine();
608 Message << ":";
Douglas Gregor22103e32012-11-30 21:58:49 +0000609 emitNote(Loc, Message.str(), &SM);
610}
611
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000612void
613DiagnosticNoteRenderer::emitBuildingModuleLocation(SourceLocation Loc,
614 PresumedLoc PLoc,
615 StringRef ModuleName,
616 const SourceManager &SM) {
617 // Generate a note indicating the include location.
618 SmallString<200> MessageStorage;
619 llvm::raw_svector_ostream Message(MessageStorage);
Richard Smith7bea1d42014-03-05 20:55:36 +0000620 if (PLoc.getFilename())
621 Message << "while building module '" << ModuleName << "' imported from "
622 << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
623 else
Jordan Rose6dcdaa62014-07-26 01:22:02 +0000624 Message << "while building module '" << ModuleName << "':";
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000625 emitNote(Loc, Message.str(), &SM);
626}