blob: 47f6a139b15ab4d5d069e56320355afb20a1038d [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Diagnostic-related interfaces.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek39a76652010-04-12 19:54:17 +000014#include "clang/Basic/Diagnostic.h"
Alex Lorenzd0e27262017-08-25 15:48:00 +000015#include "clang/Basic/CharInfo.h"
16#include "clang/Basic/DiagnosticError.h"
Douglas Gregor811db4e2012-10-23 22:26:28 +000017#include "clang/Basic/DiagnosticOptions.h"
Chris Lattnerb91fd172008-11-19 07:32:16 +000018#include "clang/Basic/IdentifierTable.h"
Ted Kremenek39a76652010-04-12 19:54:17 +000019#include "clang/Basic/PartialDiagnostic.h"
Benjamin Kramerbc9ef592017-01-18 15:50:26 +000020#include "clang/Basic/SourceManager.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000021#include "llvm/ADT/SmallString.h"
Jordan Rosec102b352012-09-22 01:24:42 +000022#include "llvm/ADT/StringExtras.h"
Ted Kremenek84de4a12011-03-21 18:40:07 +000023#include "llvm/Support/CrashRecoveryContext.h"
Richard Trieub3b8bb02015-01-08 01:27:03 +000024#include "llvm/Support/Locale.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "llvm/Support/raw_ostream.h"
Ted Kremenek84de4a12011-03-21 18:40:07 +000026
Chris Lattner22eb9722006-06-18 05:43:12 +000027using namespace clang;
28
Douglas Gregoraea7afd2015-06-24 22:02:08 +000029const DiagnosticBuilder &clang::operator<<(const DiagnosticBuilder &DB,
30 DiagNullabilityKind nullability) {
31 StringRef string;
32 switch (nullability.first) {
33 case NullabilityKind::NonNull:
34 string = nullability.second ? "'nonnull'" : "'_Nonnull'";
35 break;
36
37 case NullabilityKind::Nullable:
38 string = nullability.second ? "'nullable'" : "'_Nullable'";
39 break;
40
41 case NullabilityKind::Unspecified:
42 string = nullability.second ? "'null_unspecified'" : "'_Null_unspecified'";
43 break;
44 }
45
46 DB.AddString(string);
47 return DB;
48}
49
David Blaikie9c902b52011-09-25 23:23:43 +000050static void DummyArgToStringFn(DiagnosticsEngine::ArgumentKind AK, intptr_t QT,
Craig Topper3aa4fb32014-06-12 05:32:35 +000051 StringRef Modifier, StringRef Argument,
Craig Toppere4753502014-06-12 05:32:27 +000052 ArrayRef<DiagnosticsEngine::ArgumentValue> PrevArgs,
53 SmallVectorImpl<char> &Output,
54 void *Cookie,
55 ArrayRef<intptr_t> QualTypeVals) {
56 StringRef Str = "<can't format argument>";
57 Output.append(Str.begin(), Str.end());
Chris Lattner6a2ed6f2008-11-23 09:13:29 +000058}
59
Benjamin Kramer018b6d42016-07-21 15:06:51 +000060DiagnosticsEngine::DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> diags,
61 DiagnosticOptions *DiagOpts,
62 DiagnosticConsumer *client,
63 bool ShouldOwnClient)
64 : Diags(std::move(diags)), DiagOpts(DiagOpts), Client(nullptr),
65 SourceMgr(nullptr) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +000066 setClient(client, ShouldOwnClient);
Chris Lattner63ecc502008-11-23 09:21:17 +000067 ArgToStringFn = DummyArgToStringFn;
Craig Topperf1186c52014-05-08 06:41:40 +000068 ArgToStringCookie = nullptr;
Mike Stump11289f42009-09-09 15:08:12 +000069
Douglas Gregor0e119552010-07-31 00:40:00 +000070 AllExtensionsSilenced = 0;
Richard Smithe37391c2017-05-03 00:28:49 +000071 SuppressAfterFatalError = true;
Douglas Gregor0e119552010-07-31 00:40:00 +000072 SuppressAllDiagnostics = false;
Richard Trieu91844232012-06-26 18:18:47 +000073 ElideType = true;
74 PrintTemplateTree = false;
75 ShowColors = false;
Douglas Gregor0e119552010-07-31 00:40:00 +000076 ShowOverloads = Ovl_All;
Douglas Gregor0e119552010-07-31 00:40:00 +000077
78 ErrorLimit = 0;
79 TemplateBacktraceLimit = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +000080 ConstexprBacktraceLimit = 0;
Douglas Gregor0e119552010-07-31 00:40:00 +000081
Douglas Gregoraa21cc42010-07-19 21:46:24 +000082 Reset();
Chris Lattnerae411572006-07-05 00:55:08 +000083}
84
Reid Klecknerdccbabf2014-12-17 20:23:11 +000085DiagnosticsEngine::~DiagnosticsEngine() {
86 // If we own the diagnostic client, destroy it first so that it can access the
87 // engine from its destructor.
88 setClient(nullptr);
89}
90
David Blaikiee2eefae2011-09-25 23:39:51 +000091void DiagnosticsEngine::setClient(DiagnosticConsumer *client,
David Blaikie9c902b52011-09-25 23:23:43 +000092 bool ShouldOwnClient) {
Alexander Kornienko41c247a2014-11-17 23:46:02 +000093 Owner.reset(ShouldOwnClient ? client : nullptr);
Douglas Gregor7a964ad2011-01-31 22:04:05 +000094 Client = client;
Douglas Gregor7a964ad2011-01-31 22:04:05 +000095}
Chris Lattnerfb42a182009-07-12 21:18:45 +000096
David Blaikie9c902b52011-09-25 23:23:43 +000097void DiagnosticsEngine::pushMappings(SourceLocation Loc) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +000098 DiagStateOnPushStack.push_back(GetCurDiagState());
Chris Lattnerfb42a182009-07-12 21:18:45 +000099}
100
David Blaikie9c902b52011-09-25 23:23:43 +0000101bool DiagnosticsEngine::popMappings(SourceLocation Loc) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000102 if (DiagStateOnPushStack.empty())
Chris Lattnerfb42a182009-07-12 21:18:45 +0000103 return false;
104
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000105 if (DiagStateOnPushStack.back() != GetCurDiagState()) {
106 // State changed at some point between push/pop.
107 PushDiagStatePoint(DiagStateOnPushStack.back(), Loc);
108 }
109 DiagStateOnPushStack.pop_back();
Chris Lattnerfb42a182009-07-12 21:18:45 +0000110 return true;
111}
112
David Blaikie9c902b52011-09-25 23:23:43 +0000113void DiagnosticsEngine::Reset() {
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000114 ErrorOccurred = false;
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +0000115 UncompilableErrorOccurred = false;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000116 FatalErrorOccurred = false;
Douglas Gregor8a60bbe2011-07-06 17:40:26 +0000117 UnrecoverableErrorOccurred = false;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000118
119 NumWarnings = 0;
120 NumErrors = 0;
Argyrios Kyrtzidis1fa8b4b2011-07-29 01:25:44 +0000121 TrapNumErrorsOccurred = 0;
122 TrapNumUnrecoverableErrorsOccurred = 0;
Douglas Gregor8a60bbe2011-07-06 17:40:26 +0000123
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000124 CurDiagID = ~0U;
Richard Smith5bb4cdf2012-12-20 02:22:15 +0000125 LastDiagLevel = DiagnosticIDs::Ignored;
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000126 DelayedDiagID = 0;
Argyrios Kyrtzidisbbbeea12011-03-26 18:58:17 +0000127
128 // Clear state related to #pragma diagnostic.
129 DiagStates.clear();
Richard Smithd230de22017-01-26 01:01:01 +0000130 DiagStatesByLoc.clear();
Argyrios Kyrtzidisbbbeea12011-03-26 18:58:17 +0000131 DiagStateOnPushStack.clear();
132
133 // Create a DiagState and DiagStatePoint representing diagnostic changes
134 // through command-line.
Benjamin Kramer3204b152015-05-29 19:42:19 +0000135 DiagStates.emplace_back();
Richard Smithd230de22017-01-26 01:01:01 +0000136 DiagStatesByLoc.appendFirst(&DiagStates.back());
Douglas Gregoraa21cc42010-07-19 21:46:24 +0000137}
Chris Lattner22eb9722006-06-18 05:43:12 +0000138
David Blaikie9c902b52011-09-25 23:23:43 +0000139void DiagnosticsEngine::SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1,
Chad Rosier849a67b2012-02-07 23:24:49 +0000140 StringRef Arg2) {
Douglas Gregor85795312010-03-22 15:10:57 +0000141 if (DelayedDiagID)
142 return;
143
144 DelayedDiagID = DiagID;
Douglas Gregor96380982010-03-22 15:47:45 +0000145 DelayedDiagArg1 = Arg1.str();
146 DelayedDiagArg2 = Arg2.str();
Douglas Gregor85795312010-03-22 15:10:57 +0000147}
148
David Blaikie9c902b52011-09-25 23:23:43 +0000149void DiagnosticsEngine::ReportDelayed() {
Alex Lorenzce4518f2017-05-04 13:56:51 +0000150 unsigned ID = DelayedDiagID;
Douglas Gregor85795312010-03-22 15:10:57 +0000151 DelayedDiagID = 0;
Alex Lorenzce4518f2017-05-04 13:56:51 +0000152 Report(ID) << DelayedDiagArg1 << DelayedDiagArg2;
Douglas Gregor85795312010-03-22 15:10:57 +0000153}
154
Richard Smithd230de22017-01-26 01:01:01 +0000155void DiagnosticsEngine::DiagStateMap::appendFirst(
156 DiagState *State) {
157 assert(Files.empty() && "not first");
158 FirstDiagState = CurDiagState = State;
159 CurDiagStateLoc = SourceLocation();
Benjamin Kramerbc9ef592017-01-18 15:50:26 +0000160}
161
Richard Smithd230de22017-01-26 01:01:01 +0000162void DiagnosticsEngine::DiagStateMap::append(SourceManager &SrcMgr,
163 SourceLocation Loc,
164 DiagState *State) {
165 CurDiagState = State;
166 CurDiagStateLoc = Loc;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000167
Richard Smithd230de22017-01-26 01:01:01 +0000168 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
169 unsigned Offset = Decomp.second;
170 for (File *F = getFile(SrcMgr, Decomp.first); F;
171 Offset = F->ParentOffset, F = F->Parent) {
172 F->HasLocalTransitions = true;
173 auto &Last = F->StateTransitions.back();
174 assert(Last.Offset <= Offset && "state transitions added out of order");
Richard Smith99eff012012-08-17 00:55:32 +0000175
Richard Smithd230de22017-01-26 01:01:01 +0000176 if (Last.Offset == Offset) {
177 if (Last.State == State)
178 break;
179 Last.State = State;
180 continue;
181 }
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000182
Richard Smithd230de22017-01-26 01:01:01 +0000183 F->StateTransitions.push_back({State, Offset});
184 }
185}
186
187DiagnosticsEngine::DiagState *
188DiagnosticsEngine::DiagStateMap::lookup(SourceManager &SrcMgr,
189 SourceLocation Loc) const {
190 // Common case: we have not seen any diagnostic pragmas.
191 if (Files.empty())
192 return FirstDiagState;
193
194 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedLoc(Loc);
195 const File *F = getFile(SrcMgr, Decomp.first);
196 return F->lookup(Decomp.second);
197}
198
199DiagnosticsEngine::DiagState *
200DiagnosticsEngine::DiagStateMap::File::lookup(unsigned Offset) const {
201 auto OnePastIt = std::upper_bound(
202 StateTransitions.begin(), StateTransitions.end(), Offset,
203 [](unsigned Offset, const DiagStatePoint &P) {
204 return Offset < P.Offset;
205 });
206 assert(OnePastIt != StateTransitions.begin() && "missing initial state");
207 return OnePastIt[-1].State;
208}
209
210DiagnosticsEngine::DiagStateMap::File *
211DiagnosticsEngine::DiagStateMap::getFile(SourceManager &SrcMgr,
212 FileID ID) const {
213 // Get or insert the File for this ID.
214 auto Range = Files.equal_range(ID);
215 if (Range.first != Range.second)
216 return &Range.first->second;
217 auto &F = Files.insert(Range.first, std::make_pair(ID, File()))->second;
218
219 // We created a new File; look up the diagnostic state at the start of it and
220 // initialize it.
221 if (ID.isValid()) {
222 std::pair<FileID, unsigned> Decomp = SrcMgr.getDecomposedIncludedLoc(ID);
223 F.Parent = getFile(SrcMgr, Decomp.first);
224 F.ParentOffset = Decomp.second;
225 F.StateTransitions.push_back({F.Parent->lookup(Decomp.second), 0});
226 } else {
227 // This is the (imaginary) root file into which we pretend all top-level
228 // files are included; it descends from the initial state.
229 //
230 // FIXME: This doesn't guarantee that we use the same ordering as
231 // isBeforeInTranslationUnit in the cases where someone invented another
232 // top-level file and added diagnostic pragmas to it. See the code at the
233 // end of isBeforeInTranslationUnit for the quirks it deals with.
234 F.StateTransitions.push_back({FirstDiagState, 0});
235 }
236 return &F;
237}
238
239void DiagnosticsEngine::PushDiagStatePoint(DiagState *State,
240 SourceLocation Loc) {
241 assert(Loc.isValid() && "Adding invalid loc point");
242 DiagStatesByLoc.append(*SourceMgr, Loc, State);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000243}
244
Alp Tokerd576e002014-06-12 11:13:52 +0000245void DiagnosticsEngine::setSeverity(diag::kind Diag, diag::Severity Map,
246 SourceLocation L) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000247 assert(Diag < diag::DIAG_UPPER_LIMIT &&
248 "Can only map builtin diagnostics");
249 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
Alp Toker46df1c02014-06-12 10:15:20 +0000250 (Map == diag::Severity::Fatal || Map == diag::Severity::Error)) &&
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000251 "Cannot map errors into warnings!");
Richard Smith8a0527d2012-08-14 22:37:22 +0000252 assert((L.isInvalid() || SourceMgr) && "No SourceMgr for valid location");
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000253
Chad Rosierd1956e42012-02-03 01:49:51 +0000254 // Don't allow a mapping to a warning override an error/fatal mapping.
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +0000255 bool WasUpgradedFromWarning = false;
Alp Toker46df1c02014-06-12 10:15:20 +0000256 if (Map == diag::Severity::Warning) {
Alp Tokerc726c362014-06-10 09:31:37 +0000257 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
Alp Toker46df1c02014-06-12 10:15:20 +0000258 if (Info.getSeverity() == diag::Severity::Error ||
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +0000259 Info.getSeverity() == diag::Severity::Fatal) {
Alp Tokerc726c362014-06-10 09:31:37 +0000260 Map = Info.getSeverity();
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +0000261 WasUpgradedFromWarning = true;
262 }
Chad Rosierd1956e42012-02-03 01:49:51 +0000263 }
Alp Tokerc726c362014-06-10 09:31:37 +0000264 DiagnosticMapping Mapping = makeUserMapping(Map, L);
Duncan P. N. Exon Smith900f8172017-04-12 03:58:58 +0000265 Mapping.setUpgradedFromWarning(WasUpgradedFromWarning);
Daniel Dunbar2fba0972011-10-04 21:17:24 +0000266
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000267 // Common case; setting all the diagnostics of a group in one place.
Richard Smithd230de22017-01-26 01:01:01 +0000268 if ((L.isInvalid() || L == DiagStatesByLoc.getCurDiagStateLoc()) &&
269 DiagStatesByLoc.getCurDiagState()) {
270 // FIXME: This is theoretically wrong: if the current state is shared with
271 // some other location (via push/pop) we will change the state for that
272 // other location as well. This cannot currently happen, as we can't update
273 // the diagnostic state at the same location at which we pop.
274 DiagStatesByLoc.getCurDiagState()->setMapping(Diag, Mapping);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000275 return;
276 }
277
Richard Smithd230de22017-01-26 01:01:01 +0000278 // A diagnostic pragma occurred, create a new DiagState initialized with
279 // the current one and a new DiagStatePoint to record at which location
280 // the new state became active.
281 DiagStates.push_back(*GetCurDiagState());
282 DiagStates.back().setMapping(Diag, Mapping);
283 PushDiagStatePoint(&DiagStates.back(), L);
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000284}
285
Richard Smith3be1cb22014-08-07 00:24:21 +0000286bool DiagnosticsEngine::setSeverityForGroup(diag::Flavor Flavor,
287 StringRef Group, diag::Severity Map,
Alp Tokerd576e002014-06-12 11:13:52 +0000288 SourceLocation Loc) {
Daniel Dunbard908c122011-09-29 01:47:16 +0000289 // Get the diagnostics in this group.
Hans Wennborgeb7cd662014-08-11 16:05:54 +0000290 SmallVector<diag::kind, 256> GroupDiags;
Richard Smith3be1cb22014-08-07 00:24:21 +0000291 if (Diags->getDiagnosticsInGroup(Flavor, Group, GroupDiags))
Daniel Dunbard908c122011-09-29 01:47:16 +0000292 return true;
293
294 // Set the mapping.
Hans Wennborgeb7cd662014-08-11 16:05:54 +0000295 for (diag::kind Diag : GroupDiags)
296 setSeverity(Diag, Map, Loc);
Daniel Dunbard908c122011-09-29 01:47:16 +0000297
298 return false;
299}
300
Daniel Dunbarc2e5ca62011-09-29 00:53:47 +0000301bool DiagnosticsEngine::setDiagnosticGroupWarningAsError(StringRef Group,
302 bool Enabled) {
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000303 // If we are enabling this feature, just set the diagnostic mappings to map to
304 // errors.
305 if (Enabled)
Richard Smith3be1cb22014-08-07 00:24:21 +0000306 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
307 diag::Severity::Error);
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000308
309 // Otherwise, we want to set the diagnostic mapping's "no Werror" bit, and
310 // potentially downgrade anything already mapped to be a warning.
311
312 // Get the diagnostics in this group.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000313 SmallVector<diag::kind, 8> GroupDiags;
Richard Smith3be1cb22014-08-07 00:24:21 +0000314 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
315 GroupDiags))
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000316 return true;
317
318 // Perform the mapping change.
Craig Toppera52e2b22015-11-26 05:10:07 +0000319 for (diag::kind Diag : GroupDiags) {
320 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000321
Alp Toker46df1c02014-06-12 10:15:20 +0000322 if (Info.getSeverity() == diag::Severity::Error ||
323 Info.getSeverity() == diag::Severity::Fatal)
324 Info.setSeverity(diag::Severity::Warning);
Daniel Dunbar58d0af62011-09-29 01:58:05 +0000325
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000326 Info.setNoWarningAsError(true);
327 }
328
329 return false;
Daniel Dunbarc2e5ca62011-09-29 00:53:47 +0000330}
331
332bool DiagnosticsEngine::setDiagnosticGroupErrorAsFatal(StringRef Group,
333 bool Enabled) {
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000334 // If we are enabling this feature, just set the diagnostic mappings to map to
335 // fatal errors.
336 if (Enabled)
Richard Smith3be1cb22014-08-07 00:24:21 +0000337 return setSeverityForGroup(diag::Flavor::WarningOrError, Group,
338 diag::Severity::Fatal);
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000339
Richard Smithe37391c2017-05-03 00:28:49 +0000340 // Otherwise, we want to set the diagnostic mapping's "no Wfatal-errors" bit,
341 // and potentially downgrade anything already mapped to be a fatal error.
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000342
343 // Get the diagnostics in this group.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000344 SmallVector<diag::kind, 8> GroupDiags;
Richard Smith3be1cb22014-08-07 00:24:21 +0000345 if (Diags->getDiagnosticsInGroup(diag::Flavor::WarningOrError, Group,
346 GroupDiags))
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000347 return true;
348
349 // Perform the mapping change.
Craig Toppera52e2b22015-11-26 05:10:07 +0000350 for (diag::kind Diag : GroupDiags) {
351 DiagnosticMapping &Info = GetCurDiagState()->getOrAddMapping(Diag);
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000352
Alp Toker46df1c02014-06-12 10:15:20 +0000353 if (Info.getSeverity() == diag::Severity::Fatal)
354 Info.setSeverity(diag::Severity::Error);
Daniel Dunbar58d0af62011-09-29 01:58:05 +0000355
Daniel Dunbarfffcf212011-09-29 01:52:06 +0000356 Info.setNoErrorAsFatal(true);
357 }
358
359 return false;
Daniel Dunbarc2e5ca62011-09-29 00:53:47 +0000360}
361
Richard Smith3be1cb22014-08-07 00:24:21 +0000362void DiagnosticsEngine::setSeverityForAll(diag::Flavor Flavor,
363 diag::Severity Map,
Alp Tokerd576e002014-06-12 11:13:52 +0000364 SourceLocation Loc) {
Argyrios Kyrtzidis9ffada92012-01-27 06:15:43 +0000365 // Get all the diagnostics.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000366 SmallVector<diag::kind, 64> AllDiags;
Richard Smith3be1cb22014-08-07 00:24:21 +0000367 Diags->getAllDiagnostics(Flavor, AllDiags);
Argyrios Kyrtzidis9ffada92012-01-27 06:15:43 +0000368
369 // Set the mapping.
Craig Toppera52e2b22015-11-26 05:10:07 +0000370 for (diag::kind Diag : AllDiags)
371 if (Diags->isBuiltinWarningOrExtension(Diag))
372 setSeverity(Diag, Map, Loc);
Argyrios Kyrtzidis9ffada92012-01-27 06:15:43 +0000373}
374
David Blaikie9c902b52011-09-25 23:23:43 +0000375void DiagnosticsEngine::Report(const StoredDiagnostic &storedDiag) {
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000376 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
377
378 CurDiagLoc = storedDiag.getLocation();
379 CurDiagID = storedDiag.getID();
380 NumDiagArgs = 0;
381
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000382 DiagRanges.clear();
Benjamin Kramerf367dd92015-06-12 15:31:50 +0000383 DiagRanges.append(storedDiag.range_begin(), storedDiag.range_end());
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000384
Alexander Kornienkod3b4e082014-05-22 19:56:11 +0000385 DiagFixItHints.clear();
Benjamin Kramerf367dd92015-06-12 15:31:50 +0000386 DiagFixItHints.append(storedDiag.fixit_begin(), storedDiag.fixit_end());
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000387
David Blaikiee2eefae2011-09-25 23:39:51 +0000388 assert(Client && "DiagnosticConsumer not set!");
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000389 Level DiagLevel = storedDiag.getLevel();
David Blaikieb5784322011-09-26 01:18:08 +0000390 Diagnostic Info(this, storedDiag.getMessage());
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000391 Client->HandleDiagnostic(DiagLevel, Info);
392 if (Client->IncludeInDiagnosticCounts()) {
David Blaikie9c902b52011-09-25 23:23:43 +0000393 if (DiagLevel == DiagnosticsEngine::Warning)
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000394 ++NumWarnings;
395 }
396
397 CurDiagID = ~0U;
398}
399
Jordan Rose6f524ac2012-07-11 16:50:36 +0000400bool DiagnosticsEngine::EmitCurrentDiagnostic(bool Force) {
401 assert(getClient() && "DiagnosticClient not set!");
402
403 bool Emitted;
404 if (Force) {
405 Diagnostic Info(this);
406
407 // Figure out the diagnostic level of this message.
408 DiagnosticIDs::Level DiagLevel
409 = Diags->getDiagnosticLevel(Info.getID(), Info.getLocation(), *this);
410
411 Emitted = (DiagLevel != DiagnosticIDs::Ignored);
412 if (Emitted) {
413 // Emit the diagnostic regardless of suppression level.
414 Diags->EmitDiag(*this, DiagLevel);
415 }
416 } else {
417 // Process the diagnostic, sending the accumulated information to the
418 // DiagnosticConsumer.
419 Emitted = ProcessDiag();
420 }
Douglas Gregor85795312010-03-22 15:10:57 +0000421
422 // Clear out the current diagnostic object.
Daniel Dunbarc7c00892012-03-13 21:02:14 +0000423 Clear();
Douglas Gregor85795312010-03-22 15:10:57 +0000424
425 // If there was a delayed diagnostic, emit it now.
Alex Lorenzce4518f2017-05-04 13:56:51 +0000426 if (!Force && DelayedDiagID)
Daniel Dunbarc7c00892012-03-13 21:02:14 +0000427 ReportDelayed();
Douglas Gregor85795312010-03-22 15:10:57 +0000428
429 return Emitted;
430}
431
Nico Weber4c311642008-08-10 19:59:06 +0000432
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000433DiagnosticConsumer::~DiagnosticConsumer() {}
Nico Weber4c311642008-08-10 19:59:06 +0000434
David Blaikiee2eefae2011-09-25 23:39:51 +0000435void DiagnosticConsumer::HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
David Blaikieb5784322011-09-26 01:18:08 +0000436 const Diagnostic &Info) {
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000437 if (!IncludeInDiagnosticCounts())
438 return;
439
David Blaikie9c902b52011-09-25 23:23:43 +0000440 if (DiagLevel == DiagnosticsEngine::Warning)
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000441 ++NumWarnings;
David Blaikie9c902b52011-09-25 23:23:43 +0000442 else if (DiagLevel >= DiagnosticsEngine::Error)
Argyrios Kyrtzidisc79346a2010-11-18 20:06:46 +0000443 ++NumErrors;
444}
Chris Lattner23be0672008-11-19 06:51:40 +0000445
Chris Lattner2b786902008-11-21 07:50:02 +0000446/// ModifierIs - Return true if the specified modifier matches specified string.
447template <std::size_t StrLen>
448static bool ModifierIs(const char *Modifier, unsigned ModifierLen,
449 const char (&Str)[StrLen]) {
450 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1);
451}
452
John McCall8cb7a8a32010-01-14 20:11:39 +0000453/// ScanForward - Scans forward, looking for the given character, skipping
454/// nested clauses and escaped characters.
455static const char *ScanFormat(const char *I, const char *E, char Target) {
456 unsigned Depth = 0;
457
458 for ( ; I != E; ++I) {
459 if (Depth == 0 && *I == Target) return I;
460 if (Depth != 0 && *I == '}') Depth--;
461
462 if (*I == '%') {
463 I++;
464 if (I == E) break;
465
466 // Escaped characters get implicitly skipped here.
467
468 // Format specifier.
Jordan Rosea7d03842013-02-08 22:30:41 +0000469 if (!isDigit(*I) && !isPunctuation(*I)) {
470 for (I++; I != E && !isDigit(*I) && *I != '{'; I++) ;
John McCall8cb7a8a32010-01-14 20:11:39 +0000471 if (I == E) break;
472 if (*I == '{')
473 Depth++;
474 }
475 }
476 }
477 return E;
478}
479
Chris Lattner2b786902008-11-21 07:50:02 +0000480/// HandleSelectModifier - Handle the integer 'select' modifier. This is used
481/// like this: %select{foo|bar|baz}2. This means that the integer argument
482/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'.
483/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'.
484/// This is very useful for certain classes of variant diagnostics.
David Blaikieb5784322011-09-26 01:18:08 +0000485static void HandleSelectModifier(const Diagnostic &DInfo, unsigned ValNo,
Chris Lattner2b786902008-11-21 07:50:02 +0000486 const char *Argument, unsigned ArgumentLen,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000487 SmallVectorImpl<char> &OutStr) {
Chris Lattner2b786902008-11-21 07:50:02 +0000488 const char *ArgumentEnd = Argument+ArgumentLen;
Mike Stump11289f42009-09-09 15:08:12 +0000489
Chris Lattner2b786902008-11-21 07:50:02 +0000490 // Skip over 'ValNo' |'s.
491 while (ValNo) {
John McCall8cb7a8a32010-01-14 20:11:39 +0000492 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|');
Chris Lattner2b786902008-11-21 07:50:02 +0000493 assert(NextVal != ArgumentEnd && "Value for integer select modifier was"
494 " larger than the number of options in the diagnostic string!");
495 Argument = NextVal+1; // Skip this string.
496 --ValNo;
497 }
Mike Stump11289f42009-09-09 15:08:12 +0000498
Chris Lattner2b786902008-11-21 07:50:02 +0000499 // Get the end of the value. This is either the } or the |.
John McCall8cb7a8a32010-01-14 20:11:39 +0000500 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|');
John McCalle4d54322010-01-13 23:58:20 +0000501
502 // Recursively format the result of the select clause into the output string.
503 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000504}
505
506/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the
507/// letter 's' to the string if the value is not 1. This is used in cases like
508/// this: "you idiot, you have %4 parameter%s4!".
509static void HandleIntegerSModifier(unsigned ValNo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000510 SmallVectorImpl<char> &OutStr) {
Chris Lattner2b786902008-11-21 07:50:02 +0000511 if (ValNo != 1)
512 OutStr.push_back('s');
513}
514
John McCall9015cde2010-01-14 00:50:32 +0000515/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This
516/// prints the ordinal form of the given integer, with 1 corresponding
517/// to the first ordinal. Currently this is hard-coded to use the
518/// English form.
519static void HandleOrdinalModifier(unsigned ValNo,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000520 SmallVectorImpl<char> &OutStr) {
John McCall9015cde2010-01-14 00:50:32 +0000521 assert(ValNo != 0 && "ValNo must be strictly positive!");
522
523 llvm::raw_svector_ostream Out(OutStr);
524
525 // We could use text forms for the first N ordinals, but the numeric
526 // forms are actually nicer in diagnostics because they stand out.
Jordan Rosec102b352012-09-22 01:24:42 +0000527 Out << ValNo << llvm::getOrdinalSuffix(ValNo);
John McCall9015cde2010-01-14 00:50:32 +0000528}
529
Chris Lattner2b786902008-11-21 07:50:02 +0000530
Sebastian Redl15b02d22008-11-22 13:44:36 +0000531/// PluralNumber - Parse an unsigned integer and advance Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000532static unsigned PluralNumber(const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000533 // Programming 101: Parse a decimal number :-)
534 unsigned Val = 0;
535 while (Start != End && *Start >= '0' && *Start <= '9') {
536 Val *= 10;
537 Val += *Start - '0';
538 ++Start;
539 }
540 return Val;
541}
542
543/// TestPluralRange - Test if Val is in the parsed range. Modifies Start.
Chris Lattner2fe29202009-04-15 17:13:42 +0000544static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000545 if (*Start != '[') {
546 unsigned Ref = PluralNumber(Start, End);
547 return Ref == Val;
548 }
549
550 ++Start;
551 unsigned Low = PluralNumber(Start, End);
552 assert(*Start == ',' && "Bad plural expression syntax: expected ,");
553 ++Start;
554 unsigned High = PluralNumber(Start, End);
555 assert(*Start == ']' && "Bad plural expression syntax: expected )");
556 ++Start;
557 return Low <= Val && Val <= High;
558}
559
560/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier.
Chris Lattner2fe29202009-04-15 17:13:42 +0000561static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000562 // Empty condition?
563 if (*Start == ':')
564 return true;
565
566 while (1) {
567 char C = *Start;
568 if (C == '%') {
569 // Modulo expression
570 ++Start;
571 unsigned Arg = PluralNumber(Start, End);
572 assert(*Start == '=' && "Bad plural expression syntax: expected =");
573 ++Start;
574 unsigned ValMod = ValNo % Arg;
575 if (TestPluralRange(ValMod, Start, End))
576 return true;
577 } else {
Sebastian Redl3ceaf622008-11-27 07:28:14 +0000578 assert((C == '[' || (C >= '0' && C <= '9')) &&
Sebastian Redl15b02d22008-11-22 13:44:36 +0000579 "Bad plural expression syntax: unexpected character");
580 // Range expression
581 if (TestPluralRange(ValNo, Start, End))
582 return true;
583 }
584
585 // Scan for next or-expr part.
586 Start = std::find(Start, End, ',');
Mike Stump11289f42009-09-09 15:08:12 +0000587 if (Start == End)
Sebastian Redl15b02d22008-11-22 13:44:36 +0000588 break;
589 ++Start;
590 }
591 return false;
592}
593
594/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used
595/// for complex plural forms, or in languages where all plurals are complex.
596/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are
597/// conditions that are tested in order, the form corresponding to the first
598/// that applies being emitted. The empty condition is always true, making the
599/// last form a default case.
600/// Conditions are simple boolean expressions, where n is the number argument.
601/// Here are the rules.
602/// condition := expression | empty
603/// empty := -> always true
604/// expression := numeric [',' expression] -> logical or
605/// numeric := range -> true if n in range
606/// | '%' number '=' range -> true if n % number in range
607/// range := number
608/// | '[' number ',' number ']' -> ranges are inclusive both ends
609///
610/// Here are some examples from the GNU gettext manual written in this form:
611/// English:
612/// {1:form0|:form1}
613/// Latvian:
614/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0}
615/// Gaeilge:
616/// {1:form0|2:form1|:form2}
617/// Romanian:
618/// {1:form0|0,%100=[1,19]:form1|:form2}
619/// Lithuanian:
620/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1}
621/// Russian (requires repeated form):
622/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2}
623/// Slovak
624/// {1:form0|[2,4]:form1|:form2}
625/// Polish (requires repeated form):
626/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2}
David Blaikieb5784322011-09-26 01:18:08 +0000627static void HandlePluralModifier(const Diagnostic &DInfo, unsigned ValNo,
Sebastian Redl15b02d22008-11-22 13:44:36 +0000628 const char *Argument, unsigned ArgumentLen,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000629 SmallVectorImpl<char> &OutStr) {
Sebastian Redl15b02d22008-11-22 13:44:36 +0000630 const char *ArgumentEnd = Argument + ArgumentLen;
631 while (1) {
632 assert(Argument < ArgumentEnd && "Plural expression didn't match.");
633 const char *ExprEnd = Argument;
634 while (*ExprEnd != ':') {
635 assert(ExprEnd != ArgumentEnd && "Plural missing expression end");
636 ++ExprEnd;
637 }
638 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) {
639 Argument = ExprEnd + 1;
John McCall8cb7a8a32010-01-14 20:11:39 +0000640 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|');
John McCall43b61682010-10-14 01:55:31 +0000641
642 // Recursively format the result of the plural clause into the
643 // output string.
644 DInfo.FormatDiagnostic(Argument, ExprEnd, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000645 return;
646 }
John McCall8cb7a8a32010-01-14 20:11:39 +0000647 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1;
Sebastian Redl15b02d22008-11-22 13:44:36 +0000648 }
649}
650
Alp Tokera231ad22014-01-06 12:54:18 +0000651/// \brief Returns the friendly description for a token kind that will appear
652/// without quotes in diagnostic messages. These strings may be translatable in
653/// future.
654static const char *getTokenDescForDiagnostic(tok::TokenKind Kind) {
Alp Tokerec543272013-12-24 09:48:30 +0000655 switch (Kind) {
656 case tok::identifier:
657 return "identifier";
658 default:
Craig Topperf1186c52014-05-08 06:41:40 +0000659 return nullptr;
Alp Tokerec543272013-12-24 09:48:30 +0000660 }
661}
Sebastian Redl15b02d22008-11-22 13:44:36 +0000662
Chris Lattner23be0672008-11-19 06:51:40 +0000663/// FormatDiagnostic - Format this diagnostic into a string, substituting the
664/// formal arguments into the %0 slots. The result is appended onto the Str
665/// array.
David Blaikieb5784322011-09-26 01:18:08 +0000666void Diagnostic::
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000667FormatDiagnostic(SmallVectorImpl<char> &OutStr) const {
Argyrios Kyrtzidise9af37d2011-05-05 07:54:59 +0000668 if (!StoredDiagMessage.empty()) {
669 OutStr.append(StoredDiagMessage.begin(), StoredDiagMessage.end());
670 return;
671 }
672
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000673 StringRef Diag =
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000674 getDiags()->getDiagnosticIDs()->getDescription(getID());
Mike Stump11289f42009-09-09 15:08:12 +0000675
Argyrios Kyrtzidis0e37afa2011-05-25 05:05:01 +0000676 FormatDiagnostic(Diag.begin(), Diag.end(), OutStr);
John McCalle4d54322010-01-13 23:58:20 +0000677}
678
David Blaikieb5784322011-09-26 01:18:08 +0000679void Diagnostic::
John McCalle4d54322010-01-13 23:58:20 +0000680FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000681 SmallVectorImpl<char> &OutStr) const {
John McCalle4d54322010-01-13 23:58:20 +0000682
Richard Trieub3b8bb02015-01-08 01:27:03 +0000683 // When the diagnostic string is only "%0", the entire string is being given
684 // by an outside source. Remove unprintable characters from this string
685 // and skip all the other string processing.
Richard Trieudcd7bb02015-01-17 00:56:10 +0000686 if (DiagEnd - DiagStr == 2 &&
687 StringRef(DiagStr, DiagEnd - DiagStr).equals("%0") &&
Richard Trieub3b8bb02015-01-08 01:27:03 +0000688 getArgKind(0) == DiagnosticsEngine::ak_std_string) {
689 const std::string &S = getArgStdStr(0);
690 for (char c : S) {
691 if (llvm::sys::locale::isPrint(c) || c == '\t') {
692 OutStr.push_back(c);
693 }
694 }
695 return;
696 }
697
Chris Lattnerc243f292009-10-20 05:25:22 +0000698 /// FormattedArgs - Keep track of all of the arguments formatted by
699 /// ConvertArgToString and pass them into subsequent calls to
700 /// ConvertArgToString, allowing the implementation to avoid redundancies in
701 /// obvious cases.
David Blaikie9c902b52011-09-25 23:23:43 +0000702 SmallVector<DiagnosticsEngine::ArgumentValue, 8> FormattedArgs;
Chandler Carruthd5173952011-07-11 17:49:21 +0000703
704 /// QualTypeVals - Pass a vector of arrays so that QualType names can be
705 /// compared to see if more information is needed to be printed.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000706 SmallVector<intptr_t, 2> QualTypeVals;
Richard Trieu91844232012-06-26 18:18:47 +0000707 SmallVector<char, 64> Tree;
708
Chandler Carruthd5173952011-07-11 17:49:21 +0000709 for (unsigned i = 0, e = getNumArgs(); i < e; ++i)
David Blaikie9c902b52011-09-25 23:23:43 +0000710 if (getArgKind(i) == DiagnosticsEngine::ak_qualtype)
Chandler Carruthd5173952011-07-11 17:49:21 +0000711 QualTypeVals.push_back(getRawArg(i));
712
Chris Lattner23be0672008-11-19 06:51:40 +0000713 while (DiagStr != DiagEnd) {
714 if (DiagStr[0] != '%') {
715 // Append non-%0 substrings to Str if we have one.
716 const char *StrEnd = std::find(DiagStr, DiagEnd, '%');
717 OutStr.append(DiagStr, StrEnd);
718 DiagStr = StrEnd;
Chris Lattner2b786902008-11-21 07:50:02 +0000719 continue;
Jordan Rosea7d03842013-02-08 22:30:41 +0000720 } else if (isPunctuation(DiagStr[1])) {
John McCall8cb7a8a32010-01-14 20:11:39 +0000721 OutStr.push_back(DiagStr[1]); // %% -> %.
Chris Lattner23be0672008-11-19 06:51:40 +0000722 DiagStr += 2;
Chris Lattner2b786902008-11-21 07:50:02 +0000723 continue;
724 }
Mike Stump11289f42009-09-09 15:08:12 +0000725
Chris Lattner2b786902008-11-21 07:50:02 +0000726 // Skip the %.
727 ++DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000728
Chris Lattner2b786902008-11-21 07:50:02 +0000729 // This must be a placeholder for a diagnostic argument. The format for a
730 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0".
731 // The digit is a number from 0-9 indicating which argument this comes from.
732 // The modifier is a string of digits from the set [-a-z]+, arguments is a
733 // brace enclosed string.
Craig Topperf1186c52014-05-08 06:41:40 +0000734 const char *Modifier = nullptr, *Argument = nullptr;
Chris Lattner2b786902008-11-21 07:50:02 +0000735 unsigned ModifierLen = 0, ArgumentLen = 0;
Mike Stump11289f42009-09-09 15:08:12 +0000736
Chris Lattner2b786902008-11-21 07:50:02 +0000737 // Check to see if we have a modifier. If so eat it.
Jordan Rosea7d03842013-02-08 22:30:41 +0000738 if (!isDigit(DiagStr[0])) {
Chris Lattner2b786902008-11-21 07:50:02 +0000739 Modifier = DiagStr;
740 while (DiagStr[0] == '-' ||
741 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z'))
742 ++DiagStr;
743 ModifierLen = DiagStr-Modifier;
Chris Lattner23be0672008-11-19 06:51:40 +0000744
Chris Lattner2b786902008-11-21 07:50:02 +0000745 // If we have an argument, get it next.
746 if (DiagStr[0] == '{') {
747 ++DiagStr; // Skip {.
748 Argument = DiagStr;
Mike Stump11289f42009-09-09 15:08:12 +0000749
John McCall8cb7a8a32010-01-14 20:11:39 +0000750 DiagStr = ScanFormat(DiagStr, DiagEnd, '}');
751 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!");
Chris Lattner2b786902008-11-21 07:50:02 +0000752 ArgumentLen = DiagStr-Argument;
753 ++DiagStr; // Skip }.
Chris Lattner23be0672008-11-19 06:51:40 +0000754 }
Chris Lattner2b786902008-11-21 07:50:02 +0000755 }
Mike Stump11289f42009-09-09 15:08:12 +0000756
Jordan Rosea7d03842013-02-08 22:30:41 +0000757 assert(isDigit(*DiagStr) && "Invalid format for argument in diagnostic");
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000758 unsigned ArgNo = *DiagStr++ - '0';
Chris Lattner2b786902008-11-21 07:50:02 +0000759
Richard Trieu91844232012-06-26 18:18:47 +0000760 // Only used for type diffing.
761 unsigned ArgNo2 = ArgNo;
762
David Blaikie9c902b52011-09-25 23:23:43 +0000763 DiagnosticsEngine::ArgumentKind Kind = getArgKind(ArgNo);
Richard Trieu90c31f52013-01-30 20:04:31 +0000764 if (ModifierIs(Modifier, ModifierLen, "diff")) {
Jordan Rosea7d03842013-02-08 22:30:41 +0000765 assert(*DiagStr == ',' && isDigit(*(DiagStr + 1)) &&
Richard Trieu91844232012-06-26 18:18:47 +0000766 "Invalid format for diff modifier");
767 ++DiagStr; // Comma.
768 ArgNo2 = *DiagStr++ - '0';
Richard Trieu90c31f52013-01-30 20:04:31 +0000769 DiagnosticsEngine::ArgumentKind Kind2 = getArgKind(ArgNo2);
770 if (Kind == DiagnosticsEngine::ak_qualtype &&
771 Kind2 == DiagnosticsEngine::ak_qualtype)
772 Kind = DiagnosticsEngine::ak_qualtype_pair;
773 else {
774 // %diff only supports QualTypes. For other kinds of arguments,
775 // use the default printing. For example, if the modifier is:
776 // "%diff{compare $ to $|other text}1,2"
777 // treat it as:
778 // "compare %1 to %2"
Chandler Carruth8df65e42016-12-23 05:19:47 +0000779 const char *ArgumentEnd = Argument + ArgumentLen;
780 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
781 assert(ScanFormat(Pipe + 1, ArgumentEnd, '|') == ArgumentEnd &&
782 "Found too many '|'s in a %diff modifier!");
Richard Trieu90c31f52013-01-30 20:04:31 +0000783 const char *FirstDollar = ScanFormat(Argument, Pipe, '$');
784 const char *SecondDollar = ScanFormat(FirstDollar + 1, Pipe, '$');
Filipe Cabecinhased4a00c2013-01-30 22:03:24 +0000785 const char ArgStr1[] = { '%', static_cast<char>('0' + ArgNo) };
786 const char ArgStr2[] = { '%', static_cast<char>('0' + ArgNo2) };
Richard Trieu90c31f52013-01-30 20:04:31 +0000787 FormatDiagnostic(Argument, FirstDollar, OutStr);
788 FormatDiagnostic(ArgStr1, ArgStr1 + 2, OutStr);
789 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
790 FormatDiagnostic(ArgStr2, ArgStr2 + 2, OutStr);
791 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
792 continue;
793 }
Richard Trieu91844232012-06-26 18:18:47 +0000794 }
Chris Lattnerc243f292009-10-20 05:25:22 +0000795
796 switch (Kind) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000797 // ---- STRINGS ----
David Blaikie9c902b52011-09-25 23:23:43 +0000798 case DiagnosticsEngine::ak_std_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000799 const std::string &S = getArgStdStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000800 assert(ModifierLen == 0 && "No modifiers for strings yet");
801 OutStr.append(S.begin(), S.end());
802 break;
803 }
David Blaikie9c902b52011-09-25 23:23:43 +0000804 case DiagnosticsEngine::ak_c_string: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000805 const char *S = getArgCStr(ArgNo);
Chris Lattner2b786902008-11-21 07:50:02 +0000806 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000807
808 // Don't crash if get passed a null pointer by accident.
809 if (!S)
810 S = "(null)";
Mike Stump11289f42009-09-09 15:08:12 +0000811
Chris Lattner2b786902008-11-21 07:50:02 +0000812 OutStr.append(S, S + strlen(S));
813 break;
814 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000815 // ---- INTEGERS ----
David Blaikie9c902b52011-09-25 23:23:43 +0000816 case DiagnosticsEngine::ak_sint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000817 int Val = getArgSInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000818
Chris Lattner2b786902008-11-21 07:50:02 +0000819 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCall43b61682010-10-14 01:55:31 +0000820 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen,
821 OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000822 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
823 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000824 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000825 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
826 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000827 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
828 HandleOrdinalModifier((unsigned)Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000829 } else {
830 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000831 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000832 }
Chris Lattner2b786902008-11-21 07:50:02 +0000833 break;
834 }
David Blaikie9c902b52011-09-25 23:23:43 +0000835 case DiagnosticsEngine::ak_uint: {
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000836 unsigned Val = getArgUInt(ArgNo);
Mike Stump11289f42009-09-09 15:08:12 +0000837
Chris Lattner2b786902008-11-21 07:50:02 +0000838 if (ModifierIs(Modifier, ModifierLen, "select")) {
John McCalle4d54322010-01-13 23:58:20 +0000839 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000840 } else if (ModifierIs(Modifier, ModifierLen, "s")) {
841 HandleIntegerSModifier(Val, OutStr);
Sebastian Redl15b02d22008-11-22 13:44:36 +0000842 } else if (ModifierIs(Modifier, ModifierLen, "plural")) {
John McCall43b61682010-10-14 01:55:31 +0000843 HandlePluralModifier(*this, (unsigned)Val, Argument, ArgumentLen,
844 OutStr);
John McCall9015cde2010-01-14 00:50:32 +0000845 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) {
846 HandleOrdinalModifier(Val, OutStr);
Chris Lattner2b786902008-11-21 07:50:02 +0000847 } else {
848 assert(ModifierLen == 0 && "Unknown integer modifier");
Daniel Dunbare3633792009-10-17 18:12:14 +0000849 llvm::raw_svector_ostream(OutStr) << Val;
Chris Lattner91aea712008-11-19 07:22:31 +0000850 }
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000851 break;
Chris Lattner2b786902008-11-21 07:50:02 +0000852 }
Alp Tokerec543272013-12-24 09:48:30 +0000853 // ---- TOKEN SPELLINGS ----
854 case DiagnosticsEngine::ak_tokenkind: {
855 tok::TokenKind Kind = static_cast<tok::TokenKind>(getRawArg(ArgNo));
856 assert(ModifierLen == 0 && "No modifiers for token kinds yet");
857
858 llvm::raw_svector_ostream Out(OutStr);
Alp Tokera231ad22014-01-06 12:54:18 +0000859 if (const char *S = tok::getPunctuatorSpelling(Kind))
860 // Quoted token spelling for punctuators.
861 Out << '\'' << S << '\'';
862 else if (const char *S = tok::getKeywordSpelling(Kind))
863 // Unquoted token spelling for keywords.
864 Out << S;
865 else if (const char *S = getTokenDescForDiagnostic(Kind))
Alp Tokerec543272013-12-24 09:48:30 +0000866 // Unquoted translatable token name.
867 Out << S;
Alp Tokerec543272013-12-24 09:48:30 +0000868 else if (const char *S = tok::getTokenName(Kind))
869 // Debug name, shouldn't appear in user-facing diagnostics.
870 Out << '<' << S << '>';
871 else
872 Out << "(null)";
873 break;
874 }
Chris Lattnere3d20d92008-11-23 21:45:46 +0000875 // ---- NAMES and TYPES ----
David Blaikie9c902b52011-09-25 23:23:43 +0000876 case DiagnosticsEngine::ak_identifierinfo: {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000877 const IdentifierInfo *II = getArgIdentifier(ArgNo);
878 assert(ModifierLen == 0 && "No modifiers for strings yet");
Daniel Dunbar69a79b12009-04-20 06:13:16 +0000879
880 // Don't crash if get passed a null pointer by accident.
881 if (!II) {
882 const char *S = "(null)";
883 OutStr.append(S, S + strlen(S));
884 continue;
885 }
886
Daniel Dunbar07d07852009-10-18 21:17:35 +0000887 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\'';
Chris Lattnere3d20d92008-11-23 21:45:46 +0000888 break;
889 }
David Blaikie9c902b52011-09-25 23:23:43 +0000890 case DiagnosticsEngine::ak_qualtype:
891 case DiagnosticsEngine::ak_declarationname:
892 case DiagnosticsEngine::ak_nameddecl:
893 case DiagnosticsEngine::ak_nestednamespec:
894 case DiagnosticsEngine::ak_declcontext:
Aaron Ballman3e424b52013-12-26 18:30:57 +0000895 case DiagnosticsEngine::ak_attr:
Chris Lattnerc243f292009-10-20 05:25:22 +0000896 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo),
Craig Topper3aa4fb32014-06-12 05:32:35 +0000897 StringRef(Modifier, ModifierLen),
898 StringRef(Argument, ArgumentLen),
Craig Toppere4753502014-06-12 05:32:27 +0000899 FormattedArgs,
Chandler Carruthd5173952011-07-11 17:49:21 +0000900 OutStr, QualTypeVals);
Chris Lattner6a2ed6f2008-11-23 09:13:29 +0000901 break;
Richard Trieu91844232012-06-26 18:18:47 +0000902 case DiagnosticsEngine::ak_qualtype_pair:
903 // Create a struct with all the info needed for printing.
904 TemplateDiffTypes TDT;
905 TDT.FromType = getRawArg(ArgNo);
906 TDT.ToType = getRawArg(ArgNo2);
907 TDT.ElideType = getDiags()->ElideType;
908 TDT.ShowColors = getDiags()->ShowColors;
Richard Trieu50f5f462012-07-10 01:46:04 +0000909 TDT.TemplateDiffUsed = false;
Richard Trieu91844232012-06-26 18:18:47 +0000910 intptr_t val = reinterpret_cast<intptr_t>(&TDT);
911
Richard Trieuc6058442012-06-29 21:12:16 +0000912 const char *ArgumentEnd = Argument + ArgumentLen;
913 const char *Pipe = ScanFormat(Argument, ArgumentEnd, '|');
914
Richard Trieua4056002012-07-13 21:18:32 +0000915 // Print the tree. If this diagnostic already has a tree, skip the
916 // second tree.
917 if (getDiags()->PrintTemplateTree && Tree.empty()) {
Richard Trieu91844232012-06-26 18:18:47 +0000918 TDT.PrintFromType = true;
919 TDT.PrintTree = true;
920 getDiags()->ConvertArgToString(Kind, val,
Craig Topper3aa4fb32014-06-12 05:32:35 +0000921 StringRef(Modifier, ModifierLen),
922 StringRef(Argument, ArgumentLen),
Craig Toppere4753502014-06-12 05:32:27 +0000923 FormattedArgs,
Richard Trieu91844232012-06-26 18:18:47 +0000924 Tree, QualTypeVals);
925 // If there is no tree information, fall back to regular printing.
Richard Trieuc6058442012-06-29 21:12:16 +0000926 if (!Tree.empty()) {
927 FormatDiagnostic(Pipe + 1, ArgumentEnd, OutStr);
Richard Trieu91844232012-06-26 18:18:47 +0000928 break;
Richard Trieuc6058442012-06-29 21:12:16 +0000929 }
Richard Trieu91844232012-06-26 18:18:47 +0000930 }
931
932 // Non-tree printing, also the fall-back when tree printing fails.
933 // The fall-back is triggered when the types compared are not templates.
Richard Trieuc6058442012-06-29 21:12:16 +0000934 const char *FirstDollar = ScanFormat(Argument, ArgumentEnd, '$');
935 const char *SecondDollar = ScanFormat(FirstDollar + 1, ArgumentEnd, '$');
Richard Trieu91844232012-06-26 18:18:47 +0000936
937 // Append before text
Richard Trieuc6058442012-06-29 21:12:16 +0000938 FormatDiagnostic(Argument, FirstDollar, OutStr);
Richard Trieu91844232012-06-26 18:18:47 +0000939
940 // Append first type
941 TDT.PrintTree = false;
942 TDT.PrintFromType = true;
943 getDiags()->ConvertArgToString(Kind, val,
Craig Topper3aa4fb32014-06-12 05:32:35 +0000944 StringRef(Modifier, ModifierLen),
945 StringRef(Argument, ArgumentLen),
Craig Toppere4753502014-06-12 05:32:27 +0000946 FormattedArgs,
Richard Trieu91844232012-06-26 18:18:47 +0000947 OutStr, QualTypeVals);
Richard Trieu50f5f462012-07-10 01:46:04 +0000948 if (!TDT.TemplateDiffUsed)
949 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
950 TDT.FromType));
951
Richard Trieu91844232012-06-26 18:18:47 +0000952 // Append middle text
Richard Trieuc6058442012-06-29 21:12:16 +0000953 FormatDiagnostic(FirstDollar + 1, SecondDollar, OutStr);
Richard Trieu91844232012-06-26 18:18:47 +0000954
955 // Append second type
956 TDT.PrintFromType = false;
957 getDiags()->ConvertArgToString(Kind, val,
Craig Topper3aa4fb32014-06-12 05:32:35 +0000958 StringRef(Modifier, ModifierLen),
959 StringRef(Argument, ArgumentLen),
Craig Toppere4753502014-06-12 05:32:27 +0000960 FormattedArgs,
Richard Trieu91844232012-06-26 18:18:47 +0000961 OutStr, QualTypeVals);
Richard Trieu50f5f462012-07-10 01:46:04 +0000962 if (!TDT.TemplateDiffUsed)
963 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_qualtype,
964 TDT.ToType));
965
Richard Trieu91844232012-06-26 18:18:47 +0000966 // Append end text
Richard Trieuc6058442012-06-29 21:12:16 +0000967 FormatDiagnostic(SecondDollar + 1, Pipe, OutStr);
Richard Trieu91844232012-06-26 18:18:47 +0000968 break;
Nico Weber4c311642008-08-10 19:59:06 +0000969 }
Chris Lattnerc243f292009-10-20 05:25:22 +0000970
971 // Remember this argument info for subsequent formatting operations. Turn
972 // std::strings into a null terminated string to make it be the same case as
973 // all the other ones.
Richard Trieu91844232012-06-26 18:18:47 +0000974 if (Kind == DiagnosticsEngine::ak_qualtype_pair)
975 continue;
976 else if (Kind != DiagnosticsEngine::ak_std_string)
Chris Lattnerc243f292009-10-20 05:25:22 +0000977 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo)));
978 else
David Blaikie9c902b52011-09-25 23:23:43 +0000979 FormattedArgs.push_back(std::make_pair(DiagnosticsEngine::ak_c_string,
Chris Lattnerc243f292009-10-20 05:25:22 +0000980 (intptr_t)getArgStdStr(ArgNo).c_str()));
981
Nico Weber4c311642008-08-10 19:59:06 +0000982 }
Richard Trieu91844232012-06-26 18:18:47 +0000983
984 // Append the type tree to the end of the diagnostics.
985 OutStr.append(Tree.begin(), Tree.end());
Nico Weber4c311642008-08-10 19:59:06 +0000986}
Ted Kremenekea06ec12009-01-23 20:28:53 +0000987
David Blaikie9c902b52011-09-25 23:23:43 +0000988StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000989 StringRef Message)
Benjamin Kramer929bd682010-11-19 17:36:51 +0000990 : ID(ID), Level(Level), Loc(), Message(Message) { }
Douglas Gregor33cdd812010-02-18 18:08:43 +0000991
David Blaikie9c902b52011-09-25 23:23:43 +0000992StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level,
David Blaikieb5784322011-09-26 01:18:08 +0000993 const Diagnostic &Info)
Douglas Gregora750e8e2010-11-19 16:18:16 +0000994 : ID(Info.getID()), Level(Level)
995{
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +0000996 assert((Info.getLocation().isInvalid() || Info.hasSourceManager()) &&
997 "Valid source location without setting a source manager for diagnostic");
998 if (Info.getLocation().isValid())
999 Loc = FullSourceLoc(Info.getLocation(), Info.getSourceManager());
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +00001000 SmallString<64> Message;
Douglas Gregor33cdd812010-02-18 18:08:43 +00001001 Info.FormatDiagnostic(Message);
1002 this->Message.assign(Message.begin(), Message.end());
Benjamin Kramerf9890422015-02-17 16:48:30 +00001003 this->Ranges.assign(Info.getRanges().begin(), Info.getRanges().end());
1004 this->FixIts.assign(Info.getFixItHints().begin(), Info.getFixItHints().end());
Douglas Gregor33cdd812010-02-18 18:08:43 +00001005}
1006
David Blaikie9c902b52011-09-25 23:23:43 +00001007StoredDiagnostic::StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001008 StringRef Message, FullSourceLoc Loc,
Chris Lattner54b16772011-07-23 17:14:25 +00001009 ArrayRef<CharSourceRange> Ranges,
Aaron Ballman234ebd72013-02-24 19:08:10 +00001010 ArrayRef<FixItHint> FixIts)
1011 : ID(ID), Level(Level), Loc(Loc), Message(Message),
1012 Ranges(Ranges.begin(), Ranges.end()), FixIts(FixIts.begin(), FixIts.end())
Douglas Gregor925296b2011-07-19 16:10:42 +00001013{
Douglas Gregor925296b2011-07-19 16:10:42 +00001014}
1015
Ted Kremenekea06ec12009-01-23 20:28:53 +00001016/// IncludeInDiagnosticCounts - This method (whose default implementation
1017/// returns true) indicates whether the diagnostics handled by this
David Blaikiee2eefae2011-09-25 23:39:51 +00001018/// DiagnosticConsumer should be included in the number of diagnostics
David Blaikie9c902b52011-09-25 23:23:43 +00001019/// reported by DiagnosticsEngine.
David Blaikiee2eefae2011-09-25 23:39:51 +00001020bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
Douglas Gregor89336232010-03-29 23:34:08 +00001021
David Blaikie68e081d2011-12-20 02:48:34 +00001022void IgnoringDiagConsumer::anchor() { }
1023
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +00001024ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
Douglas Gregor6b930962013-05-03 22:58:43 +00001025
1026void ForwardingDiagnosticConsumer::HandleDiagnostic(
1027 DiagnosticsEngine::Level DiagLevel,
1028 const Diagnostic &Info) {
1029 Target.HandleDiagnostic(DiagLevel, Info);
1030}
1031
1032void ForwardingDiagnosticConsumer::clear() {
1033 DiagnosticConsumer::clear();
1034 Target.clear();
1035}
1036
1037bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
1038 return Target.IncludeInDiagnosticCounts();
1039}
1040
Benjamin Kramer7ec12c92012-02-07 22:29:24 +00001041PartialDiagnostic::StorageAllocator::StorageAllocator() {
Douglas Gregor89336232010-03-29 23:34:08 +00001042 for (unsigned I = 0; I != NumCached; ++I)
1043 FreeList[I] = Cached + I;
1044 NumFreeListEntries = NumCached;
1045}
1046
Benjamin Kramer7ec12c92012-02-07 22:29:24 +00001047PartialDiagnostic::StorageAllocator::~StorageAllocator() {
Chad Rosier849a67b2012-02-07 23:24:49 +00001048 // Don't assert if we are in a CrashRecovery context, as this invariant may
1049 // be invalidated during a crash.
Justin Lebarbf16db12016-08-10 01:09:07 +00001050 assert((NumFreeListEntries == NumCached ||
1051 llvm::CrashRecoveryContext::isRecoveringFromCrash()) &&
1052 "A partial is on the lam");
Douglas Gregor89336232010-03-29 23:34:08 +00001053}
Alex Lorenzd0e27262017-08-25 15:48:00 +00001054
1055char DiagnosticError::ID;