blob: 22b957988f4620def3cb5ddf8df34f2b4389d26b [file] [log] [blame]
Eugene Zelenko4f233182018-03-22 00:53:26 +00001//===- DiagnosticRenderer.cpp - Diagnostic Pretty-Printing ----------------===//
Ted Kremenekc4bbd852011-12-17 05:26:04 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Ted Kremenekc4bbd852011-12-17 05:26:04 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "clang/Frontend/DiagnosticRenderer.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000010#include "clang/Basic/Diagnostic.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000011#include "clang/Basic/DiagnosticOptions.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000012#include "clang/Basic/LLVM.h"
13#include "clang/Basic/SourceLocation.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000014#include "clang/Basic/SourceManager.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000015#include "clang/Edit/Commit.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/Edit/EditedSource.h"
Ted Kremenekf7639e12012-03-06 20:06:33 +000017#include "clang/Edit/EditsReceiver.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/Lex/Lexer.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000019#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/None.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000022#include "llvm/ADT/SmallString.h"
Eugene Zelenko4f233182018-03-22 00:53:26 +000023#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringRef.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenekc4bbd852011-12-17 05:26:04 +000026#include <algorithm>
Eugene Zelenko4f233182018-03-22 00:53:26 +000027#include <cassert>
28#include <iterator>
29#include <utility>
30
Ted Kremenekc4bbd852011-12-17 05:26:04 +000031using namespace clang;
32
Argyrios Kyrtzidisb16ff5d2012-05-10 05:03:45 +000033DiagnosticRenderer::DiagnosticRenderer(const LangOptions &LangOpts,
Douglas Gregor811db4e2012-10-23 22:26:28 +000034 DiagnosticOptions *DiagOpts)
Eugene Zelenko4f233182018-03-22 00:53:26 +000035 : LangOpts(LangOpts), DiagOpts(DiagOpts), LastLevel() {}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000036
Eugene Zelenko4f233182018-03-22 00:53:26 +000037DiagnosticRenderer::~DiagnosticRenderer() = default;
Ted Kremenekc4bbd852011-12-17 05:26:04 +000038
Ted Kremenekf7639e12012-03-06 20:06:33 +000039namespace {
40
41class FixitReceiver : public edit::EditsReceiver {
42 SmallVectorImpl<FixItHint> &MergedFixits;
43
44public:
45 FixitReceiver(SmallVectorImpl<FixItHint> &MergedFixits)
Eugene Zelenko4f233182018-03-22 00:53:26 +000046 : MergedFixits(MergedFixits) {}
47
Craig Topperafa7cb32014-03-13 06:07:04 +000048 void insert(SourceLocation loc, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000049 MergedFixits.push_back(FixItHint::CreateInsertion(loc, text));
50 }
Eugene Zelenko4f233182018-03-22 00:53:26 +000051
Craig Topperafa7cb32014-03-13 06:07:04 +000052 void replace(CharSourceRange range, StringRef text) override {
Ted Kremenekf7639e12012-03-06 20:06:33 +000053 MergedFixits.push_back(FixItHint::CreateReplacement(range, text));
54 }
55};
56
Eugene Zelenko4f233182018-03-22 00:53:26 +000057} // namespace
Ted Kremenekf7639e12012-03-06 20:06:33 +000058
59static void mergeFixits(ArrayRef<FixItHint> FixItHints,
60 const SourceManager &SM, const LangOptions &LangOpts,
61 SmallVectorImpl<FixItHint> &MergedFixits) {
62 edit::Commit commit(SM, LangOpts);
Eugene Zelenko4f233182018-03-22 00:53:26 +000063 for (const auto &Hint : FixItHints)
Ted Kremenekf7639e12012-03-06 20:06:33 +000064 if (Hint.CodeToInsert.empty()) {
65 if (Hint.InsertFromRange.isValid())
66 commit.insertFromRange(Hint.RemoveRange.getBegin(),
67 Hint.InsertFromRange, /*afterToken=*/false,
68 Hint.BeforePreviousInsertions);
69 else
70 commit.remove(Hint.RemoveRange);
71 } else {
72 if (Hint.RemoveRange.isTokenRange() ||
73 Hint.RemoveRange.getBegin() != Hint.RemoveRange.getEnd())
74 commit.replace(Hint.RemoveRange, Hint.CodeToInsert);
75 else
76 commit.insert(Hint.RemoveRange.getBegin(), Hint.CodeToInsert,
77 /*afterToken=*/false, Hint.BeforePreviousInsertions);
78 }
Ted Kremenekf7639e12012-03-06 20:06:33 +000079
80 edit::EditedSource Editor(SM, LangOpts);
81 if (Editor.commit(commit)) {
82 FixitReceiver Rec(MergedFixits);
83 Editor.applyRewrites(Rec);
84 }
85}
Ted Kremenekc4bbd852011-12-17 05:26:04 +000086
Christof Doumafb4a0452017-06-27 09:50:38 +000087void DiagnosticRenderer::emitDiagnostic(FullSourceLoc Loc,
Ted Kremenekc4bbd852011-12-17 05:26:04 +000088 DiagnosticsEngine::Level Level,
89 StringRef Message,
90 ArrayRef<CharSourceRange> Ranges,
91 ArrayRef<FixItHint> FixItHints,
Ted Kremenek0964cca2012-02-14 02:46:00 +000092 DiagOrStoredDiag D) {
Christof Doumafb4a0452017-06-27 09:50:38 +000093 assert(Loc.hasManager() || Loc.isInvalid());
Richard Smithc01cca22012-12-05 09:47:49 +000094
Ted Kremenek0964cca2012-02-14 02:46:00 +000095 beginDiagnostic(D, Level);
Richard Smithc01cca22012-12-05 09:47:49 +000096
97 if (!Loc.isValid())
98 // If we have no source location, just emit the diagnostic message.
Christof Doumafb4a0452017-06-27 09:50:38 +000099 emitDiagnosticMessage(Loc, PresumedLoc(), Level, Message, Ranges, D);
Richard Smithc01cca22012-12-05 09:47:49 +0000100 else {
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000101 // Get the ranges into a local array we can hack on.
102 SmallVector<CharSourceRange, 20> MutableRanges(Ranges.begin(),
103 Ranges.end());
Richard Smithc01cca22012-12-05 09:47:49 +0000104
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000105 SmallVector<FixItHint, 8> MergedFixits;
Ted Kremenekf7639e12012-03-06 20:06:33 +0000106 if (!FixItHints.empty()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000107 mergeFixits(FixItHints, Loc.getManager(), LangOpts, MergedFixits);
Ted Kremenekf7639e12012-03-06 20:06:33 +0000108 FixItHints = MergedFixits;
109 }
110
Eugene Zelenko4f233182018-03-22 00:53:26 +0000111 for (const auto &Hint : FixItHints)
112 if (Hint.RemoveRange.isValid())
113 MutableRanges.push_back(Hint.RemoveRange);
Richard Smithaebee682012-12-05 06:20:58 +0000114
Christof Doumafb4a0452017-06-27 09:50:38 +0000115 FullSourceLoc UnexpandedLoc = Loc;
Richard Smithaebee682012-12-05 06:20:58 +0000116
Ted Kremenek372735f2012-12-19 01:16:49 +0000117 // Find the ultimate expansion location for the diagnostic.
Christof Doumafb4a0452017-06-27 09:50:38 +0000118 Loc = Loc.getFileLoc();
Richard Smithc01cca22012-12-05 09:47:49 +0000119
Christof Doumafb4a0452017-06-27 09:50:38 +0000120 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Richard Smithc01cca22012-12-05 09:47:49 +0000121
122 // First, if this diagnostic is not in the main file, print out the
123 // "included from" lines.
Christof Doumafb4a0452017-06-27 09:50:38 +0000124 emitIncludeStack(Loc, PLoc, Level);
Richard Smithc01cca22012-12-05 09:47:49 +0000125
126 // Next, emit the actual diagnostic message and caret.
Christof Doumafb4a0452017-06-27 09:50:38 +0000127 emitDiagnosticMessage(Loc, PLoc, Level, Message, Ranges, D);
128 emitCaret(Loc, Level, MutableRanges, FixItHints);
Richard Smithc01cca22012-12-05 09:47:49 +0000129
130 // If this location is within a macro, walk from UnexpandedLoc up to Loc
131 // and produce a macro backtrace.
132 if (UnexpandedLoc.isValid() && UnexpandedLoc.isMacroID()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000133 emitMacroExpansions(UnexpandedLoc, Level, MutableRanges, FixItHints);
Richard Smithaebee682012-12-05 06:20:58 +0000134 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000135 }
Richard Smithc01cca22012-12-05 09:47:49 +0000136
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000137 LastLoc = Loc;
138 LastLevel = Level;
Richard Smithc01cca22012-12-05 09:47:49 +0000139
Ted Kremenek0964cca2012-02-14 02:46:00 +0000140 endDiagnostic(D, Level);
141}
142
Ted Kremenek0964cca2012-02-14 02:46:00 +0000143void DiagnosticRenderer::emitStoredDiagnostic(StoredDiagnostic &Diag) {
144 emitDiagnostic(Diag.getLocation(), Diag.getLevel(), Diag.getMessage(),
145 Diag.getRanges(), Diag.getFixIts(),
146 &Diag);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000147}
148
Alp Toker4db87ab2014-06-21 23:31:59 +0000149void DiagnosticRenderer::emitBasicNote(StringRef Message) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000150 emitDiagnosticMessage(FullSourceLoc(), PresumedLoc(), DiagnosticsEngine::Note,
151 Message, None, DiagOrStoredDiag());
Alp Toker4db87ab2014-06-21 23:31:59 +0000152}
153
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000154/// Prints an include stack when appropriate for a particular
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000155/// diagnostic level and location.
156///
157/// This routine handles all the logic of suppressing particular include
158/// stacks (such as those for notes) and duplicate include stacks when
159/// repeated warnings occur within the same file. It also handles the logic
160/// of customizing the formatting and display of the include stack.
161///
Douglas Gregor22103e32012-11-30 21:58:49 +0000162/// \param Loc The diagnostic location.
163/// \param PLoc The presumed location of the diagnostic location.
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000164/// \param Level The diagnostic level of the message this stack pertains to.
Christof Doumafb4a0452017-06-27 09:50:38 +0000165void DiagnosticRenderer::emitIncludeStack(FullSourceLoc Loc, PresumedLoc PLoc,
166 DiagnosticsEngine::Level Level) {
167 FullSourceLoc IncludeLoc =
168 PLoc.isInvalid() ? FullSourceLoc()
169 : FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager());
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;
Fangrui Song6907ce22018-07-30 19:24:48 +0000174
Douglas Gregor22103e32012-11-30 21:58:49 +0000175 LastIncludeLoc = IncludeLoc;
Fangrui Song6907ce22018-07-30 19:24:48 +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())
Christof Doumafb4a0452017-06-27 09:50:38 +0000181 emitIncludeStackRecursively(IncludeLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000182 else {
Christof Doumafb4a0452017-06-27 09:50:38 +0000183 emitModuleBuildStack(Loc.getManager());
184 emitImportStack(Loc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000185 }
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000186}
187
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000188/// Helper to recursively walk up the include stack and print each layer
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000189/// on the way back down.
Christof Doumafb4a0452017-06-27 09:50:38 +0000190void DiagnosticRenderer::emitIncludeStackRecursively(FullSourceLoc Loc) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000191 if (Loc.isInvalid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000192 emitModuleBuildStack(Loc.getManager());
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000193 return;
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000194 }
Christof Doumafb4a0452017-06-27 09:50:38 +0000195
196 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000197 if (PLoc.isInvalid())
198 return;
Douglas Gregor22103e32012-11-30 21:58:49 +0000199
200 // If this source location was imported from a module, print the module
Fangrui Song6907ce22018-07-30 19:24:48 +0000201 // import stack rather than the
Douglas Gregor22103e32012-11-30 21:58:49 +0000202 // FIXME: We want submodule granularity here.
Christof Doumafb4a0452017-06-27 09:50:38 +0000203 std::pair<FullSourceLoc, StringRef> Imported = Loc.getModuleImportLoc();
Richard Smitha24ff552015-08-11 00:05:21 +0000204 if (!Imported.second.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000205 // This location was imported by a module. Emit the module import stack.
Christof Doumafb4a0452017-06-27 09:50:38 +0000206 emitImportStackRecursively(Imported.first, Imported.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000207 return;
208 }
209
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000210 // Emit the other include frames first.
Christof Doumafb4a0452017-06-27 09:50:38 +0000211 emitIncludeStackRecursively(
212 FullSourceLoc(PLoc.getIncludeLoc(), Loc.getManager()));
213
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000214 // Emit the inclusion text/note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000215 emitIncludeLocation(Loc, PLoc);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000216}
217
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000218/// Emit the module import stack associated with the current location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000219void DiagnosticRenderer::emitImportStack(FullSourceLoc Loc) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000220 if (Loc.isInvalid()) {
Christof Doumafb4a0452017-06-27 09:50:38 +0000221 emitModuleBuildStack(Loc.getManager());
Douglas Gregor22103e32012-11-30 21:58:49 +0000222 return;
223 }
224
Christof Doumafb4a0452017-06-27 09:50:38 +0000225 std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
226 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000227}
228
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000229/// Helper to recursively walk up the import stack and print each layer
Douglas Gregor22103e32012-11-30 21:58:49 +0000230/// on the way back down.
Christof Doumafb4a0452017-06-27 09:50:38 +0000231void DiagnosticRenderer::emitImportStackRecursively(FullSourceLoc Loc,
232 StringRef ModuleName) {
Richard Smitha24ff552015-08-11 00:05:21 +0000233 if (ModuleName.empty()) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000234 return;
235 }
236
Christof Doumafb4a0452017-06-27 09:50:38 +0000237 PresumedLoc PLoc = Loc.getPresumedLoc(DiagOpts->ShowPresumedLoc);
Douglas Gregor22103e32012-11-30 21:58:49 +0000238
239 // Emit the other import frames first.
Christof Doumafb4a0452017-06-27 09:50:38 +0000240 std::pair<FullSourceLoc, StringRef> NextImportLoc = Loc.getModuleImportLoc();
241 emitImportStackRecursively(NextImportLoc.first, NextImportLoc.second);
Douglas Gregor22103e32012-11-30 21:58:49 +0000242
243 // Emit the inclusion text/note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000244 emitImportLocation(Loc, PLoc, ModuleName);
Douglas Gregor22103e32012-11-30 21:58:49 +0000245}
246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000247/// Emit the module build stack, for cases where a module is (re-)built
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000248/// on demand.
Douglas Gregor63365432012-11-30 22:11:57 +0000249void DiagnosticRenderer::emitModuleBuildStack(const SourceManager &SM) {
250 ModuleBuildStack Stack = SM.getModuleBuildStack();
Eugene Zelenko4f233182018-03-22 00:53:26 +0000251 for (const auto &I : Stack) {
252 emitBuildingModuleLocation(I.second, I.second.getPresumedLoc(
253 DiagOpts->ShowPresumedLoc),
254 I.first);
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000255 }
256}
257
Richard Trieuc3096242015-09-24 01:21:01 +0000258/// A recursive function to trace all possible backtrace locations
259/// to match the \p CaretLocFileID.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000260static SourceLocation
261retrieveMacroLocation(SourceLocation Loc, FileID MacroFileID,
262 FileID CaretFileID,
263 const SmallVectorImpl<FileID> &CommonArgExpansions,
Richard Smithb5f81712018-04-30 05:25:48 +0000264 bool IsBegin, const SourceManager *SM,
265 bool &IsTokenRange) {
Reid Klecknerda30cff2015-12-08 01:08:09 +0000266 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
Richard Smithb5f81712018-04-30 05:25:48 +0000272 CharSourceRange MacroRange, MacroArgRange;
Richard Trieuc3096242015-09-24 01:21:01 +0000273
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))
Richard Smithb5f81712018-04-30 05:25:48 +0000279 MacroRange =
280 CharSourceRange(SM->getImmediateSpellingLoc(Loc), IsTokenRange);
281 MacroArgRange = SM->getImmediateExpansionRange(Loc);
Richard Trieuc3096242015-09-24 01:21:01 +0000282 } else {
Richard Smithb5f81712018-04-30 05:25:48 +0000283 MacroRange = SM->getImmediateExpansionRange(Loc);
284 MacroArgRange =
285 CharSourceRange(SM->getImmediateSpellingLoc(Loc), IsTokenRange);
Richard Trieuc3096242015-09-24 01:21:01 +0000286 }
287
Richard Smithb5f81712018-04-30 05:25:48 +0000288 SourceLocation MacroLocation =
289 IsBegin ? MacroRange.getBegin() : MacroRange.getEnd();
Reid Klecknerda30cff2015-12-08 01:08:09 +0000290 if (MacroLocation.isValid()) {
291 MacroFileID = SM->getFileID(MacroLocation);
Richard Smithb5f81712018-04-30 05:25:48 +0000292 bool TokenRange = IsBegin ? IsTokenRange : MacroRange.isTokenRange();
Reid Klecknerda30cff2015-12-08 01:08:09 +0000293 MacroLocation =
294 retrieveMacroLocation(MacroLocation, MacroFileID, CaretFileID,
Richard Smithb5f81712018-04-30 05:25:48 +0000295 CommonArgExpansions, IsBegin, SM, TokenRange);
296 if (MacroLocation.isValid()) {
297 IsTokenRange = TokenRange;
Reid Klecknerda30cff2015-12-08 01:08:09 +0000298 return MacroLocation;
Richard Smithb5f81712018-04-30 05:25:48 +0000299 }
Reid Klecknerda30cff2015-12-08 01:08:09 +0000300 }
Richard Trieuc3096242015-09-24 01:21:01 +0000301
Richard Smithb5f81712018-04-30 05:25:48 +0000302 // If we moved the end of the range to an expansion location, we now have
303 // a range of the same kind as the expansion range.
304 if (!IsBegin)
305 IsTokenRange = MacroArgRange.isTokenRange();
306
307 SourceLocation MacroArgLocation =
308 IsBegin ? MacroArgRange.getBegin() : MacroArgRange.getEnd();
Richard Trieuc3096242015-09-24 01:21:01 +0000309 MacroFileID = SM->getFileID(MacroArgLocation);
310 return retrieveMacroLocation(MacroArgLocation, MacroFileID, CaretFileID,
Richard Smithb5f81712018-04-30 05:25:48 +0000311 CommonArgExpansions, IsBegin, SM, IsTokenRange);
Reid Klecknerda30cff2015-12-08 01:08:09 +0000312}
313
314/// Walk up the chain of macro expansions and collect the FileIDs identifying the
315/// expansions.
316static void getMacroArgExpansionFileIDs(SourceLocation Loc,
317 SmallVectorImpl<FileID> &IDs,
318 bool IsBegin, const SourceManager *SM) {
319 while (Loc.isMacroID()) {
320 if (SM->isMacroArgExpansion(Loc)) {
321 IDs.push_back(SM->getFileID(Loc));
322 Loc = SM->getImmediateSpellingLoc(Loc);
323 } else {
324 auto ExpRange = SM->getImmediateExpansionRange(Loc);
Richard Smithb5f81712018-04-30 05:25:48 +0000325 Loc = IsBegin ? ExpRange.getBegin() : ExpRange.getEnd();
Reid Klecknerda30cff2015-12-08 01:08:09 +0000326 }
327 }
328}
329
330/// Collect the expansions of the begin and end locations and compute the set
331/// intersection. Produces a sorted vector of FileIDs in CommonArgExpansions.
332static void computeCommonMacroArgExpansionFileIDs(
333 SourceLocation Begin, SourceLocation End, const SourceManager *SM,
334 SmallVectorImpl<FileID> &CommonArgExpansions) {
335 SmallVector<FileID, 4> BeginArgExpansions;
336 SmallVector<FileID, 4> EndArgExpansions;
337 getMacroArgExpansionFileIDs(Begin, BeginArgExpansions, /*IsBegin=*/true, SM);
338 getMacroArgExpansionFileIDs(End, EndArgExpansions, /*IsBegin=*/false, SM);
Fangrui Song55fab262018-09-26 22:16:28 +0000339 llvm::sort(BeginArgExpansions);
340 llvm::sort(EndArgExpansions);
Reid Klecknerda30cff2015-12-08 01:08:09 +0000341 std::set_intersection(BeginArgExpansions.begin(), BeginArgExpansions.end(),
342 EndArgExpansions.begin(), EndArgExpansions.end(),
343 std::back_inserter(CommonArgExpansions));
Richard Trieuc3096242015-09-24 01:21:01 +0000344}
345
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000346// Helper function to fix up source ranges. It takes in an array of ranges,
347// and outputs an array of ranges where we want to draw the range highlighting
348// around the location specified by CaretLoc.
349//
350// To find locations which correspond to the caret, we crawl the macro caller
351// chain for the beginning and end of each range. If the caret location
352// is in a macro expansion, we search each chain for a location
353// in the same expansion as the caret; otherwise, we crawl to the top of
354// each chain. Two locations are part of the same macro expansion
355// iff the FileID is the same.
Christof Doumafb4a0452017-06-27 09:50:38 +0000356static void
357mapDiagnosticRanges(FullSourceLoc CaretLoc, ArrayRef<CharSourceRange> Ranges,
358 SmallVectorImpl<CharSourceRange> &SpellingRanges) {
359 FileID CaretLocFileID = CaretLoc.getFileID();
360
361 const SourceManager *SM = &CaretLoc.getManager();
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000362
Eugene Zelenko4f233182018-03-22 00:53:26 +0000363 for (const auto &Range : Ranges) {
364 if (Range.isInvalid())
365 continue;
Richard Trieuc3096242015-09-24 01:21:01 +0000366
Eugene Zelenko4f233182018-03-22 00:53:26 +0000367 SourceLocation Begin = Range.getBegin(), End = Range.getEnd();
368 bool IsTokenRange = Range.isTokenRange();
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000369
Eli Friedmandea98de2012-11-30 06:19:40 +0000370 FileID BeginFileID = SM->getFileID(Begin);
Nadav Rotemb8937342012-12-13 19:58:10 +0000371 FileID EndFileID = SM->getFileID(End);
Eli Friedmandea98de2012-11-30 06:19:40 +0000372
Nadav Rotemb8937342012-12-13 19:58:10 +0000373 // Find the common parent for the beginning and end of the range.
374
375 // First, crawl the expansion chain for the beginning of the range.
376 llvm::SmallDenseMap<FileID, SourceLocation> BeginLocsMap;
377 while (Begin.isMacroID() && BeginFileID != EndFileID) {
378 BeginLocsMap[BeginFileID] = Begin;
Richard Smithb5f81712018-04-30 05:25:48 +0000379 Begin = SM->getImmediateExpansionRange(Begin).getBegin();
Nadav Rotemb8937342012-12-13 19:58:10 +0000380 BeginFileID = SM->getFileID(Begin);
381 }
382
383 // Then, crawl the expansion chain for the end of the range.
384 if (BeginFileID != EndFileID) {
385 while (End.isMacroID() && !BeginLocsMap.count(EndFileID)) {
Richard Smithb5f81712018-04-30 05:25:48 +0000386 auto Exp = SM->getImmediateExpansionRange(End);
387 IsTokenRange = Exp.isTokenRange();
388 End = Exp.getEnd();
Nadav Rotemb8937342012-12-13 19:58:10 +0000389 EndFileID = SM->getFileID(End);
390 }
391 if (End.isMacroID()) {
392 Begin = BeginLocsMap[EndFileID];
393 BeginFileID = EndFileID;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000394 }
Eli Friedmancdb135a2012-12-13 00:14:59 +0000395 }
396
Richard Trieuc3096242015-09-24 01:21:01 +0000397 // Do the backtracking.
Reid Klecknerda30cff2015-12-08 01:08:09 +0000398 SmallVector<FileID, 4> CommonArgExpansions;
399 computeCommonMacroArgExpansionFileIDs(Begin, End, SM, CommonArgExpansions);
Richard Trieuc3096242015-09-24 01:21:01 +0000400 Begin = retrieveMacroLocation(Begin, BeginFileID, CaretLocFileID,
Richard Smithb5f81712018-04-30 05:25:48 +0000401 CommonArgExpansions, /*IsBegin=*/true, SM,
402 IsTokenRange);
Richard Trieuc3096242015-09-24 01:21:01 +0000403 End = retrieveMacroLocation(End, BeginFileID, CaretLocFileID,
Richard Smithb5f81712018-04-30 05:25:48 +0000404 CommonArgExpansions, /*IsBegin=*/false, SM,
405 IsTokenRange);
Richard Trieuc3096242015-09-24 01:21:01 +0000406 if (Begin.isInvalid() || End.isInvalid()) continue;
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000407
408 // Return the spelling location of the beginning and end of the range.
409 Begin = SM->getSpellingLoc(Begin);
410 End = SM->getSpellingLoc(End);
Richard Trieuc3096242015-09-24 01:21:01 +0000411
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000412 SpellingRanges.push_back(CharSourceRange(SourceRange(Begin, End),
413 IsTokenRange));
414 }
415}
416
Christof Doumafb4a0452017-06-27 09:50:38 +0000417void DiagnosticRenderer::emitCaret(FullSourceLoc Loc,
Richard Smithaebee682012-12-05 06:20:58 +0000418 DiagnosticsEngine::Level Level,
419 ArrayRef<CharSourceRange> Ranges,
Christof Doumafb4a0452017-06-27 09:50:38 +0000420 ArrayRef<FixItHint> Hints) {
Richard Smithaebee682012-12-05 06:20:58 +0000421 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000422 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
423 emitCodeContext(Loc, Level, SpellingRanges, Hints);
Richard Smithaebee682012-12-05 06:20:58 +0000424}
425
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000426/// A helper function for emitMacroExpansion to print the
Richard Trieu97c45b62015-07-28 20:53:46 +0000427/// macro expansion message
428void DiagnosticRenderer::emitSingleMacroExpansion(
Christof Doumafb4a0452017-06-27 09:50:38 +0000429 FullSourceLoc Loc, DiagnosticsEngine::Level Level,
430 ArrayRef<CharSourceRange> Ranges) {
Richard Smith7a2d40d2012-12-05 03:18:16 +0000431 // Find the spelling location for the macro definition. We must use the
Richard Trieu97c45b62015-07-28 20:53:46 +0000432 // spelling location here to avoid emitting a macro backtrace for the note.
Christof Doumafb4a0452017-06-27 09:50:38 +0000433 FullSourceLoc SpellingLoc = Loc.getSpellingLoc();
Richard Smith7a2d40d2012-12-05 03:18:16 +0000434
435 // Map the ranges into the FileID of the diagnostic location.
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000436 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000437 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
Eli Friedman34ff0ea2012-11-03 03:36:51 +0000438
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000439 SmallString<100> MessageStorage;
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000440 llvm::raw_svector_ostream Message(MessageStorage);
Christof Doumafb4a0452017-06-27 09:50:38 +0000441 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
442 Loc, Loc.getManager(), LangOpts);
Richard Smithf89e2e22012-12-05 11:04:55 +0000443 if (MacroName.empty())
444 Message << "expanded from here";
445 else
446 Message << "expanded from macro '" << MacroName << "'";
Richard Trieu97c45b62015-07-28 20:53:46 +0000447
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +0000448 emitDiagnostic(SpellingLoc, DiagnosticsEngine::Note, Message.str(),
Christof Doumafb4a0452017-06-27 09:50:38 +0000449 SpellingRanges, None);
Ted Kremenekc4bbd852011-12-17 05:26:04 +0000450}
451
Richard Trieuc3096242015-09-24 01:21:01 +0000452/// Check that the macro argument location of Loc starts with ArgumentLoc.
453/// The starting location of the macro expansions is used to differeniate
454/// different macro expansions.
455static bool checkLocForMacroArgExpansion(SourceLocation Loc,
456 const SourceManager &SM,
457 SourceLocation ArgumentLoc) {
458 SourceLocation MacroLoc;
459 if (SM.isMacroArgExpansion(Loc, &MacroLoc)) {
460 if (ArgumentLoc == MacroLoc) return true;
461 }
462
463 return false;
464}
465
466/// Check if all the locations in the range have the same macro argument
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +0000467/// expansion, and that the expansion starts with ArgumentLoc.
Richard Trieuecd36ee2015-08-12 18:24:59 +0000468static bool checkRangeForMacroArgExpansion(CharSourceRange Range,
Richard Trieuc3096242015-09-24 01:21:01 +0000469 const SourceManager &SM,
470 SourceLocation ArgumentLoc) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000471 SourceLocation BegLoc = Range.getBegin(), EndLoc = Range.getEnd();
472 while (BegLoc != EndLoc) {
Richard Trieuc3096242015-09-24 01:21:01 +0000473 if (!checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000474 return false;
475 BegLoc.getLocWithOffset(1);
476 }
477
Richard Trieuc3096242015-09-24 01:21:01 +0000478 return checkLocForMacroArgExpansion(BegLoc, SM, ArgumentLoc);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000479}
480
Richard Trieuc3096242015-09-24 01:21:01 +0000481/// A helper function to check if the current ranges are all inside the same
482/// macro argument expansion as Loc.
Christof Doumafb4a0452017-06-27 09:50:38 +0000483static bool checkRangesForMacroArgExpansion(FullSourceLoc Loc,
484 ArrayRef<CharSourceRange> Ranges) {
Richard Trieuecd36ee2015-08-12 18:24:59 +0000485 assert(Loc.isMacroID() && "Must be a macro expansion!");
486
487 SmallVector<CharSourceRange, 4> SpellingRanges;
Christof Doumafb4a0452017-06-27 09:50:38 +0000488 mapDiagnosticRanges(Loc, Ranges, SpellingRanges);
Richard Trieuecd36ee2015-08-12 18:24:59 +0000489
Richard Trieuc3096242015-09-24 01:21:01 +0000490 /// Count all valid ranges.
491 unsigned ValidCount = 0;
Eugene Zelenko4f233182018-03-22 00:53:26 +0000492 for (const auto &Range : Ranges)
493 if (Range.isValid())
494 ValidCount++;
Richard Trieuc3096242015-09-24 01:21:01 +0000495
496 if (ValidCount > SpellingRanges.size())
Richard Trieuecd36ee2015-08-12 18:24:59 +0000497 return false;
498
Richard Trieuc3096242015-09-24 01:21:01 +0000499 /// To store the source location of the argument location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000500 FullSourceLoc ArgumentLoc;
Richard Trieuc3096242015-09-24 01:21:01 +0000501
502 /// Set the ArgumentLoc to the beginning location of the expansion of Loc
503 /// so to check if the ranges expands to the same beginning location.
Christof Doumafb4a0452017-06-27 09:50:38 +0000504 if (!Loc.isMacroArgExpansion(&ArgumentLoc))
Richard Trieuc3096242015-09-24 01:21:01 +0000505 return false;
506
Eugene Zelenko4f233182018-03-22 00:53:26 +0000507 for (const auto &Range : SpellingRanges)
508 if (!checkRangeForMacroArgExpansion(Range, Loc.getManager(), ArgumentLoc))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000509 return false;
510
511 return true;
512}
513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000514/// Recursively emit notes for each macro expansion and caret
Richard Trieu97c45b62015-07-28 20:53:46 +0000515/// diagnostics where appropriate.
516///
517/// Walks up the macro expansion stack printing expansion notes, the code
518/// snippet, caret, underlines and FixItHint display as appropriate at each
519/// level.
520///
521/// \param Loc The location for this caret.
522/// \param Level The diagnostic level currently being emitted.
523/// \param Ranges The underlined ranges for this code snippet.
524/// \param Hints The FixIt hints active for this diagnostic.
Christof Doumafb4a0452017-06-27 09:50:38 +0000525void DiagnosticRenderer::emitMacroExpansions(FullSourceLoc Loc,
Richard Trieu97c45b62015-07-28 20:53:46 +0000526 DiagnosticsEngine::Level Level,
527 ArrayRef<CharSourceRange> Ranges,
Christof Doumafb4a0452017-06-27 09:50:38 +0000528 ArrayRef<FixItHint> Hints) {
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000529 assert(Loc.isValid() && "must have a valid source location here");
Richard Smithb5f81712018-04-30 05:25:48 +0000530 const SourceManager &SM = Loc.getManager();
531 SourceLocation L = Loc;
Richard Trieu97c45b62015-07-28 20:53:46 +0000532
533 // Produce a stack of macro backtraces.
Richard Smithb5f81712018-04-30 05:25:48 +0000534 SmallVector<SourceLocation, 8> LocationStack;
Richard Trieuecd36ee2015-08-12 18:24:59 +0000535 unsigned IgnoredEnd = 0;
Richard Smithb5f81712018-04-30 05:25:48 +0000536 while (L.isMacroID()) {
Richard Trieua1d7ece2015-08-27 23:38:45 +0000537 // If this is the expansion of a macro argument, point the caret at the
538 // use of the argument in the definition of the macro, not the expansion.
Richard Smithb5f81712018-04-30 05:25:48 +0000539 if (SM.isMacroArgExpansion(L))
540 LocationStack.push_back(SM.getImmediateExpansionRange(L).getBegin());
Richard Trieua1d7ece2015-08-27 23:38:45 +0000541 else
Richard Smithb5f81712018-04-30 05:25:48 +0000542 LocationStack.push_back(L);
Richard Trieua1d7ece2015-08-27 23:38:45 +0000543
Richard Smithb5f81712018-04-30 05:25:48 +0000544 if (checkRangesForMacroArgExpansion(FullSourceLoc(L, SM), Ranges))
Richard Trieuecd36ee2015-08-12 18:24:59 +0000545 IgnoredEnd = LocationStack.size();
546
Richard Smithb5f81712018-04-30 05:25:48 +0000547 L = SM.getImmediateMacroCallerLoc(L);
Richard Trieua1d7ece2015-08-27 23:38:45 +0000548
549 // Once the location no longer points into a macro, try stepping through
550 // the last found location. This sometimes produces additional useful
551 // backtraces.
Richard Smithb5f81712018-04-30 05:25:48 +0000552 if (L.isFileID())
553 L = SM.getImmediateMacroCallerLoc(LocationStack.back());
554 assert(L.isValid() && "must have a valid source location here");
Richard Trieu97c45b62015-07-28 20:53:46 +0000555 }
556
Richard Trieuecd36ee2015-08-12 18:24:59 +0000557 LocationStack.erase(LocationStack.begin(),
558 LocationStack.begin() + IgnoredEnd);
559
Richard Trieu97c45b62015-07-28 20:53:46 +0000560 unsigned MacroDepth = LocationStack.size();
561 unsigned MacroLimit = DiagOpts->MacroBacktraceLimit;
562 if (MacroDepth <= MacroLimit || MacroLimit == 0) {
563 for (auto I = LocationStack.rbegin(), E = LocationStack.rend();
564 I != E; ++I)
Richard Smithb5f81712018-04-30 05:25:48 +0000565 emitSingleMacroExpansion(FullSourceLoc(*I, SM), Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000566 return;
567 }
568
569 unsigned MacroStartMessages = MacroLimit / 2;
570 unsigned MacroEndMessages = MacroLimit / 2 + MacroLimit % 2;
571
572 for (auto I = LocationStack.rbegin(),
573 E = LocationStack.rbegin() + MacroStartMessages;
574 I != E; ++I)
Richard Smithb5f81712018-04-30 05:25:48 +0000575 emitSingleMacroExpansion(FullSourceLoc(*I, SM), Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000576
577 SmallString<200> MessageStorage;
578 llvm::raw_svector_ostream Message(MessageStorage);
579 Message << "(skipping " << (MacroDepth - MacroLimit)
580 << " expansions in backtrace; use -fmacro-backtrace-limit=0 to "
581 "see all)";
582 emitBasicNote(Message.str());
583
584 for (auto I = LocationStack.rend() - MacroEndMessages,
585 E = LocationStack.rend();
586 I != E; ++I)
Richard Smithb5f81712018-04-30 05:25:48 +0000587 emitSingleMacroExpansion(FullSourceLoc(*I, SM), Level, Ranges);
Richard Trieu97c45b62015-07-28 20:53:46 +0000588}
589
Eugene Zelenko4f233182018-03-22 00:53:26 +0000590DiagnosticNoteRenderer::~DiagnosticNoteRenderer() = default;
Ted Kremenek0964cca2012-02-14 02:46:00 +0000591
Christof Doumafb4a0452017-06-27 09:50:38 +0000592void DiagnosticNoteRenderer::emitIncludeLocation(FullSourceLoc Loc,
593 PresumedLoc PLoc) {
Ted Kremenek0964cca2012-02-14 02:46:00 +0000594 // Generate a note indicating the include location.
595 SmallString<200> MessageStorage;
596 llvm::raw_svector_ostream Message(MessageStorage);
597 Message << "in file included from " << PLoc.getFilename() << ':'
598 << PLoc.getLine() << ":";
Christof Doumafb4a0452017-06-27 09:50:38 +0000599 emitNote(Loc, Message.str());
Ted Kremenek0964cca2012-02-14 02:46:00 +0000600}
601
Christof Doumafb4a0452017-06-27 09:50:38 +0000602void DiagnosticNoteRenderer::emitImportLocation(FullSourceLoc Loc,
Douglas Gregor22103e32012-11-30 21:58:49 +0000603 PresumedLoc PLoc,
Christof Doumafb4a0452017-06-27 09:50:38 +0000604 StringRef ModuleName) {
Douglas Gregor22103e32012-11-30 21:58:49 +0000605 // Generate a note indicating the include location.
606 SmallString<200> MessageStorage;
607 llvm::raw_svector_ostream Message(MessageStorage);
Richard Smitha24ff552015-08-11 00:05:21 +0000608 Message << "in module '" << ModuleName;
Yaron Kerened1fe5d2015-10-03 05:15:57 +0000609 if (PLoc.isValid())
Richard Smitha24ff552015-08-11 00:05:21 +0000610 Message << "' imported from " << PLoc.getFilename() << ':'
611 << PLoc.getLine();
612 Message << ":";
Christof Doumafb4a0452017-06-27 09:50:38 +0000613 emitNote(Loc, Message.str());
Douglas Gregor22103e32012-11-30 21:58:49 +0000614}
615
Christof Doumafb4a0452017-06-27 09:50:38 +0000616void DiagnosticNoteRenderer::emitBuildingModuleLocation(FullSourceLoc Loc,
617 PresumedLoc PLoc,
618 StringRef ModuleName) {
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000619 // Generate a note indicating the include location.
620 SmallString<200> MessageStorage;
621 llvm::raw_svector_ostream Message(MessageStorage);
Jordan Rose602ac142016-06-28 01:02:31 +0000622 if (PLoc.isValid())
Richard Smith7bea1d42014-03-05 20:55:36 +0000623 Message << "while building module '" << ModuleName << "' imported from "
624 << PLoc.getFilename() << ':' << PLoc.getLine() << ":";
625 else
Jordan Rose6dcdaa62014-07-26 01:22:02 +0000626 Message << "while building module '" << ModuleName << "':";
Christof Doumafb4a0452017-06-27 09:50:38 +0000627 emitNote(Loc, Message.str());
Douglas Gregoraf8f0262012-11-30 18:38:50 +0000628}