blob: b6c9564f64eaa8922817359455f5c1109afed64b [file] [log] [blame]
Eugene Zelenko4f233182018-03-22 00:53:26 +00001//===- DiagnosticRenderer.cpp - Diagnostic Pretty-Printing ----------------===//
Ted Kremenekc4bbd852011-12-17 05:26:04 +00002//
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"
Eugene Zelenko4f233182018-03-22 00:53:26 +000011#include "clang/Basic/Diagnostic.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000012#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000013#include "clang/Basic/LLVM.h"
14#include "clang/Basic/SourceLocation.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000015#include "clang/Basic/SourceManager.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000016#include "clang/Edit/Commit.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Edit/EditedSource.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000018#include "clang/Edit/EditsReceiver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Lex/Lexer.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000020#include "llvm/ADT/ArrayRef.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/ADT/None.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000023#include "llvm/ADT/SmallString.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000024#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000026#include "llvm/Support/raw_ostream.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000027#include <algorithm>
Eugene Zelenko4f233182018-03-22 00:53:26 +000028#include <cassert>
29#include <iterator>
30#include <utility>
31
Ted Kremenekc4bbd852011-12-17 05:26:04 +000032using namespace clang;
33
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000034DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
Douglas Gregor811db4e2012-10-23 22:26:28 +000035 DiagnosticOptions *DiagOpts)
Eugene Zelenko4f233182018-03-22 00:53:26 +000036 : LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000037
Eugene Zelenko4f233182018-03-22 00:53:26 +000038DiagnosticRenderer::~DiagnosticRenderer() = default;
Ted Kremenekc4bbd852011-12-17 05:26:04 +000039
Ted Kremenekf7639e12012-03-06 20:06:33 +000040namespace {
41
42class FixitReceiver : public edit::EditsReceiver {
43 SmallVectorImpl<FixItHint> &MergedFixits;
44
45public:
46 FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
Eugene Zelenko4f233182018-03-22 00:53:26 +000047 : MergedFixits(MergedFixits) {}
48
Craig Topperafa7cb32014-03-13 06:07:04 +000049 void insert(SourceLocation loc, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000050 MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
51 }
Eugene Zelenko4f233182018-03-22 00:53:26 +000052
Craig Topperafa7cb32014-03-13 06:07:04 +000053 void replace(CharSourceRange range, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000054 MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
55 }
56};
57
Eugene Zelenko4f233182018-03-22 00:53:26 +000058} // namespace
Ted Kremenekf7639e12012-03-06 20:06:33 +000059
60static void mergeFixits(ArrayRef<FixItHint> FixItHints,
61 const SourceManager &SM, const LangOptions &LangOpts,
62 SmallVectorImpl<FixItHint> &MergedFixits) {
63 edit::Commit commit(SM, LangOpts);
Eugene Zelenko4f233182018-03-22 00:53:26 +000064 for (const auto &Hint : FixItHints)
Ted Kremenekf7639e12012-03-06 20:06:33 +000065 if (Hint.CodeToInsert.empty()) {
66 if (Hint.InsertFromRange.isValid())
67 commit.insertFromRange(Hint.RemoveRange.getBegin(),
68 Hint.InsertFromRange, /*afterToken=*/false,
69 Hint.BeforePreviousInsertions);
70 else
71 commit.remove(Hint.RemoveRange);
72 } else {
73 if (Hint.RemoveRange.isTokenRange() ||
74 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
75 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
76 else
77 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
78 /*afterToken=*/false, Hint.BeforePreviousInsertions);
79 }
Ted Kremenekf7639e12012-03-06 20:06:33 +000080
81 edit::EditedSource Editor(SM, LangOpts);
82 if (Editor.commit(commit)) {
83 FixitReceiver Rec(MergedFixits);
84 Editor.applyRewrites(Rec);
85 }
86}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000087
Christof Doumafb4a0452017-06-27 09:50:38 +000088void DiagnosticRenderer::emitDiagnostic(FullSourceLoc Loc,
Ted Kremenekc4bbd852011-12-17 05:26:04 +000089 DiagnosticsEngine::Level Level,
90 StringRef Message,
91 ArrayRef<CharSourceRange> Ranges,
92 ArrayRef<FixItHint> FixItHints,
Ted Kremenek0964cca2012-02-14 02:46:00 +000093 DiagOrStoredDiag D) {
Christof Doumafb4a0452017-06-27 09:50:38 +000094 assert(Loc.hasManager() || Loc.isInvalid());
Richard Smithc01cca22012-12-05 09:47:49 +000095
Ted Kremenek0964cca2012-02-14 02:46:00 +000096 beginDiagnostic(D, Level);
Richard Smithc01cca22012-12-05 09:47:49 +000097
98 if (!Loc.isValid())
99 // If we have no source location, just emit the diagnostic message.
Christof Doumafb4a0452017-06-27 09:50:38 +0000100 emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, D);
Richard Smithc01cca22012-12-05 09:47:49 +0000101 else {
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000102 // Get the ranges into a local array we can hack on.
103 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
104 Ranges.end());
Richard Smithc01cca22012-12-05 09:47:49 +0000105
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000106 SmallVector<FixItHint, 8> MergedFixits;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000107 if (!FixItHints.empty()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000108 mergeFixits(FixItHints, Loc.getManager(), LangOpts, MergedFixits);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000109 FixItHints = MergedFixits;
110 }
111
Eugene Zelenko4f233182018-03-22 00:53:26 +0000112 for (const auto &Hint : FixItHints)
113 if (Hint.RemoveRange.isValid())
114 MutableRanges.push_back(Hint.RemoveRange);
Richard Smithaebee682012-12-05 06:20:58 +0000115
Christof Doumafb4a0452017-06-27 09:50:38 +0000116 FullSourceLoc UnexpandedLoc = Loc;
Richard Smithaebee682012-12-05 06:20:58 +0000117
Ted Kremenek372735f2012-12-19 01:16:49 +0000118 // Find the ultimate expansion location for the diagnostic.
Christof Doumafb4a0452017-06-27 09:50:38 +0000119 Loc = Loc.getFileLoc();
Richard Smithc01cca22012-12-05 09:47:49 +0000120
Christof Doumafb4a0452017-06-27 09:50:38 +0000121 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Richard Smithc01cca22012-12-05 09:47:49 +0000122
123 // First, if this diagnostic is not in the main file, print out the
124 // "included from" lines.
Christof Doumafb4a0452017-06-27 09:50:38 +0000125 emitIncludeStack(Loc, PLoc, Level);
Richard Smithc01cca22012-12-05 09:47:49 +0000126
127 // Next, emit the actual diagnostic message and caret.
Christof Doumafb4a0452017-06-27 09:50:38 +0000128 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, D);
129 emitCaret(Loc, Level, MutableRanges, FixItHints);
Richard Smithc01cca22012-12-05 09:47:49 +0000130
131 // If this location is within a macro, walk from UnexpandedLoc up to Loc
132 // and produce a macro backtrace.
133 if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000134 emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints);
Richard Smithaebee682012-12-05 06:20:58 +0000135 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000136 }
Richard Smithc01cca22012-12-05 09:47:49 +0000137
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000138 LastLoc = Loc;
139 LastLevel = Level;
Richard Smithc01cca22012-12-05 09:47:49 +0000140
Ted Kremenek0964cca2012-02-14 02:46:00 +0000141 endDiagnostic(D, Level);
142}
143
Ted Kremenek0964cca2012-02-14 02:46:00 +0000144void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
145 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
146 Diag.getRanges(), Diag.getFixIts(),
147 &Diag);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000148}
149
Alp Toker4db87ab2014-06-21 23:31:59 +0000150void DiagnosticRenderer::emitBasicNote(StringRef Message) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000151 emitDiagnosticMessage(FullSourceLoc(), PresumedLoc(), DiagnosticsEngine::Note,
152 Message, None, 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.
Christof Doumafb4a0452017-06-27 09:50:38 +0000166void DiagnosticRenderer::emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc,
167 DiagnosticsEngine::Level Level) {
168 FullSourceLoc IncludeLoc =
169 PLoc.isInvalid() ? FullSourceLoc()
170 : FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager());
Douglas Gregor22103e32012-11-30 21:58:49 +0000171
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())
Christof Doumafb4a0452017-06-27 09:50:38 +0000182 emitIncludeStackRecursively(IncludeLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000183 else {
Christof Doumafb4a0452017-06-27 09:50:38 +0000184 emitModuleBuildStack(Loc.getManager());
185 emitImportStack(Loc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000186 }
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.
Christof Doumafb4a0452017-06-27 09:50:38 +0000191void DiagnosticRenderer::emitIncludeStackRecursively(FullSourceLoc Loc) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000192 if (Loc.isInvalid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000193 emitModuleBuildStack(Loc.getManager());
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000194 return;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000195 }
Christof Doumafb4a0452017-06-27 09:50:38 +0000196
197 PresumedLoc PLoc = Loc.getPresumedLoc(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.
Christof Doumafb4a0452017-06-27 09:50:38 +0000204 std::pair<FullSourceLoc, StringRef> Imported = Loc.getModuleImportLoc();
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.
Christof Doumafb4a0452017-06-27 09:50:38 +0000207 emitImportStackRecursively(Imported.first, Imported.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000208 return;
209 }
210
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000211 // Emit the other include frames first.
Christof Doumafb4a0452017-06-27 09:50:38 +0000212 emitIncludeStackRecursively(
213 FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager()));
214
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000215 // Emit the inclusion text/note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000216 emitIncludeLocation(Loc, PLoc);
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.
Christof Doumafb4a0452017-06-27 09:50:38 +0000220void DiagnosticRenderer::emitImportStack(FullSourceLoc Loc) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000221 if (Loc.isInvalid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000222 emitModuleBuildStack(Loc.getManager());
Douglas Gregor22103e32012-11-30 21:58:49 +0000223 return;
224 }
225
Christof Doumafb4a0452017-06-27 09:50:38 +0000226 std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
227 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000228}
229
230/// \brief Helper to recursivly walk up the import stack and print each layer
231/// on the way back down.
Christof Doumafb4a0452017-06-27 09:50:38 +0000232void DiagnosticRenderer::emitImportStackRecursively(FullSourceLoc Loc,
233 StringRef ModuleName) {
Richard Smitha24ff552015-08-11 00:05:21 +0000234 if (ModuleName.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000235 return;
236 }
237
Christof Doumafb4a0452017-06-27 09:50:38 +0000238 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000239
240 // Emit the other import frames first.
Christof Doumafb4a0452017-06-27 09:50:38 +0000241 std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
242 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000243
244 // Emit the inclusion text/note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000245 emitImportLocation(Loc, PLoc, ModuleName);
Douglas Gregor22103e32012-11-30 21:58:49 +0000246}
247
Douglas Gregor63365432012-11-30 22:11:57 +0000248/// \brief Emit the module build stack, for cases where a module is (re-)built
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000249/// on demand.
Douglas Gregor63365432012-11-30 22:11:57 +0000250void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
251 ModuleBuildStack Stack = SM.getModuleBuildStack();
Eugene Zelenko4f233182018-03-22 00:53:26 +0000252 for (const auto &I : Stack) {
253 emitBuildingModuleLocation(I.second, I.second.getPresumedLoc(
254 DiagOpts->ShowPresumedLoc),
255 I.first);
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000256 }
257}
258
Richard Trieuc3096242015-09-24 01:21:01 +0000259/// A recursive function to trace all possible backtrace locations
260/// to match the \p CaretLocFileID.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000261static SourceLocation
262retrieveMacroLocation(SourceLocation Loc, FileID MacroFileID,
263 FileID CaretFileID,
264 const SmallVectorImpl<FileID> &CommonArgExpansions,
265 bool IsBegin, const SourceManager *SM) {
266 assert(SM->getFileID(Loc) == MacroFileID);
267 if (MacroFileID == CaretFileID)
268 return Loc;
269 if (!Loc.isMacroID())
Eugene Zelenko4f233182018-03-22 00:53:26 +0000270 return {};
Richard Trieuc3096242015-09-24 01:21:01 +0000271
272 SourceLocation MacroLocation, MacroArgLocation;
273
274 if (SM->isMacroArgExpansion(Loc)) {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000275 // Only look at the immediate spelling location of this macro argument if
276 // the other location in the source range is also present in that expansion.
277 if (std::binary_search(CommonArgExpansions.begin(),
278 CommonArgExpansions.end(), MacroFileID))
279 MacroLocation = SM->getImmediateSpellingLoc(Loc);
280 MacroArgLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
281 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000282 } else {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000283 MacroLocation = IsBegin ? SM->getImmediateExpansionRange(Loc).first
284 : SM->getImmediateExpansionRange(Loc).second;
Richard Trieuc3096242015-09-24 01:21:01 +0000285 MacroArgLocation = SM->getImmediateSpellingLoc(Loc);
286 }
287
Reid Klecknerda30cff2015-12-08 01:08:09 +0000288 if (MacroLocation.isValid()) {
289 MacroFileID = SM->getFileID(MacroLocation);
290 MacroLocation =
291 retrieveMacroLocation(MacroLocation, MacroFileID, CaretFileID,
292 CommonArgExpansions, IsBegin, SM);
293 if (MacroLocation.isValid())
294 return MacroLocation;
295 }
Richard Trieuc3096242015-09-24 01:21:01 +0000296
297 MacroFileID = SM->getFileID(MacroArgLocation);
298 return retrieveMacroLocation(MacroArgLocation, MacroFileID, CaretFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000299 CommonArgExpansions, IsBegin, SM);
300}
301
302/// Walk up the chain of macro expansions and collect the FileIDs identifying the
303/// expansions.
304static void getMacroArgExpansionFileIDs(SourceLocation Loc,
305 SmallVectorImpl<FileID> &IDs,
306 bool IsBegin, const SourceManager *SM) {
307 while (Loc.isMacroID()) {
308 if (SM->isMacroArgExpansion(Loc)) {
309 IDs.push_back(SM->getFileID(Loc));
310 Loc = SM->getImmediateSpellingLoc(Loc);
311 } else {
312 auto ExpRange = SM->getImmediateExpansionRange(Loc);
313 Loc = IsBegin ? ExpRange.first : ExpRange.second;
314 }
315 }
316}
317
318/// Collect the expansions of the begin and end locations and compute the set
319/// intersection. Produces a sorted vector of FileIDs in CommonArgExpansions.
320static void computeCommonMacroArgExpansionFileIDs(
321 SourceLocation Begin, SourceLocation End, const SourceManager *SM,
322 SmallVectorImpl<FileID> &CommonArgExpansions) {
323 SmallVector<FileID, 4> BeginArgExpansions;
324 SmallVector<FileID, 4> EndArgExpansions;
325 getMacroArgExpansionFileIDs(Begin, BeginArgExpansions, /*IsBegin=*/true, SM);
326 getMacroArgExpansionFileIDs(End, EndArgExpansions, /*IsBegin=*/false, SM);
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000327 llvm::sort(BeginArgExpansions.begin(), BeginArgExpansions.end());
328 llvm::sort(EndArgExpansions.begin(), EndArgExpansions.end());
Reid Klecknerda30cff2015-12-08 01:08:09 +0000329 std::set_intersection(BeginArgExpansions.begin(), BeginArgExpansions.end(),
330 EndArgExpansions.begin(), EndArgExpansions.end(),
331 std::back_inserter(CommonArgExpansions));
Richard Trieuc3096242015-09-24 01:21:01 +0000332}
333
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000334// Helper function to fix up source ranges. It takes in an array of ranges,
335// and outputs an array of ranges where we want to draw the range highlighting
336// around the location specified by CaretLoc.
337//
338// To find locations which correspond to the caret, we crawl the macro caller
339// chain for the beginning and end of each range. If the caret location
340// is in a macro expansion, we search each chain for a location
341// in the same expansion as the caret; otherwise, we crawl to the top of
342// each chain. Two locations are part of the same macro expansion
343// iff the FileID is the same.
Christof Doumafb4a0452017-06-27 09:50:38 +0000344static void
345mapDiagnosticRanges(FullSourceLoc CaretLoc, ArrayRef<CharSourceRange> Ranges,
346 SmallVectorImpl<CharSourceRange> &SpellingRanges) {
347 FileID CaretLocFileID = CaretLoc.getFileID();
348
349 const SourceManager *SM = &CaretLoc.getManager();
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000350
Eugene Zelenko4f233182018-03-22 00:53:26 +0000351 for (const auto &Range : Ranges) {
352 if (Range.isInvalid())
353 continue;
Richard Trieuc3096242015-09-24 01:21:01 +0000354
Eugene Zelenko4f233182018-03-22 00:53:26 +0000355 SourceLocation Begin = Range.getBegin(), End = Range.getEnd();
356 bool IsTokenRange = Range.isTokenRange();
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000357
Eli Friedmandea98de2012-11-30 06:19:40 +0000358 FileID BeginFileID = SM->getFileID(Begin);
Nadav Rotemb8937342012-12-13 19:58:10 +0000359 FileID EndFileID = SM->getFileID(End);
Eli Friedmandea98de2012-11-30 06:19:40 +0000360
Nadav Rotemb8937342012-12-13 19:58:10 +0000361 // Find the common parent for the beginning and end of the range.
362
363 // First, crawl the expansion chain for the beginning of the range.
364 llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
365 while (Begin.isMacroID() && BeginFileID != EndFileID) {
366 BeginLocsMap[BeginFileID] = Begin;
367 Begin = SM->getImmediateExpansionRange(Begin).first;
368 BeginFileID = SM->getFileID(Begin);
369 }
370
371 // Then, crawl the expansion chain for the end of the range.
372 if (BeginFileID != EndFileID) {
373 while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000374 End = SM->getImmediateExpansionRange(End).second;
Nadav Rotemb8937342012-12-13 19:58:10 +0000375 EndFileID = SM->getFileID(End);
376 }
377 if (End.isMacroID()) {
378 Begin = BeginLocsMap[EndFileID];
379 BeginFileID = EndFileID;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000380 }
Eli Friedmancdb135a2012-12-13 00:14:59 +0000381 }
382
Richard Trieuc3096242015-09-24 01:21:01 +0000383 // Do the backtracking.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000384 SmallVector<FileID, 4> CommonArgExpansions;
385 computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);
Richard Trieuc3096242015-09-24 01:21:01 +0000386 Begin = retrieveMacroLocation(Begin, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000387 CommonArgExpansions, /*IsBegin=*/true, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000388 End = retrieveMacroLocation(End, BeginFileID, CaretLocFileID,
Reid Klecknerda30cff2015-12-08 01:08:09 +0000389 CommonArgExpansions, /*IsBegin=*/false, SM);
Richard Trieuc3096242015-09-24 01:21:01 +0000390 if (Begin.isInvalid() || End.isInvalid()) continue;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000391
392 // Return the spelling location of the beginning and end of the range.
393 Begin = SM->getSpellingLoc(Begin);
394 End = SM->getSpellingLoc(End);
Richard Trieuc3096242015-09-24 01:21:01 +0000395
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000396 SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
397 IsTokenRange));
398 }
399}
400
Christof Doumafb4a0452017-06-27 09:50:38 +0000401void DiagnosticRenderer::emitCaret(FullSourceLoc Loc,
Richard Smithaebee682012-12-05 06:20:58 +0000402 DiagnosticsEngine::Level Level,
403 ArrayRef<CharSourceRange> Ranges,
Christof Doumafb4a0452017-06-27 09:50:38 +0000404 ArrayRef<FixItHint> Hints) {
Richard Smithaebee682012-12-05 06:20:58 +0000405 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000406 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
407 emitCodeContext(Loc, Level, SpellingRanges, Hints);
Richard Smithaebee682012-12-05 06:20:58 +0000408}
409
Richard Trieu97c45b62015-07-28 20:53:46 +0000410/// \brief A helper function for emitMacroExpansion to print the
411/// macro expansion message
412void DiagnosticRenderer::emitSingleMacroExpansion(
Christof Doumafb4a0452017-06-27 09:50:38 +0000413 FullSourceLoc Loc, DiagnosticsEngine::Level Level,
414 ArrayRef<CharSourceRange> Ranges) {
Richard Smith7a2d40d2012-12-05 03:18:16 +0000415 // Find the spelling location for the macro definition. We must use the
Richard Trieu97c45b62015-07-28 20:53:46 +0000416 // spelling location here to avoid emitting a macro backtrace for the note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000417 FullSourceLoc SpellingLoc = Loc.getSpellingLoc();
Richard Smith7a2d40d2012-12-05 03:18:16 +0000418
419 // Map the ranges into the FileID of the diagnostic location.
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000420 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000421 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000422
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000423 SmallString<100> MessageStorage;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000424 llvm::raw_svector_ostream Message(MessageStorage);
Christof Doumafb4a0452017-06-27 09:50:38 +0000425 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
426 Loc, Loc.getManager(), LangOpts);
Richard Smithf89e2e22012-12-05 11:04:55 +0000427 if (MacroName.empty())
428 Message << "expanded from here";
429 else
430 Message << "expanded from macro '" << MacroName << "'";
Richard Trieu97c45b62015-07-28 20:53:46 +0000431
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000432 emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
Christof Doumafb4a0452017-06-27 09:50:38 +0000433 SpellingRanges, None);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000434}
435
Richard Trieuc3096242015-09-24 01:21:01 +0000436/// Check that the macro argument location of Loc starts with ArgumentLoc.
437/// The starting location of the macro expansions is used to differeniate
438/// different macro expansions.
439static bool checkLocForMacroArgExpansion(SourceLocation Loc,
440 const SourceManager &SM,
441 SourceLocation ArgumentLoc) {
442 SourceLocation MacroLoc;
443 if (SM.isMacroArgExpansion(Loc, &MacroLoc)) {
444 if (ArgumentLoc == MacroLoc) return true;
445 }
446
447 return false;
448}
449
450/// Check if all the locations in the range have the same macro argument
451/// expansion, and that that expansion starts with ArgumentLoc.
Richard Trieuecd36ee2015-08-12 18:24:59 +0000452static bool checkRangeForMacroArgExpansion(CharSourceRange Range,
Richard Trieuc3096242015-09-24 01:21:01 +0000453 const SourceManager &SM,
454 SourceLocation ArgumentLoc) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000455 SourceLocation BegLoc = Range.getBegin(), EndLoc = Range.getEnd();
456 while (BegLoc != EndLoc) {
Richard Trieuc3096242015-09-24 01:21:01 +0000457 if (!checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000458 return false;
459 BegLoc.getLocWithOffset(1);
460 }
461
Richard Trieuc3096242015-09-24 01:21:01 +0000462 return checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000463}
464
Richard Trieuc3096242015-09-24 01:21:01 +0000465/// A helper function to check if the current ranges are all inside the same
466/// macro argument expansion as Loc.
Christof Doumafb4a0452017-06-27 09:50:38 +0000467static bool checkRangesForMacroArgExpansion(FullSourceLoc Loc,
468 ArrayRef<CharSourceRange> Ranges) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000469 assert(Loc.isMacroID() && "Must be a macro expansion!");
470
471 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000472 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000473
Richard Trieuc3096242015-09-24 01:21:01 +0000474 /// Count all valid ranges.
475 unsigned ValidCount = 0;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000476 for (const auto &Range : Ranges)
477 if (Range.isValid())
478 ValidCount++;
Richard Trieuc3096242015-09-24 01:21:01 +0000479
480 if (ValidCount > SpellingRanges.size())
Richard Trieuecd36ee2015-08-12 18:24:59 +0000481 return false;
482
Richard Trieuc3096242015-09-24 01:21:01 +0000483 /// To store the source location of the argument location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000484 FullSourceLoc ArgumentLoc;
Richard Trieuc3096242015-09-24 01:21:01 +0000485
486 /// Set the ArgumentLoc to the beginning location of the expansion of Loc
487 /// so to check if the ranges expands to the same beginning location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000488 if (!Loc.isMacroArgExpansion(&ArgumentLoc))
Richard Trieuc3096242015-09-24 01:21:01 +0000489 return false;
490
Eugene Zelenko4f233182018-03-22 00:53:26 +0000491 for (const auto &Range : SpellingRanges)
492 if (!checkRangeForMacroArgExpansion(Range, Loc.getManager(), ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000493 return false;
494
495 return true;
496}
497
Richard Trieu97c45b62015-07-28 20:53:46 +0000498/// \brief Recursively emit notes for each macro expansion and caret
499/// diagnostics where appropriate.
500///
501/// Walks up the macro expansion stack printing expansion notes, the code
502/// snippet, caret, underlines and FixItHint display as appropriate at each
503/// level.
504///
505/// \param Loc The location for this caret.
506/// \param Level The diagnostic level currently being emitted.
507/// \param Ranges The underlined ranges for this code snippet.
508/// \param Hints The FixIt hints active for this diagnostic.
Christof Doumafb4a0452017-06-27 09:50:38 +0000509void DiagnosticRenderer::emitMacroExpansions(FullSourceLoc Loc,
Richard Trieu97c45b62015-07-28 20:53:46 +0000510 DiagnosticsEngine::Level Level,
511 ArrayRef<CharSourceRange> Ranges,
Christof Doumafb4a0452017-06-27 09:50:38 +0000512 ArrayRef<FixItHint> Hints) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000513 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000514
515 // Produce a stack of macro backtraces.
Christof Doumafb4a0452017-06-27 09:50:38 +0000516 SmallVector<FullSourceLoc, 8> LocationStack;
Richard Trieuecd36ee2015-08-12 18:24:59 +0000517 unsigned IgnoredEnd = 0;
Richard Trieu97c45b62015-07-28 20:53:46 +0000518 while (Loc.isMacroID()) {
Richard Trieua1d7ece2015-08-27 23:38:45 +0000519 // If this is the expansion of a macro argument, point the caret at the
520 // use of the argument in the definition of the macro, not the expansion.
Christof Doumafb4a0452017-06-27 09:50:38 +0000521 if (Loc.isMacroArgExpansion())
522 LocationStack.push_back(Loc.getImmediateExpansionRange().first);
Richard Trieua1d7ece2015-08-27 23:38:45 +0000523 else
524 LocationStack.push_back(Loc);
525
Christof Doumafb4a0452017-06-27 09:50:38 +0000526 if (checkRangesForMacroArgExpansion(Loc, Ranges))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000527 IgnoredEnd = LocationStack.size();
528
Christof Doumafb4a0452017-06-27 09:50:38 +0000529 Loc = Loc.getImmediateMacroCallerLoc();
Richard Trieua1d7ece2015-08-27 23:38:45 +0000530
531 // Once the location no longer points into a macro, try stepping through
532 // the last found location. This sometimes produces additional useful
533 // backtraces.
534 if (Loc.isFileID())
Christof Doumafb4a0452017-06-27 09:50:38 +0000535 Loc = LocationStack.back().getImmediateMacroCallerLoc();
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000536 assert(Loc.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000537 }
538
Richard Trieuecd36ee2015-08-12 18:24:59 +0000539 LocationStack.erase(LocationStack.begin(),
540 LocationStack.begin() + IgnoredEnd);
541
Richard Trieu97c45b62015-07-28 20:53:46 +0000542 unsigned MacroDepth = LocationStack.size();
543 unsigned MacroLimit = DiagOpts->MacroBacktraceLimit;
544 if (MacroDepth <= MacroLimit || MacroLimit == 0) {
545 for (auto I = LocationStack.rbegin(), E = LocationStack.rend();
546 I != E; ++I)
Christof Doumafb4a0452017-06-27 09:50:38 +0000547 emitSingleMacroExpansion(*I, Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000548 return;
549 }
550
551 unsigned MacroStartMessages = MacroLimit / 2;
552 unsigned MacroEndMessages = MacroLimit / 2 + MacroLimit % 2;
553
554 for (auto I = LocationStack.rbegin(),
555 E = LocationStack.rbegin() + MacroStartMessages;
556 I != E; ++I)
Christof Doumafb4a0452017-06-27 09:50:38 +0000557 emitSingleMacroExpansion(*I, Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000558
559 SmallString<200> MessageStorage;
560 llvm::raw_svector_ostream Message(MessageStorage);
561 Message << "(skipping " << (MacroDepth - MacroLimit)
562 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
563 "see all)";
564 emitBasicNote(Message.str());
565
566 for (auto I = LocationStack.rend() - MacroEndMessages,
567 E = LocationStack.rend();
568 I != E; ++I)
Christof Doumafb4a0452017-06-27 09:50:38 +0000569 emitSingleMacroExpansion(*I, Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000570}
571
Eugene Zelenko4f233182018-03-22 00:53:26 +0000572DiagnosticNoteRenderer::~DiagnosticNoteRenderer() = default;
Ted Kremenek0964cca2012-02-14 02:46:00 +0000573
Christof Doumafb4a0452017-06-27 09:50:38 +0000574void DiagnosticNoteRenderer::emitIncludeLocation(FullSourceLoc Loc,
575 PresumedLoc PLoc) {
Ted Kremenek0964cca2012-02-14 02:46:00 +0000576 // Generate a note indicating the include location.
577 SmallString<200> MessageStorage;
578 llvm::raw_svector_ostream Message(MessageStorage);
579 Message << "in file included from " << PLoc.getFilename() << ':'
580 << PLoc.getLine() << ":";
Christof Doumafb4a0452017-06-27 09:50:38 +0000581 emitNote(Loc, Message.str());
Ted Kremenek0964cca2012-02-14 02:46:00 +0000582}
583
Christof Doumafb4a0452017-06-27 09:50:38 +0000584void DiagnosticNoteRenderer::emitImportLocation(FullSourceLoc Loc,
Douglas Gregor22103e32012-11-30 21:58:49 +0000585 PresumedLoc PLoc,
Christof Doumafb4a0452017-06-27 09:50:38 +0000586 StringRef ModuleName) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000587 // Generate a note indicating the include location.
588 SmallString<200> MessageStorage;
589 llvm::raw_svector_ostream Message(MessageStorage);
Richard Smitha24ff552015-08-11 00:05:21 +0000590 Message << "in module '" << ModuleName;
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000591 if (PLoc.isValid())
Richard Smitha24ff552015-08-11 00:05:21 +0000592 Message << "' imported from " << PLoc.getFilename() << ':'
593 << PLoc.getLine();
594 Message << ":";
Christof Doumafb4a0452017-06-27 09:50:38 +0000595 emitNote(Loc, Message.str());
Douglas Gregor22103e32012-11-30 21:58:49 +0000596}
597
Christof Doumafb4a0452017-06-27 09:50:38 +0000598void DiagnosticNoteRenderer::emitBuildingModuleLocation(FullSourceLoc Loc,
599 PresumedLoc PLoc,
600 StringRef ModuleName) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000601 // Generate a note indicating the include location.
602 SmallString<200> MessageStorage;
603 llvm::raw_svector_ostream Message(MessageStorage);
Jordan Rose602ac142016-06-28 01:02:31 +0000604 if (PLoc.isValid())
Richard Smith7bea1d42014-03-05 20:55:36 +0000605 Message << "while building module '" << ModuleName << "' imported from "
606 << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
607 else
Jordan Rose6dcdaa62014-07-26 01:22:02 +0000608 Message << "while building module '" << ModuleName << "':";
Christof Doumafb4a0452017-06-27 09:50:38 +0000609 emitNote(Loc, Message.str());
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000610}