blob: 177feac974411de300e57c2d9ed7c13061b80c0e [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/SourceManager.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000013#include "clang/Edit/Commit.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Edit/EditedSource.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000015#include "clang/Edit/EditsReceiver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/Lex/Lexer.h"
Eli Friedman34ff0ea2012-11-03 03:36:51 +000017#include "llvm/ADT/SmallSet.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000018#include "llvm/ADT/SmallString.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "llvm/Support/ErrorHandling.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "llvm/Support/raw_ostream.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000021#include <algorithm>
22using namespace clang;
23
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000024DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
Douglas Gregor811db4e2012-10-23 22:26:28 +000025 DiagnosticOptions *DiagOpts)
26 : LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000027
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000028DiagnosticRenderer::~DiagnosticRenderer() {}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000029
Ted Kremenekf7639e12012-03-06 20:06:33 +000030namespace {
31
32class FixitReceiver : public edit::EditsReceiver {
33 SmallVectorImpl<FixItHint> &MergedFixits;
34
35public:
36 FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
37 : MergedFixits(MergedFixits) { }
Craig Topperafa7cb32014-03-13 06:07:04 +000038 void insert(SourceLocation loc, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000039 MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
40 }
Craig Topperafa7cb32014-03-13 06:07:04 +000041 void replace(CharSourceRange range, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000042 MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
43 }
44};
45
Alexander Kornienkoab9db512015-06-22 23:07:51 +000046}
Ted Kremenekf7639e12012-03-06 20:06:33 +000047
48static void mergeFixits(ArrayRef<FixItHint> FixItHints,
49 const SourceManager &SM, const LangOptions &LangOpts,
50 SmallVectorImpl<FixItHint> &MergedFixits) {
51 edit::Commit commit(SM, LangOpts);
52 for (ArrayRef<FixItHint>::const_iterator
53 I = FixItHints.begin(), E = FixItHints.end(); I != E; ++I) {
54 const FixItHint &Hint = *I;
55 if (Hint.CodeToInsert.empty()) {
56 if (Hint.InsertFromRange.isValid())
57 commit.insertFromRange(Hint.RemoveRange.getBegin(),
58 Hint.InsertFromRange, /*afterToken=*/false,
59 Hint.BeforePreviousInsertions);
60 else
61 commit.remove(Hint.RemoveRange);
62 } else {
63 if (Hint.RemoveRange.isTokenRange() ||
64 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
65 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
66 else
67 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
68 /*afterToken=*/false, Hint.BeforePreviousInsertions);
69 }
70 }
71
72 edit::EditedSource Editor(SM, LangOpts);
73 if (Editor.commit(commit)) {
74 FixitReceiver Rec(MergedFixits);
75 Editor.applyRewrites(Rec);
76 }
77}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000078
79void DiagnosticRenderer::emitDiagnostic(SourceLocation Loc,
80 DiagnosticsEngine::Level Level,
81 StringRef Message,
82 ArrayRef<CharSourceRange> Ranges,
83 ArrayRef<FixItHint> FixItHints,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000084 const SourceManager *SM,
Ted Kremenek0964cca2012-02-14 02:46:00 +000085 DiagOrStoredDiag D) {
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000086 assert(SM || Loc.isInvalid());
Richard Smithc01cca22012-12-05 09:47:49 +000087
Ted Kremenek0964cca2012-02-14 02:46:00 +000088 beginDiagnostic(D, Level);
Richard Smithc01cca22012-12-05 09:47:49 +000089
90 if (!Loc.isValid())
91 // If we have no source location, just emit the diagnostic message.
92 emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, SM, D);
93 else {
Ted Kremenekc4bbd852011-12-17 05:26:04 +000094 // Get the ranges into a local array we can hack on.
95 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
96 Ranges.end());
Richard Smithc01cca22012-12-05 09:47:49 +000097
Dmitri Gribenkof8579502013-01-12 19:30:44 +000098 SmallVector<FixItHint, 8> MergedFixits;
Ted Kremenekf7639e12012-03-06 20:06:33 +000099 if (!FixItHints.empty()) {
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000100 mergeFixits(FixItHints, *SM, LangOpts, MergedFixits);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000101 FixItHints = MergedFixits;
102 }
103
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000104 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
105 E = FixItHints.end();
106 I != E; ++I)
107 if (I->RemoveRange.isValid())
108 MutableRanges.push_back(I->RemoveRange);
Richard Smithaebee682012-12-05 06:20:58 +0000109
Richard Smithc01cca22012-12-05 09:47:49 +0000110 SourceLocation UnexpandedLoc = Loc;
Richard Smithaebee682012-12-05 06:20:58 +0000111
Ted Kremenek372735f2012-12-19 01:16:49 +0000112 // Find the ultimate expansion location for the diagnostic.
113 Loc = SM->getFileLoc(Loc);
Richard Smithc01cca22012-12-05 09:47:49 +0000114
115 PresumedLoc PLoc = SM->getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
116
117 // First, if this diagnostic is not in the main file, print out the
118 // "included from" lines.
119 emitIncludeStack(Loc, PLoc, Level, *SM);
120
121 // Next, emit the actual diagnostic message and caret.
122 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, SM, D);
123 emitCaret(Loc, Level, MutableRanges, FixItHints, *SM);
124
125 // If this location is within a macro, walk from UnexpandedLoc up to Loc
126 // and produce a macro backtrace.
127 if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
Richard Trieu97c45b62015-07-28 20:53:46 +0000128 emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints, *SM);
Richard Smithaebee682012-12-05 06:20:58 +0000129 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000130 }
Richard Smithc01cca22012-12-05 09:47:49 +0000131
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000132 LastLoc = Loc;
133 LastLevel = Level;
Richard Smithc01cca22012-12-05 09:47:49 +0000134
Ted Kremenek0964cca2012-02-14 02:46:00 +0000135 endDiagnostic(D, Level);
136}
137
138
139void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
140 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
141 Diag.getRanges(), Diag.getFixIts(),
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000142 Diag.getLocation().isValid() ? &Diag.getLocation().getManager()
Craig Topper49a27902014-05-22 04:46:25 +0000143 : nullptr,
Ted Kremenek0964cca2012-02-14 02:46:00 +0000144 &Diag);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000145}
146
Alp Toker4db87ab2014-06-21 23:31:59 +0000147void DiagnosticRenderer::emitBasicNote(StringRef Message) {
148 emitDiagnosticMessage(
149 SourceLocation(), PresumedLoc(), DiagnosticsEngine::Note, Message,
Craig Topper5fc8fc22014-08-27 06:28:36 +0000150 None, nullptr, DiagOrStoredDiag());
Alp Toker4db87ab2014-06-21 23:31:59 +0000151}
152
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000153/// \brief Prints an include stack when appropriate for a particular
154/// diagnostic level and location.
155///
156/// This routine handles all the logic of suppressing particular include
157/// stacks (such as those for notes) and duplicate include stacks when
158/// repeated warnings occur within the same file. It also handles the logic
159/// of customizing the formatting and display of the include stack.
160///
Douglas Gregor22103e32012-11-30 21:58:49 +0000161/// \param Loc The diagnostic location.
162/// \param PLoc The presumed location of the diagnostic location.
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000163/// \param Level The diagnostic level of the message this stack pertains to.
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000164void DiagnosticRenderer::emitIncludeStack(SourceLocation Loc,
Douglas Gregor22103e32012-11-30 21:58:49 +0000165 PresumedLoc PLoc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000166 DiagnosticsEngine::Level Level,
167 const SourceManager &SM) {
Richard Smith41e66292016-04-28 18:26:32 +0000168 SourceLocation IncludeLoc =
169 PLoc.isInvalid() ? SourceLocation() : PLoc.getIncludeLoc();
Douglas Gregor22103e32012-11-30 21:58:49 +0000170
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000171 // Skip redundant include stacks altogether.
Douglas Gregor22103e32012-11-30 21:58:49 +0000172 if (LastIncludeLoc == IncludeLoc)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000173 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000174
175 LastIncludeLoc = IncludeLoc;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000176
Douglas Gregor811db4e2012-10-23 22:26:28 +0000177 if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000178 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000179
180 if (IncludeLoc.isValid())
181 emitIncludeStackRecursively(IncludeLoc, SM);
182 else {
Douglas Gregor63365432012-11-30 22:11:57 +0000183 emitModuleBuildStack(SM);
Douglas Gregor22103e32012-11-30 21:58:49 +0000184 emitImportStack(Loc, SM);
185 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000186}
187
188/// \brief Helper to recursivly walk up the include stack and print each layer
189/// on the way back down.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000190void DiagnosticRenderer::emitIncludeStackRecursively(SourceLocation Loc,
191 const SourceManager &SM) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000192 if (Loc.isInvalid()) {
Douglas Gregor63365432012-11-30 22:11:57 +0000193 emitModuleBuildStack(SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000194 return;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000195 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000196
Richard Smith0b50cb72012-11-14 23:55:25 +0000197 PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000198 if (PLoc.isInvalid())
199 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000200
201 // If this source location was imported from a module, print the module
202 // import stack rather than the
203 // FIXME: We want submodule granularity here.
204 std::pair<SourceLocation, StringRef> Imported = SM.getModuleImportLoc(Loc);
Richard Smitha24ff552015-08-11 00:05:21 +0000205 if (!Imported.second.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000206 // This location was imported by a module. Emit the module import stack.
207 emitImportStackRecursively(Imported.first, Imported.second, SM);
208 return;
209 }
210
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000211 // Emit the other include frames first.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000212 emitIncludeStackRecursively(PLoc.getIncludeLoc(), SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000213
214 // Emit the inclusion text/note.
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000215 emitIncludeLocation(Loc, PLoc, SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000216}
217
Douglas Gregor22103e32012-11-30 21:58:49 +0000218/// \brief Emit the module import stack associated with the current location.
219void DiagnosticRenderer::emitImportStack(SourceLocation Loc,
220 const SourceManager &SM) {
221 if (Loc.isInvalid()) {
Douglas Gregor63365432012-11-30 22:11:57 +0000222 emitModuleBuildStack(SM);
Douglas Gregor22103e32012-11-30 21:58:49 +0000223 return;
224 }
225
226 std::pair<SourceLocation, StringRef> NextImportLoc
227 = SM.getModuleImportLoc(Loc);
228 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
229}
230
231/// \brief Helper to recursivly walk up the import stack and print each layer
232/// on the way back down.
233void DiagnosticRenderer::emitImportStackRecursively(SourceLocation Loc,
234 StringRef ModuleName,
235 const SourceManager &SM) {
Richard Smitha24ff552015-08-11 00:05:21 +0000236 if (ModuleName.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000237 return;
238 }
239
240 PresumedLoc PLoc = SM.getPresumedLoc(Loc, DiagOpts->ShowPresumedLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000241
242 // Emit the other import frames first.
243 std::pair<SourceLocation, StringRef> NextImportLoc
244 = SM.getModuleImportLoc(Loc);
245 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second, SM);
246
247 // Emit the inclusion text/note.
248 emitImportLocation(Loc, PLoc, ModuleName, SM);
249}
250
Douglas Gregor63365432012-11-30 22:11:57 +0000251/// \brief Emit the module build stack, for cases where a module is (re-)built
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000252/// on demand.
Douglas Gregor63365432012-11-30 22:11:57 +0000253void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
254 ModuleBuildStack Stack = SM.getModuleBuildStack();
255 for (unsigned I = 0, N = Stack.size(); I != N; ++I) {
256 const SourceManager &CurSM = Stack[I].second.getManager();
257 SourceLocation CurLoc = Stack[I].second;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000258 emitBuildingModuleLocation(CurLoc,
259 CurSM.getPresumedLoc(CurLoc,
260 DiagOpts->ShowPresumedLoc),
Douglas Gregor63365432012-11-30 22:11:57 +0000261 Stack[I].first,
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000262 CurSM);
263 }
264}
265
Richard Trieuc3096242015-09-24 01:21:01 +0000266/// A recursive function to trace all possible backtrace locations
267/// to match the \p CaretLocFileID.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000268static SourceLocation
269retrieveMacroLocation(SourceLocation Loc, FileID MacroFileID,
270 FileID CaretFileID,
271 const SmallVectorImpl<FileID> &CommonArgExpansions,
272 bool IsBegin, const SourceManager *SM) {
273 assert(SM->getFileID(Loc) == MacroFileID);
274 if (MacroFileID == CaretFileID)
275 return Loc;
276 if (!Loc.isMacroID())
277 return SourceLocation();
Richard Trieuc3096242015-09-24 01:21:01 +0000278
279 SourceLocation MacroLocation, MacroArgLocation;
280
281 if (SM->isMacroArgExpansion(Loc)) {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000282 // Only look at the immediate spelling location of this macro argument if
283 // the other location in the source range is also present in that expansion.
284 if (std::binary_search(CommonArgExpansions.begin(),
285 CommonArgExpansions.end(), MacroFileID))
286 MacroLocation = SM->getImmediateSpellingLoc(Loc);
287 MacroArgLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
288 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000289 } else {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000290 MacroLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
291 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000292 MacroArgLocation = SM->getImmediateSpellingLoc(Loc);
293 }
294
Reid Klecknerda30cff2015-12-08 01:08:09 +0000295 if (MacroLocation.isValid()) {
296 MacroFileID = SM->getFileID(MacroLocation);
297 MacroLocation =
298 retrieveMacroLocation(MacroLocation, MacroFileID, CaretFileID,
299 CommonArgExpansions, IsBegin, SM);
300 if (MacroLocation.isValid())
301 return MacroLocation;
302 }
Richard Trieuc3096242015-09-24 01:21:01 +0000303
304 MacroFileID = SM->getFileID(MacroArgLocation);
305 return retrieveMacroLocation(MacroArgLocation, MacroFileID, CaretFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000306 CommonArgExpansions, IsBegin, SM);
307}
308
309/// Walk up the chain of macro expansions and collect the FileIDs identifying the
310/// expansions.
311static void getMacroArgExpansionFileIDs(SourceLocation Loc,
312 SmallVectorImpl<FileID> &IDs,
313 bool IsBegin, const SourceManager *SM) {
314 while (Loc.isMacroID()) {
315 if (SM->isMacroArgExpansion(Loc)) {
316 IDs.push_back(SM->getFileID(Loc));
317 Loc = SM->getImmediateSpellingLoc(Loc);
318 } else {
319 auto ExpRange = SM->getImmediateExpansionRange(Loc);
320 Loc = IsBegin ? ExpRange.first : ExpRange.second;
321 }
322 }
323}
324
325/// Collect the expansions of the begin and end locations and compute the set
326/// intersection. Produces a sorted vector of FileIDs in CommonArgExpansions.
327static void computeCommonMacroArgExpansionFileIDs(
328 SourceLocation Begin, SourceLocation End, const SourceManager *SM,
329 SmallVectorImpl<FileID> &CommonArgExpansions) {
330 SmallVector<FileID, 4> BeginArgExpansions;
331 SmallVector<FileID, 4> EndArgExpansions;
332 getMacroArgExpansionFileIDs(Begin, BeginArgExpansions, /*IsBegin=*/true, SM);
333 getMacroArgExpansionFileIDs(End, EndArgExpansions, /*IsBegin=*/false, SM);
334 std::sort(BeginArgExpansions.begin(), BeginArgExpansions.end());
335 std::sort(EndArgExpansions.begin(), EndArgExpansions.end());
336 std::set_intersection(BeginArgExpansions.begin(), BeginArgExpansions.end(),
337 EndArgExpansions.begin(), EndArgExpansions.end(),
338 std::back_inserter(CommonArgExpansions));
Richard Trieuc3096242015-09-24 01:21:01 +0000339}
340
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000341// Helper function to fix up source ranges. It takes in an array of ranges,
342// and outputs an array of ranges where we want to draw the range highlighting
343// around the location specified by CaretLoc.
344//
345// To find locations which correspond to the caret, we crawl the macro caller
346// chain for the beginning and end of each range. If the caret location
347// is in a macro expansion, we search each chain for a location
348// in the same expansion as the caret; otherwise, we crawl to the top of
349// each chain. Two locations are part of the same macro expansion
350// iff the FileID is the same.
351static void mapDiagnosticRanges(
352 SourceLocation CaretLoc,
Richard Smithaebee682012-12-05 06:20:58 +0000353 ArrayRef<CharSourceRange> Ranges,
Richard Smithc01cca22012-12-05 09:47:49 +0000354 SmallVectorImpl<CharSourceRange> &SpellingRanges,
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000355 const SourceManager *SM) {
356 FileID CaretLocFileID = SM->getFileID(CaretLoc);
357
Richard Trieuc3096242015-09-24 01:21:01 +0000358 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
359 if (I->isInvalid()) continue;
360
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000361 SourceLocation Begin = I->getBegin(), End = I->getEnd();
362 bool IsTokenRange = I->isTokenRange();
363
Eli Friedmandea98de2012-11-30 06:19:40 +0000364 FileID BeginFileID = SM->getFileID(Begin);
Nadav Rotemb8937342012-12-13 19:58:10 +0000365 FileID EndFileID = SM->getFileID(End);
Eli Friedmandea98de2012-11-30 06:19:40 +0000366
Nadav Rotemb8937342012-12-13 19:58:10 +0000367 // Find the common parent for the beginning and end of the range.
368
369 // First, crawl the expansion chain for the beginning of the range.
370 llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
371 while (Begin.isMacroID() && BeginFileID != EndFileID) {
372 BeginLocsMap[BeginFileID] = Begin;
373 Begin = SM->getImmediateExpansionRange(Begin).first;
374 BeginFileID = SM->getFileID(Begin);
375 }
376
377 // Then, crawl the expansion chain for the end of the range.
378 if (BeginFileID != EndFileID) {
379 while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000380 End = SM->getImmediateExpansionRange(End).second;
Nadav Rotemb8937342012-12-13 19:58:10 +0000381 EndFileID = SM->getFileID(End);
382 }
383 if (End.isMacroID()) {
384 Begin = BeginLocsMap[EndFileID];
385 BeginFileID = EndFileID;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000386 }
Eli Friedmancdb135a2012-12-13 00:14:59 +0000387 }
388
Richard Trieuc3096242015-09-24 01:21:01 +0000389 // Do the backtracking.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000390 SmallVector<FileID, 4> CommonArgExpansions;
391 computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);
Richard Trieuc3096242015-09-24 01:21:01 +0000392 Begin = retrieveMacroLocation(Begin, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000393 CommonArgExpansions, /*IsBegin=*/true, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000394 End = retrieveMacroLocation(End, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000395 CommonArgExpansions, /*IsBegin=*/false, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000396 if (Begin.isInvalid() || End.isInvalid()) continue;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000397
398 // Return the spelling location of the beginning and end of the range.
399 Begin = SM->getSpellingLoc(Begin);
400 End = SM->getSpellingLoc(End);
Richard Trieuc3096242015-09-24 01:21:01 +0000401
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000402 SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
403 IsTokenRange));
404 }
405}
406
Richard Smithaebee682012-12-05 06:20:58 +0000407void DiagnosticRenderer::emitCaret(SourceLocation Loc,
408 DiagnosticsEngine::Level Level,
409 ArrayRef<CharSourceRange> Ranges,
410 ArrayRef<FixItHint> Hints,
411 const SourceManager &SM) {
412 SmallVector<CharSourceRange, 4> SpellingRanges;
413 mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
414 emitCodeContext(Loc, Level, SpellingRanges, Hints, SM);
415}
416
Richard Trieu97c45b62015-07-28 20:53:46 +0000417/// \brief A helper function for emitMacroExpansion to print the
418/// macro expansion message
419void DiagnosticRenderer::emitSingleMacroExpansion(
420 SourceLocation Loc,
421 DiagnosticsEngine::Level Level,
422 ArrayRef<CharSourceRange> Ranges,
423 const SourceManager &SM) {
Richard Smith7a2d40d2012-12-05 03:18:16 +0000424 // Find the spelling location for the macro definition. We must use the
Richard Trieu97c45b62015-07-28 20:53:46 +0000425 // spelling location here to avoid emitting a macro backtrace for the note.
Richard Trieua1d7ece2015-08-27 23:38:45 +0000426 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
Richard Smith7a2d40d2012-12-05 03:18:16 +0000427
428 // Map the ranges into the FileID of the diagnostic location.
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000429 SmallVector<CharSourceRange, 4> SpellingRanges;
Richard Smith7a2d40d2012-12-05 03:18:16 +0000430 mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000431
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000432 SmallString<100> MessageStorage;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000433 llvm::raw_svector_ostream Message(MessageStorage);
Richard Trieu3a5c9582016-01-26 02:51:55 +0000434 StringRef MacroName =
435 Lexer::getImmediateMacroNameForDiagnostics(Loc, SM, LangOpts);
Richard Smithf89e2e22012-12-05 11:04:55 +0000436 if (MacroName.empty())
437 Message << "expanded from here";
438 else
439 Message << "expanded from macro '" << MacroName << "'";
Richard Trieu97c45b62015-07-28 20:53:46 +0000440
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000441 emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
442 SpellingRanges, None, &SM);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000443}
444
Richard Trieuc3096242015-09-24 01:21:01 +0000445/// Check that the macro argument location of Loc starts with ArgumentLoc.
446/// The starting location of the macro expansions is used to differeniate
447/// different macro expansions.
448static bool checkLocForMacroArgExpansion(SourceLocation Loc,
449 const SourceManager &SM,
450 SourceLocation ArgumentLoc) {
451 SourceLocation MacroLoc;
452 if (SM.isMacroArgExpansion(Loc, &MacroLoc)) {
453 if (ArgumentLoc == MacroLoc) return true;
454 }
455
456 return false;
457}
458
459/// Check if all the locations in the range have the same macro argument
460/// expansion, and that that expansion starts with ArgumentLoc.
Richard Trieuecd36ee2015-08-12 18:24:59 +0000461static bool checkRangeForMacroArgExpansion(CharSourceRange Range,
Richard Trieuc3096242015-09-24 01:21:01 +0000462 const SourceManager &SM,
463 SourceLocation ArgumentLoc) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000464 SourceLocation BegLoc = Range.getBegin(), EndLoc = Range.getEnd();
465 while (BegLoc != EndLoc) {
Richard Trieuc3096242015-09-24 01:21:01 +0000466 if (!checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000467 return false;
468 BegLoc.getLocWithOffset(1);
469 }
470
Richard Trieuc3096242015-09-24 01:21:01 +0000471 return checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000472}
473
Richard Trieuc3096242015-09-24 01:21:01 +0000474/// A helper function to check if the current ranges are all inside the same
475/// macro argument expansion as Loc.
Richard Trieuecd36ee2015-08-12 18:24:59 +0000476static bool checkRangesForMacroArgExpansion(SourceLocation Loc,
477 ArrayRef<CharSourceRange> Ranges,
478 const SourceManager &SM) {
479 assert(Loc.isMacroID() && "Must be a macro expansion!");
480
481 SmallVector<CharSourceRange, 4> SpellingRanges;
482 mapDiagnosticRanges(Loc, Ranges, SpellingRanges, &SM);
483
Richard Trieuc3096242015-09-24 01:21:01 +0000484 /// Count all valid ranges.
485 unsigned ValidCount = 0;
486 for (auto I : Ranges)
487 if (I.isValid()) ValidCount++;
488
489 if (ValidCount > SpellingRanges.size())
Richard Trieuecd36ee2015-08-12 18:24:59 +0000490 return false;
491
Richard Trieuc3096242015-09-24 01:21:01 +0000492 /// To store the source location of the argument location.
493 SourceLocation ArgumentLoc;
494
495 /// Set the ArgumentLoc to the beginning location of the expansion of Loc
496 /// so to check if the ranges expands to the same beginning location.
497 if (!SM.isMacroArgExpansion(Loc,&ArgumentLoc))
498 return false;
499
500 for (auto I = SpellingRanges.begin(), E = SpellingRanges.end(); I != E; ++I) {
501 if (!checkRangeForMacroArgExpansion(*I, SM, ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000502 return false;
Richard Trieuc3096242015-09-24 01:21:01 +0000503 }
Richard Trieuecd36ee2015-08-12 18:24:59 +0000504
505 return true;
506}
507
Richard Trieu97c45b62015-07-28 20:53:46 +0000508/// \brief Recursively emit notes for each macro expansion and caret
509/// diagnostics where appropriate.
510///
511/// Walks up the macro expansion stack printing expansion notes, the code
512/// snippet, caret, underlines and FixItHint display as appropriate at each
513/// level.
514///
515/// \param Loc The location for this caret.
516/// \param Level The diagnostic level currently being emitted.
517/// \param Ranges The underlined ranges for this code snippet.
518/// \param Hints The FixIt hints active for this diagnostic.
519void DiagnosticRenderer::emitMacroExpansions(SourceLocation Loc,
520 DiagnosticsEngine::Level Level,
521 ArrayRef<CharSourceRange> Ranges,
522 ArrayRef<FixItHint> Hints,
523 const SourceManager &SM) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000524 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000525
526 // Produce a stack of macro backtraces.
527 SmallVector<SourceLocation, 8> LocationStack;
Richard Trieuecd36ee2015-08-12 18:24:59 +0000528 unsigned IgnoredEnd = 0;
Richard Trieu97c45b62015-07-28 20:53:46 +0000529 while (Loc.isMacroID()) {
Richard Trieua1d7ece2015-08-27 23:38:45 +0000530 // If this is the expansion of a macro argument, point the caret at the
531 // use of the argument in the definition of the macro, not the expansion.
532 if (SM.isMacroArgExpansion(Loc))
533 LocationStack.push_back(SM.getImmediateExpansionRange(Loc).first);
534 else
535 LocationStack.push_back(Loc);
536
Richard Trieuecd36ee2015-08-12 18:24:59 +0000537 if (checkRangesForMacroArgExpansion(Loc, Ranges, SM))
538 IgnoredEnd = LocationStack.size();
539
Richard Trieu97c45b62015-07-28 20:53:46 +0000540 Loc = SM.getImmediateMacroCallerLoc(Loc);
Richard Trieua1d7ece2015-08-27 23:38:45 +0000541
542 // Once the location no longer points into a macro, try stepping through
543 // the last found location. This sometimes produces additional useful
544 // backtraces.
545 if (Loc.isFileID())
546 Loc = SM.getImmediateMacroCallerLoc(LocationStack.back());
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000547 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000548 }
549
Richard Trieuecd36ee2015-08-12 18:24:59 +0000550 LocationStack.erase(LocationStack.begin(),
551 LocationStack.begin() + IgnoredEnd);
552
Richard Trieu97c45b62015-07-28 20:53:46 +0000553 unsigned MacroDepth = LocationStack.size();
554 unsigned MacroLimit = DiagOpts->MacroBacktraceLimit;
555 if (MacroDepth <= MacroLimit || MacroLimit == 0) {
556 for (auto I = LocationStack.rbegin(), E = LocationStack.rend();
557 I != E; ++I)
558 emitSingleMacroExpansion(*I, Level, Ranges, SM);
559 return;
560 }
561
562 unsigned MacroStartMessages = MacroLimit / 2;
563 unsigned MacroEndMessages = MacroLimit / 2 + MacroLimit % 2;
564
565 for (auto I = LocationStack.rbegin(),
566 E = LocationStack.rbegin() + MacroStartMessages;
567 I != E; ++I)
568 emitSingleMacroExpansion(*I, Level, Ranges, SM);
569
570 SmallString<200> MessageStorage;
571 llvm::raw_svector_ostream Message(MessageStorage);
572 Message << "(skipping " << (MacroDepth - MacroLimit)
573 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
574 "see all)";
575 emitBasicNote(Message.str());
576
577 for (auto I = LocationStack.rend() - MacroEndMessages,
578 E = LocationStack.rend();
579 I != E; ++I)
580 emitSingleMacroExpansion(*I, Level, Ranges, SM);
581}
582
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000583DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
Ted Kremenek0964cca2012-02-14 02:46:00 +0000584
585void DiagnosticNoteRenderer::emitIncludeLocation(SourceLocation Loc,
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000586 PresumedLoc PLoc,
587 const SourceManager &SM) {
Ted Kremenek0964cca2012-02-14 02:46:00 +0000588 // Generate a note indicating the include location.
589 SmallString<200> MessageStorage;
590 llvm::raw_svector_ostream Message(MessageStorage);
591 Message << "in file included from " << PLoc.getFilename() << ':'
592 << PLoc.getLine() << ":";
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +0000593 emitNote(Loc, Message.str(), &SM);
Ted Kremenek0964cca2012-02-14 02:46:00 +0000594}
595
Douglas Gregor22103e32012-11-30 21:58:49 +0000596void DiagnosticNoteRenderer::emitImportLocation(SourceLocation Loc,
597 PresumedLoc PLoc,
598 StringRef ModuleName,
599 const SourceManager &SM) {
600 // Generate a note indicating the include location.
601 SmallString<200> MessageStorage;
602 llvm::raw_svector_ostream Message(MessageStorage);
Richard Smitha24ff552015-08-11 00:05:21 +0000603 Message << "in module '" << ModuleName;
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000604 if (PLoc.isValid())
Richard Smitha24ff552015-08-11 00:05:21 +0000605 Message << "' imported from " << PLoc.getFilename() << ':'
606 << PLoc.getLine();
607 Message << ":";
Douglas Gregor22103e32012-11-30 21:58:49 +0000608 emitNote(Loc, Message.str(), &SM);
609}
610
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000611void
612DiagnosticNoteRenderer::emitBuildingModuleLocation(SourceLocation Loc,
613 PresumedLoc PLoc,
614 StringRef ModuleName,
615 const SourceManager &SM) {
616 // Generate a note indicating the include location.
617 SmallString<200> MessageStorage;
618 llvm::raw_svector_ostream Message(MessageStorage);
Jordan Rose602ac142016-06-28 01:02:31 +0000619 if (PLoc.isValid())
Richard Smith7bea1d42014-03-05 20:55:36 +0000620 Message << "while building module '" << ModuleName << "' imported from "
621 << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
622 else
Jordan Rose6dcdaa62014-07-26 01:22:02 +0000623 Message << "while building module '" << ModuleName << "':";
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000624 emitNote(Loc, Message.str(), &SM);
625}