blob: e3263843e29bfbf0ccf3f1218cf789df90bf03a8 [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
Christof Doumafb4a0452017-06-27 09:50:38 +000079void DiagnosticRenderer::emitDiagnostic(FullSourceLoc Loc,
Ted Kremenekc4bbd852011-12-17 05:26:04 +000080 DiagnosticsEngine::Level Level,
81 StringRef Message,
82 ArrayRef<CharSourceRange> Ranges,
83 ArrayRef<FixItHint> FixItHints,
Ted Kremenek0964cca2012-02-14 02:46:00 +000084 DiagOrStoredDiag D) {
Christof Doumafb4a0452017-06-27 09:50:38 +000085 assert(Loc.hasManager() || Loc.isInvalid());
Richard Smithc01cca22012-12-05 09:47:49 +000086
Ted Kremenek0964cca2012-02-14 02:46:00 +000087 beginDiagnostic(D, Level);
Richard Smithc01cca22012-12-05 09:47:49 +000088
89 if (!Loc.isValid())
90 // If we have no source location, just emit the diagnostic message.
Christof Doumafb4a0452017-06-27 09:50:38 +000091 emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, D);
Richard Smithc01cca22012-12-05 09:47:49 +000092 else {
Ted Kremenekc4bbd852011-12-17 05:26:04 +000093 // Get the ranges into a local array we can hack on.
94 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
95 Ranges.end());
Richard Smithc01cca22012-12-05 09:47:49 +000096
Dmitri Gribenkof8579502013-01-12 19:30:44 +000097 SmallVector<FixItHint, 8> MergedFixits;
Ted Kremenekf7639e12012-03-06 20:06:33 +000098 if (!FixItHints.empty()) {
Christof Doumafb4a0452017-06-27 09:50:38 +000099 mergeFixits(FixItHints, Loc.getManager(), LangOpts, MergedFixits);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000100 FixItHints = MergedFixits;
101 }
102
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000103 for (ArrayRef<FixItHint>::const_iterator I = FixItHints.begin(),
104 E = FixItHints.end();
105 I != E; ++I)
106 if (I->RemoveRange.isValid())
107 MutableRanges.push_back(I->RemoveRange);
Richard Smithaebee682012-12-05 06:20:58 +0000108
Christof Doumafb4a0452017-06-27 09:50:38 +0000109 FullSourceLoc UnexpandedLoc = Loc;
Richard Smithaebee682012-12-05 06:20:58 +0000110
Ted Kremenek372735f2012-12-19 01:16:49 +0000111 // Find the ultimate expansion location for the diagnostic.
Christof Doumafb4a0452017-06-27 09:50:38 +0000112 Loc = Loc.getFileLoc();
Richard Smithc01cca22012-12-05 09:47:49 +0000113
Christof Doumafb4a0452017-06-27 09:50:38 +0000114 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Richard Smithc01cca22012-12-05 09:47:49 +0000115
116 // First, if this diagnostic is not in the main file, print out the
117 // "included from" lines.
Christof Doumafb4a0452017-06-27 09:50:38 +0000118 emitIncludeStack(Loc, PLoc, Level);
Richard Smithc01cca22012-12-05 09:47:49 +0000119
120 // Next, emit the actual diagnostic message and caret.
Christof Doumafb4a0452017-06-27 09:50:38 +0000121 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, D);
122 emitCaret(Loc, Level, MutableRanges, FixItHints);
Richard Smithc01cca22012-12-05 09:47:49 +0000123
124 // If this location is within a macro, walk from UnexpandedLoc up to Loc
125 // and produce a macro backtrace.
126 if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000127 emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints);
Richard Smithaebee682012-12-05 06:20:58 +0000128 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000129 }
Richard Smithc01cca22012-12-05 09:47:49 +0000130
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000131 LastLoc = Loc;
132 LastLevel = Level;
Richard Smithc01cca22012-12-05 09:47:49 +0000133
Ted Kremenek0964cca2012-02-14 02:46:00 +0000134 endDiagnostic(D, Level);
135}
136
137
138void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
139 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
140 Diag.getRanges(), Diag.getFixIts(),
141 &Diag);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000142}
143
Alp Toker4db87ab2014-06-21 23:31:59 +0000144void DiagnosticRenderer::emitBasicNote(StringRef Message) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000145 emitDiagnosticMessage(FullSourceLoc(), PresumedLoc(), DiagnosticsEngine::Note,
146 Message, None, DiagOrStoredDiag());
Alp Toker4db87ab2014-06-21 23:31:59 +0000147}
148
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000149/// \brief Prints an include stack when appropriate for a particular
150/// diagnostic level and location.
151///
152/// This routine handles all the logic of suppressing particular include
153/// stacks (such as those for notes) and duplicate include stacks when
154/// repeated warnings occur within the same file. It also handles the logic
155/// of customizing the formatting and display of the include stack.
156///
Douglas Gregor22103e32012-11-30 21:58:49 +0000157/// \param Loc The diagnostic location.
158/// \param PLoc The presumed location of the diagnostic location.
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000159/// \param Level The diagnostic level of the message this stack pertains to.
Christof Doumafb4a0452017-06-27 09:50:38 +0000160void DiagnosticRenderer::emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc,
161 DiagnosticsEngine::Level Level) {
162 FullSourceLoc IncludeLoc =
163 PLoc.isInvalid() ? FullSourceLoc()
164 : FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager());
Douglas Gregor22103e32012-11-30 21:58:49 +0000165
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000166 // Skip redundant include stacks altogether.
Douglas Gregor22103e32012-11-30 21:58:49 +0000167 if (LastIncludeLoc == IncludeLoc)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000168 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000169
170 LastIncludeLoc = IncludeLoc;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000171
Douglas Gregor811db4e2012-10-23 22:26:28 +0000172 if (!DiagOpts->ShowNoteIncludeStack && Level == DiagnosticsEngine::Note)
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000173 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000174
175 if (IncludeLoc.isValid())
Christof Doumafb4a0452017-06-27 09:50:38 +0000176 emitIncludeStackRecursively(IncludeLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000177 else {
Christof Doumafb4a0452017-06-27 09:50:38 +0000178 emitModuleBuildStack(Loc.getManager());
179 emitImportStack(Loc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000180 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000181}
182
183/// \brief Helper to recursivly walk up the include stack and print each layer
184/// on the way back down.
Christof Doumafb4a0452017-06-27 09:50:38 +0000185void DiagnosticRenderer::emitIncludeStackRecursively(FullSourceLoc Loc) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000186 if (Loc.isInvalid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000187 emitModuleBuildStack(Loc.getManager());
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000188 return;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000189 }
Christof Doumafb4a0452017-06-27 09:50:38 +0000190
191 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000192 if (PLoc.isInvalid())
193 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000194
195 // If this source location was imported from a module, print the module
196 // import stack rather than the
197 // FIXME: We want submodule granularity here.
Christof Doumafb4a0452017-06-27 09:50:38 +0000198 std::pair<FullSourceLoc, StringRef> Imported = Loc.getModuleImportLoc();
Richard Smitha24ff552015-08-11 00:05:21 +0000199 if (!Imported.second.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000200 // This location was imported by a module. Emit the module import stack.
Christof Doumafb4a0452017-06-27 09:50:38 +0000201 emitImportStackRecursively(Imported.first, Imported.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000202 return;
203 }
204
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000205 // Emit the other include frames first.
Christof Doumafb4a0452017-06-27 09:50:38 +0000206 emitIncludeStackRecursively(
207 FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager()));
208
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000209 // Emit the inclusion text/note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000210 emitIncludeLocation(Loc, PLoc);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000211}
212
Douglas Gregor22103e32012-11-30 21:58:49 +0000213/// \brief Emit the module import stack associated with the current location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000214void DiagnosticRenderer::emitImportStack(FullSourceLoc Loc) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000215 if (Loc.isInvalid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000216 emitModuleBuildStack(Loc.getManager());
Douglas Gregor22103e32012-11-30 21:58:49 +0000217 return;
218 }
219
Christof Doumafb4a0452017-06-27 09:50:38 +0000220 std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
221 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000222}
223
224/// \brief Helper to recursivly walk up the import stack and print each layer
225/// on the way back down.
Christof Doumafb4a0452017-06-27 09:50:38 +0000226void DiagnosticRenderer::emitImportStackRecursively(FullSourceLoc Loc,
227 StringRef ModuleName) {
Richard Smitha24ff552015-08-11 00:05:21 +0000228 if (ModuleName.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000229 return;
230 }
231
Christof Doumafb4a0452017-06-27 09:50:38 +0000232 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000233
234 // Emit the other import frames first.
Christof Doumafb4a0452017-06-27 09:50:38 +0000235 std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
236 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000237
238 // Emit the inclusion text/note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000239 emitImportLocation(Loc, PLoc, ModuleName);
Douglas Gregor22103e32012-11-30 21:58:49 +0000240}
241
Douglas Gregor63365432012-11-30 22:11:57 +0000242/// \brief Emit the module build stack, for cases where a module is (re-)built
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000243/// on demand.
Douglas Gregor63365432012-11-30 22:11:57 +0000244void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
245 ModuleBuildStack Stack = SM.getModuleBuildStack();
246 for (unsigned I = 0, N = Stack.size(); I != N; ++I) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000247 emitBuildingModuleLocation(Stack[I].second, Stack[I].second.getPresumedLoc(
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000248 DiagOpts->ShowPresumedLoc),
Christof Doumafb4a0452017-06-27 09:50:38 +0000249 Stack[I].first);
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000250 }
251}
252
Richard Trieuc3096242015-09-24 01:21:01 +0000253/// A recursive function to trace all possible backtrace locations
254/// to match the \p CaretLocFileID.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000255static SourceLocation
256retrieveMacroLocation(SourceLocation Loc, FileID MacroFileID,
257 FileID CaretFileID,
258 const SmallVectorImpl<FileID> &CommonArgExpansions,
259 bool IsBegin, const SourceManager *SM) {
260 assert(SM->getFileID(Loc) == MacroFileID);
261 if (MacroFileID == CaretFileID)
262 return Loc;
263 if (!Loc.isMacroID())
264 return SourceLocation();
Richard Trieuc3096242015-09-24 01:21:01 +0000265
266 SourceLocation MacroLocation, MacroArgLocation;
267
268 if (SM->isMacroArgExpansion(Loc)) {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000269 // Only look at the immediate spelling location of this macro argument if
270 // the other location in the source range is also present in that expansion.
271 if (std::binary_search(CommonArgExpansions.begin(),
272 CommonArgExpansions.end(), MacroFileID))
273 MacroLocation = SM->getImmediateSpellingLoc(Loc);
274 MacroArgLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
275 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000276 } else {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000277 MacroLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
278 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000279 MacroArgLocation = SM->getImmediateSpellingLoc(Loc);
280 }
281
Reid Klecknerda30cff2015-12-08 01:08:09 +0000282 if (MacroLocation.isValid()) {
283 MacroFileID = SM->getFileID(MacroLocation);
284 MacroLocation =
285 retrieveMacroLocation(MacroLocation, MacroFileID, CaretFileID,
286 CommonArgExpansions, IsBegin, SM);
287 if (MacroLocation.isValid())
288 return MacroLocation;
289 }
Richard Trieuc3096242015-09-24 01:21:01 +0000290
291 MacroFileID = SM->getFileID(MacroArgLocation);
292 return retrieveMacroLocation(MacroArgLocation, MacroFileID, CaretFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000293 CommonArgExpansions, IsBegin, SM);
294}
295
296/// Walk up the chain of macro expansions and collect the FileIDs identifying the
297/// expansions.
298static void getMacroArgExpansionFileIDs(SourceLocation Loc,
299 SmallVectorImpl<FileID> &IDs,
300 bool IsBegin, const SourceManager *SM) {
301 while (Loc.isMacroID()) {
302 if (SM->isMacroArgExpansion(Loc)) {
303 IDs.push_back(SM->getFileID(Loc));
304 Loc = SM->getImmediateSpellingLoc(Loc);
305 } else {
306 auto ExpRange = SM->getImmediateExpansionRange(Loc);
307 Loc = IsBegin ? ExpRange.first : ExpRange.second;
308 }
309 }
310}
311
312/// Collect the expansions of the begin and end locations and compute the set
313/// intersection. Produces a sorted vector of FileIDs in CommonArgExpansions.
314static void computeCommonMacroArgExpansionFileIDs(
315 SourceLocation Begin, SourceLocation End, const SourceManager *SM,
316 SmallVectorImpl<FileID> &CommonArgExpansions) {
317 SmallVector<FileID, 4> BeginArgExpansions;
318 SmallVector<FileID, 4> EndArgExpansions;
319 getMacroArgExpansionFileIDs(Begin, BeginArgExpansions, /*IsBegin=*/true, SM);
320 getMacroArgExpansionFileIDs(End, EndArgExpansions, /*IsBegin=*/false, SM);
321 std::sort(BeginArgExpansions.begin(), BeginArgExpansions.end());
322 std::sort(EndArgExpansions.begin(), EndArgExpansions.end());
323 std::set_intersection(BeginArgExpansions.begin(), BeginArgExpansions.end(),
324 EndArgExpansions.begin(), EndArgExpansions.end(),
325 std::back_inserter(CommonArgExpansions));
Richard Trieuc3096242015-09-24 01:21:01 +0000326}
327
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000328// Helper function to fix up source ranges. It takes in an array of ranges,
329// and outputs an array of ranges where we want to draw the range highlighting
330// around the location specified by CaretLoc.
331//
332// To find locations which correspond to the caret, we crawl the macro caller
333// chain for the beginning and end of each range. If the caret location
334// is in a macro expansion, we search each chain for a location
335// in the same expansion as the caret; otherwise, we crawl to the top of
336// each chain. Two locations are part of the same macro expansion
337// iff the FileID is the same.
Christof Doumafb4a0452017-06-27 09:50:38 +0000338static void
339mapDiagnosticRanges(FullSourceLoc CaretLoc, ArrayRef<CharSourceRange> Ranges,
340 SmallVectorImpl<CharSourceRange> &SpellingRanges) {
341 FileID CaretLocFileID = CaretLoc.getFileID();
342
343 const SourceManager *SM = &CaretLoc.getManager();
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000344
Richard Trieuc3096242015-09-24 01:21:01 +0000345 for (auto I = Ranges.begin(), E = Ranges.end(); I != E; ++I) {
346 if (I->isInvalid()) continue;
347
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000348 SourceLocation Begin = I->getBegin(), End = I->getEnd();
349 bool IsTokenRange = I->isTokenRange();
350
Eli Friedmandea98de2012-11-30 06:19:40 +0000351 FileID BeginFileID = SM->getFileID(Begin);
Nadav Rotemb8937342012-12-13 19:58:10 +0000352 FileID EndFileID = SM->getFileID(End);
Eli Friedmandea98de2012-11-30 06:19:40 +0000353
Nadav Rotemb8937342012-12-13 19:58:10 +0000354 // Find the common parent for the beginning and end of the range.
355
356 // First, crawl the expansion chain for the beginning of the range.
357 llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
358 while (Begin.isMacroID() && BeginFileID != EndFileID) {
359 BeginLocsMap[BeginFileID] = Begin;
360 Begin = SM->getImmediateExpansionRange(Begin).first;
361 BeginFileID = SM->getFileID(Begin);
362 }
363
364 // Then, crawl the expansion chain for the end of the range.
365 if (BeginFileID != EndFileID) {
366 while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000367 End = SM->getImmediateExpansionRange(End).second;
Nadav Rotemb8937342012-12-13 19:58:10 +0000368 EndFileID = SM->getFileID(End);
369 }
370 if (End.isMacroID()) {
371 Begin = BeginLocsMap[EndFileID];
372 BeginFileID = EndFileID;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000373 }
Eli Friedmancdb135a2012-12-13 00:14:59 +0000374 }
375
Richard Trieuc3096242015-09-24 01:21:01 +0000376 // Do the backtracking.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000377 SmallVector<FileID, 4> CommonArgExpansions;
378 computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);
Richard Trieuc3096242015-09-24 01:21:01 +0000379 Begin = retrieveMacroLocation(Begin, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000380 CommonArgExpansions, /*IsBegin=*/true, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000381 End = retrieveMacroLocation(End, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000382 CommonArgExpansions, /*IsBegin=*/false, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000383 if (Begin.isInvalid() || End.isInvalid()) continue;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000384
385 // Return the spelling location of the beginning and end of the range.
386 Begin = SM->getSpellingLoc(Begin);
387 End = SM->getSpellingLoc(End);
Richard Trieuc3096242015-09-24 01:21:01 +0000388
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000389 SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
390 IsTokenRange));
391 }
392}
393
Christof Doumafb4a0452017-06-27 09:50:38 +0000394void DiagnosticRenderer::emitCaret(FullSourceLoc Loc,
Richard Smithaebee682012-12-05 06:20:58 +0000395 DiagnosticsEngine::Level Level,
396 ArrayRef<CharSourceRange> Ranges,
Christof Doumafb4a0452017-06-27 09:50:38 +0000397 ArrayRef<FixItHint> Hints) {
Richard Smithaebee682012-12-05 06:20:58 +0000398 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000399 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
400 emitCodeContext(Loc, Level, SpellingRanges, Hints);
Richard Smithaebee682012-12-05 06:20:58 +0000401}
402
Richard Trieu97c45b62015-07-28 20:53:46 +0000403/// \brief A helper function for emitMacroExpansion to print the
404/// macro expansion message
405void DiagnosticRenderer::emitSingleMacroExpansion(
Christof Doumafb4a0452017-06-27 09:50:38 +0000406 FullSourceLoc Loc, DiagnosticsEngine::Level Level,
407 ArrayRef<CharSourceRange> Ranges) {
Richard Smith7a2d40d2012-12-05 03:18:16 +0000408 // Find the spelling location for the macro definition. We must use the
Richard Trieu97c45b62015-07-28 20:53:46 +0000409 // spelling location here to avoid emitting a macro backtrace for the note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000410 FullSourceLoc SpellingLoc = Loc.getSpellingLoc();
Richard Smith7a2d40d2012-12-05 03:18:16 +0000411
412 // Map the ranges into the FileID of the diagnostic location.
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000413 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000414 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000415
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000416 SmallString<100> MessageStorage;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000417 llvm::raw_svector_ostream Message(MessageStorage);
Christof Doumafb4a0452017-06-27 09:50:38 +0000418 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
419 Loc, Loc.getManager(), LangOpts);
Richard Smithf89e2e22012-12-05 11:04:55 +0000420 if (MacroName.empty())
421 Message << "expanded from here";
422 else
423 Message << "expanded from macro '" << MacroName << "'";
Richard Trieu97c45b62015-07-28 20:53:46 +0000424
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000425 emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
Christof Doumafb4a0452017-06-27 09:50:38 +0000426 SpellingRanges, None);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000427}
428
Richard Trieuc3096242015-09-24 01:21:01 +0000429/// Check that the macro argument location of Loc starts with ArgumentLoc.
430/// The starting location of the macro expansions is used to differeniate
431/// different macro expansions.
432static bool checkLocForMacroArgExpansion(SourceLocation Loc,
433 const SourceManager &SM,
434 SourceLocation ArgumentLoc) {
435 SourceLocation MacroLoc;
436 if (SM.isMacroArgExpansion(Loc, &MacroLoc)) {
437 if (ArgumentLoc == MacroLoc) return true;
438 }
439
440 return false;
441}
442
443/// Check if all the locations in the range have the same macro argument
444/// expansion, and that that expansion starts with ArgumentLoc.
Richard Trieuecd36ee2015-08-12 18:24:59 +0000445static bool checkRangeForMacroArgExpansion(CharSourceRange Range,
Richard Trieuc3096242015-09-24 01:21:01 +0000446 const SourceManager &SM,
447 SourceLocation ArgumentLoc) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000448 SourceLocation BegLoc = Range.getBegin(), EndLoc = Range.getEnd();
449 while (BegLoc != EndLoc) {
Richard Trieuc3096242015-09-24 01:21:01 +0000450 if (!checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000451 return false;
452 BegLoc.getLocWithOffset(1);
453 }
454
Richard Trieuc3096242015-09-24 01:21:01 +0000455 return checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000456}
457
Richard Trieuc3096242015-09-24 01:21:01 +0000458/// A helper function to check if the current ranges are all inside the same
459/// macro argument expansion as Loc.
Christof Doumafb4a0452017-06-27 09:50:38 +0000460static bool checkRangesForMacroArgExpansion(FullSourceLoc Loc,
461 ArrayRef<CharSourceRange> Ranges) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000462 assert(Loc.isMacroID() && "Must be a macro expansion!");
463
464 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000465 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000466
Richard Trieuc3096242015-09-24 01:21:01 +0000467 /// Count all valid ranges.
468 unsigned ValidCount = 0;
469 for (auto I : Ranges)
470 if (I.isValid()) ValidCount++;
471
472 if (ValidCount > SpellingRanges.size())
Richard Trieuecd36ee2015-08-12 18:24:59 +0000473 return false;
474
Richard Trieuc3096242015-09-24 01:21:01 +0000475 /// To store the source location of the argument location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000476 FullSourceLoc ArgumentLoc;
Richard Trieuc3096242015-09-24 01:21:01 +0000477
478 /// Set the ArgumentLoc to the beginning location of the expansion of Loc
479 /// so to check if the ranges expands to the same beginning location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000480 if (!Loc.isMacroArgExpansion(&ArgumentLoc))
Richard Trieuc3096242015-09-24 01:21:01 +0000481 return false;
482
483 for (auto I = SpellingRanges.begin(), E = SpellingRanges.end(); I != E; ++I) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000484 if (!checkRangeForMacroArgExpansion(*I, Loc.getManager(), ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000485 return false;
Richard Trieuc3096242015-09-24 01:21:01 +0000486 }
Richard Trieuecd36ee2015-08-12 18:24:59 +0000487
488 return true;
489}
490
Richard Trieu97c45b62015-07-28 20:53:46 +0000491/// \brief Recursively emit notes for each macro expansion and caret
492/// diagnostics where appropriate.
493///
494/// Walks up the macro expansion stack printing expansion notes, the code
495/// snippet, caret, underlines and FixItHint display as appropriate at each
496/// level.
497///
498/// \param Loc The location for this caret.
499/// \param Level The diagnostic level currently being emitted.
500/// \param Ranges The underlined ranges for this code snippet.
501/// \param Hints The FixIt hints active for this diagnostic.
Christof Doumafb4a0452017-06-27 09:50:38 +0000502void DiagnosticRenderer::emitMacroExpansions(FullSourceLoc Loc,
Richard Trieu97c45b62015-07-28 20:53:46 +0000503 DiagnosticsEngine::Level Level,
504 ArrayRef<CharSourceRange> Ranges,
Christof Doumafb4a0452017-06-27 09:50:38 +0000505 ArrayRef<FixItHint> Hints) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000506 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000507
508 // Produce a stack of macro backtraces.
Christof Doumafb4a0452017-06-27 09:50:38 +0000509 SmallVector<FullSourceLoc, 8> LocationStack;
Richard Trieuecd36ee2015-08-12 18:24:59 +0000510 unsigned IgnoredEnd = 0;
Richard Trieu97c45b62015-07-28 20:53:46 +0000511 while (Loc.isMacroID()) {
Richard Trieua1d7ece2015-08-27 23:38:45 +0000512 // If this is the expansion of a macro argument, point the caret at the
513 // use of the argument in the definition of the macro, not the expansion.
Christof Doumafb4a0452017-06-27 09:50:38 +0000514 if (Loc.isMacroArgExpansion())
515 LocationStack.push_back(Loc.getImmediateExpansionRange().first);
Richard Trieua1d7ece2015-08-27 23:38:45 +0000516 else
517 LocationStack.push_back(Loc);
518
Christof Doumafb4a0452017-06-27 09:50:38 +0000519 if (checkRangesForMacroArgExpansion(Loc, Ranges))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000520 IgnoredEnd = LocationStack.size();
521
Christof Doumafb4a0452017-06-27 09:50:38 +0000522 Loc = Loc.getImmediateMacroCallerLoc();
Richard Trieua1d7ece2015-08-27 23:38:45 +0000523
524 // Once the location no longer points into a macro, try stepping through
525 // the last found location. This sometimes produces additional useful
526 // backtraces.
527 if (Loc.isFileID())
Christof Doumafb4a0452017-06-27 09:50:38 +0000528 Loc = LocationStack.back().getImmediateMacroCallerLoc();
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000529 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000530 }
531
Richard Trieuecd36ee2015-08-12 18:24:59 +0000532 LocationStack.erase(LocationStack.begin(),
533 LocationStack.begin() + IgnoredEnd);
534
Richard Trieu97c45b62015-07-28 20:53:46 +0000535 unsigned MacroDepth = LocationStack.size();
536 unsigned MacroLimit = DiagOpts->MacroBacktraceLimit;
537 if (MacroDepth <= MacroLimit || MacroLimit == 0) {
538 for (auto I = LocationStack.rbegin(), E = LocationStack.rend();
539 I != E; ++I)
Christof Doumafb4a0452017-06-27 09:50:38 +0000540 emitSingleMacroExpansion(*I, Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000541 return;
542 }
543
544 unsigned MacroStartMessages = MacroLimit / 2;
545 unsigned MacroEndMessages = MacroLimit / 2 + MacroLimit % 2;
546
547 for (auto I = LocationStack.rbegin(),
548 E = LocationStack.rbegin() + MacroStartMessages;
549 I != E; ++I)
Christof Doumafb4a0452017-06-27 09:50:38 +0000550 emitSingleMacroExpansion(*I, Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000551
552 SmallString<200> MessageStorage;
553 llvm::raw_svector_ostream Message(MessageStorage);
554 Message << "(skipping " << (MacroDepth - MacroLimit)
555 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
556 "see all)";
557 emitBasicNote(Message.str());
558
559 for (auto I = LocationStack.rend() - MacroEndMessages,
560 E = LocationStack.rend();
561 I != E; ++I)
Christof Doumafb4a0452017-06-27 09:50:38 +0000562 emitSingleMacroExpansion(*I, Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000563}
564
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000565DiagnosticNoteRenderer::~DiagnosticNoteRenderer() {}
Ted Kremenek0964cca2012-02-14 02:46:00 +0000566
Christof Doumafb4a0452017-06-27 09:50:38 +0000567void DiagnosticNoteRenderer::emitIncludeLocation(FullSourceLoc Loc,
568 PresumedLoc PLoc) {
Ted Kremenek0964cca2012-02-14 02:46:00 +0000569 // Generate a note indicating the include location.
570 SmallString<200> MessageStorage;
571 llvm::raw_svector_ostream Message(MessageStorage);
572 Message << "in file included from " << PLoc.getFilename() << ':'
573 << PLoc.getLine() << ":";
Christof Doumafb4a0452017-06-27 09:50:38 +0000574 emitNote(Loc, Message.str());
Ted Kremenek0964cca2012-02-14 02:46:00 +0000575}
576
Christof Doumafb4a0452017-06-27 09:50:38 +0000577void DiagnosticNoteRenderer::emitImportLocation(FullSourceLoc Loc,
Douglas Gregor22103e32012-11-30 21:58:49 +0000578 PresumedLoc PLoc,
Christof Doumafb4a0452017-06-27 09:50:38 +0000579 StringRef ModuleName) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000580 // Generate a note indicating the include location.
581 SmallString<200> MessageStorage;
582 llvm::raw_svector_ostream Message(MessageStorage);
Richard Smitha24ff552015-08-11 00:05:21 +0000583 Message << "in module '" << ModuleName;
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000584 if (PLoc.isValid())
Richard Smitha24ff552015-08-11 00:05:21 +0000585 Message << "' imported from " << PLoc.getFilename() << ':'
586 << PLoc.getLine();
587 Message << ":";
Christof Doumafb4a0452017-06-27 09:50:38 +0000588 emitNote(Loc, Message.str());
Douglas Gregor22103e32012-11-30 21:58:49 +0000589}
590
Christof Doumafb4a0452017-06-27 09:50:38 +0000591void DiagnosticNoteRenderer::emitBuildingModuleLocation(FullSourceLoc Loc,
592 PresumedLoc PLoc,
593 StringRef ModuleName) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000594 // Generate a note indicating the include location.
595 SmallString<200> MessageStorage;
596 llvm::raw_svector_ostream Message(MessageStorage);
Jordan Rose602ac142016-06-28 01:02:31 +0000597 if (PLoc.isValid())
Richard Smith7bea1d42014-03-05 20:55:36 +0000598 Message << "while building module '" << ModuleName << "' imported from "
599 << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
600 else
Jordan Rose6dcdaa62014-07-26 01:22:02 +0000601 Message << "while building module '" << ModuleName << "':";
Christof Doumafb4a0452017-06-27 09:50:38 +0000602 emitNote(Loc, Message.str());
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000603}