blob: abcca096bb36f413578614fac7574533a6db76c7 [file] [log] [blame]
Daniel Dunbar34818552009-11-14 03:23:19 +00001//===--- VerifyDiagnosticsClient.cpp - Verifying Diagnostic Client --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This is a concrete diagnostic client, which buffers the diagnostic messages.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Frontend/VerifyDiagnosticsClient.h"
15#include "clang/Frontend/FrontendDiagnostic.h"
16#include "clang/Frontend/TextDiagnosticBuffer.h"
17#include "clang/Lex/Preprocessor.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/Support/raw_ostream.h"
20using namespace clang;
21
22VerifyDiagnosticsClient::VerifyDiagnosticsClient(DiagnosticClient *_Primary)
23 : PrimaryClient(_Primary), Buffer(new TextDiagnosticBuffer()),
24 CurrentPreprocessor(0), Diags(0), SourceMgr(0), NumErrors(0) {
25}
26
27VerifyDiagnosticsClient::~VerifyDiagnosticsClient() {
28 CheckDiagnostics();
29}
30
31// DiagnosticClient interface.
32
33void VerifyDiagnosticsClient::BeginSourceFile(const LangOptions &LangOpts,
34 const Preprocessor *PP) {
35 // FIXME: Const hack, we screw up the preprocessor but in practice its ok
36 // because it doesn't get reused. It would be better if we could make a copy
37 // though.
38 CurrentPreprocessor = const_cast<Preprocessor*>(PP);
39
40 // FIXME: HACK. Remember the source manager, and just expect that its lifetime
41 // exceeds when we need it.
42 SourceMgr = PP ? &PP->getSourceManager() : 0;
43
44 // FIXME: HACK. Remember the diagnostic engine, and just expect that its
45 // lifetime exceeds when we need it.
46 Diags = PP ? &PP->getDiagnostics() : 0;
47
48 PrimaryClient->BeginSourceFile(LangOpts, PP);
49}
50
51void VerifyDiagnosticsClient::EndSourceFile() {
52 CheckDiagnostics();
53
54 PrimaryClient->EndSourceFile();
55
56 CurrentPreprocessor = 0;
57}
58
59void VerifyDiagnosticsClient::HandleDiagnostic(Diagnostic::Level DiagLevel,
60 const DiagnosticInfo &Info) {
61 // Send the diagnostic to the buffer, we will check it once we reach the end
62 // of the source file (or are destructed).
63 Buffer->HandleDiagnostic(DiagLevel, Info);
64}
65
66// FIXME: It would be nice to just get this from the primary diagnostic client
67// or something.
68bool VerifyDiagnosticsClient::HadErrors() {
69 CheckDiagnostics();
70
71 return NumErrors != 0;
72}
73
74//===----------------------------------------------------------------------===//
75// Checking diagnostics implementation.
76//===----------------------------------------------------------------------===//
77
78typedef TextDiagnosticBuffer::DiagList DiagList;
79typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
80
81/// FindDiagnostics - Go through the comment and see if it indicates expected
82/// diagnostics. If so, then put them in a diagnostic list.
83///
84static void FindDiagnostics(const char *CommentStart, unsigned CommentLen,
85 DiagList &ExpectedDiags,
86 Preprocessor &PP, SourceLocation Pos,
87 const char *ExpectedStr) {
88 const char *CommentEnd = CommentStart+CommentLen;
89 unsigned ExpectedStrLen = strlen(ExpectedStr);
90
91 // Find all expected-foo diagnostics in the string and add them to
92 // ExpectedDiags.
93 while (CommentStart != CommentEnd) {
94 CommentStart = std::find(CommentStart, CommentEnd, 'e');
95 if (unsigned(CommentEnd-CommentStart) < ExpectedStrLen) return;
96
97 // If this isn't expected-foo, ignore it.
98 if (memcmp(CommentStart, ExpectedStr, ExpectedStrLen)) {
99 ++CommentStart;
100 continue;
101 }
102
103 CommentStart += ExpectedStrLen;
104
105 // Skip whitespace.
106 while (CommentStart != CommentEnd &&
107 isspace(CommentStart[0]))
108 ++CommentStart;
109
110 // Default, if we find the '{' now, is 1 time.
111 int Times = 1;
112 int Temp = 0;
113 // In extended syntax, there could be a digit now.
114 while (CommentStart != CommentEnd &&
115 CommentStart[0] >= '0' && CommentStart[0] <= '9') {
116 Temp *= 10;
117 Temp += CommentStart[0] - '0';
118 ++CommentStart;
119 }
120 if (Temp > 0)
121 Times = Temp;
122
123 // Skip whitespace again.
124 while (CommentStart != CommentEnd &&
125 isspace(CommentStart[0]))
126 ++CommentStart;
127
128 // We should have a {{ now.
129 if (CommentEnd-CommentStart < 2 ||
130 CommentStart[0] != '{' || CommentStart[1] != '{') {
131 if (std::find(CommentStart, CommentEnd, '{') != CommentEnd)
132 PP.Diag(Pos, diag::err_verify_bogus_characters);
133 else
134 PP.Diag(Pos, diag::err_verify_missing_start);
135 return;
136 }
137 CommentStart += 2;
138
139 // Find the }}.
140 const char *ExpectedEnd = CommentStart;
141 while (1) {
142 ExpectedEnd = std::find(ExpectedEnd, CommentEnd, '}');
143 if (CommentEnd-ExpectedEnd < 2) {
144 PP.Diag(Pos, diag::err_verify_missing_end);
145 return;
146 }
147
148 if (ExpectedEnd[1] == '}')
149 break;
150
151 ++ExpectedEnd; // Skip over singular }'s
152 }
153
154 std::string Msg(CommentStart, ExpectedEnd);
155 std::string::size_type FindPos;
156 while ((FindPos = Msg.find("\\n")) != std::string::npos)
157 Msg.replace(FindPos, 2, "\n");
158 // Add is possibly multiple times.
159 for (int i = 0; i < Times; ++i)
160 ExpectedDiags.push_back(std::make_pair(Pos, Msg));
161
162 CommentStart = ExpectedEnd;
163 }
164}
165
166/// FindExpectedDiags - Lex the main source file to find all of the
167// expected errors and warnings.
168static void FindExpectedDiags(Preprocessor &PP,
169 DiagList &ExpectedErrors,
170 DiagList &ExpectedWarnings,
171 DiagList &ExpectedNotes) {
172 // Create a raw lexer to pull all the comments out of the main file. We don't
173 // want to look in #include'd headers for expected-error strings.
174 FileID FID = PP.getSourceManager().getMainFileID();
175 if (PP.getSourceManager().getMainFileID().isInvalid())
176 return;
177
178 // Create a lexer to lex all the tokens of the main file in raw mode.
179 Lexer RawLex(FID, PP.getSourceManager(), PP.getLangOptions());
180
181 // Return comments as tokens, this is how we find expected diagnostics.
182 RawLex.SetCommentRetentionState(true);
183
184 Token Tok;
185 Tok.setKind(tok::comment);
186 while (Tok.isNot(tok::eof)) {
187 RawLex.Lex(Tok);
188 if (!Tok.is(tok::comment)) continue;
189
190 std::string Comment = PP.getSpelling(Tok);
191 if (Comment.empty()) continue;
192
193 // Find all expected errors.
194 FindDiagnostics(&Comment[0], Comment.size(), ExpectedErrors, PP,
195 Tok.getLocation(), "expected-error");
196
197 // Find all expected warnings.
198 FindDiagnostics(&Comment[0], Comment.size(), ExpectedWarnings, PP,
199 Tok.getLocation(), "expected-warning");
200
201 // Find all expected notes.
202 FindDiagnostics(&Comment[0], Comment.size(), ExpectedNotes, PP,
203 Tok.getLocation(), "expected-note");
204 };
205}
206
207/// PrintProblem - This takes a diagnostic map of the delta between expected and
208/// seen diagnostics. If there's anything in it, then something unexpected
209/// happened. Print the map out in a nice format and return "true". If the map
210/// is empty and we're not going to print things, then return "false".
211///
212static unsigned PrintProblem(Diagnostic &Diags, SourceManager &SourceMgr,
213 const_diag_iterator diag_begin,
214 const_diag_iterator diag_end,
215 const char *Kind, bool Expected) {
216 if (diag_begin == diag_end) return 0;
217
218 llvm::SmallString<256> Fmt;
219 llvm::raw_svector_ostream OS(Fmt);
220 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
221 if (I->first.isInvalid())
222 OS << "\n (frontend)";
223 else
224 OS << "\n Line " << SourceMgr.getInstantiationLineNumber(I->first);
225 OS << ": " << I->second;
226 }
227
228 Diags.Report(diag::err_verify_inconsistent_diags)
229 << Kind << Expected << OS.str();
230 return std::distance(diag_begin, diag_end);
231}
232
233/// CompareDiagLists - Compare two diagnostic lists and return the difference
234/// between them.
235///
236static unsigned CompareDiagLists(Diagnostic &Diags,
237 SourceManager &SourceMgr,
238 const_diag_iterator d1_begin,
239 const_diag_iterator d1_end,
240 const_diag_iterator d2_begin,
241 const_diag_iterator d2_end,
242 const char *Label) {
243 DiagList LeftOnly;
244 DiagList Left(d1_begin, d1_end);
245 DiagList Right(d2_begin, d2_end);
246
247 for (const_diag_iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
248 unsigned LineNo1 = SourceMgr.getInstantiationLineNumber(I->first);
249 const std::string &Diag1 = I->second;
250
251 DiagList::iterator II, IE;
252 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
253 unsigned LineNo2 = SourceMgr.getInstantiationLineNumber(II->first);
254 if (LineNo1 != LineNo2) continue;
255
256 const std::string &Diag2 = II->second;
257 if (Diag2.find(Diag1) != std::string::npos ||
258 Diag1.find(Diag2) != std::string::npos) {
259 break;
260 }
261 }
262 if (II == IE) {
263 // Not found.
264 LeftOnly.push_back(*I);
265 } else {
266 // Found. The same cannot be found twice.
267 Right.erase(II);
268 }
269 }
270 // Now all that's left in Right are those that were not matched.
271
272 return (PrintProblem(Diags, SourceMgr,
273 LeftOnly.begin(), LeftOnly.end(), Label, false) +
274 PrintProblem(Diags, SourceMgr,
275 Right.begin(), Right.end(), Label, true));
276}
277
278/// CheckResults - This compares the expected results to those that
279/// were actually reported. It emits any discrepencies. Return "true" if there
280/// were problems. Return "false" otherwise.
281///
282static unsigned CheckResults(Diagnostic &Diags, SourceManager &SourceMgr,
283 const TextDiagnosticBuffer &Buffer,
284 const DiagList &ExpectedErrors,
285 const DiagList &ExpectedWarnings,
286 const DiagList &ExpectedNotes) {
287 // We want to capture the delta between what was expected and what was
288 // seen.
289 //
290 // Expected \ Seen - set expected but not seen
291 // Seen \ Expected - set seen but not expected
292 unsigned NumProblems = 0;
293
294 // See if there are error mismatches.
295 NumProblems += CompareDiagLists(Diags, SourceMgr,
296 ExpectedErrors.begin(), ExpectedErrors.end(),
297 Buffer.err_begin(), Buffer.err_end(),
298 "error");
299
300 // See if there are warning mismatches.
301 NumProblems += CompareDiagLists(Diags, SourceMgr,
302 ExpectedWarnings.begin(),
303 ExpectedWarnings.end(),
304 Buffer.warn_begin(), Buffer.warn_end(),
305 "warning");
306
307 // See if there are note mismatches.
308 NumProblems += CompareDiagLists(Diags, SourceMgr,
309 ExpectedNotes.begin(),
310 ExpectedNotes.end(),
311 Buffer.note_begin(), Buffer.note_end(),
312 "note");
313
314 return NumProblems;
315}
316
317
318void VerifyDiagnosticsClient::CheckDiagnostics() {
319 DiagList ExpectedErrors, ExpectedWarnings, ExpectedNotes;
320
321 // Ensure any diagnostics go to the primary client.
322 DiagnosticClient *CurClient = Diags->getClient();
323 Diags->setClient(PrimaryClient.get());
324
325 // If we have a preprocessor, scan the source for expected diagnostic
326 // markers. If not then any diagnostics are unexpected.
327 if (CurrentPreprocessor) {
328 FindExpectedDiags(*CurrentPreprocessor, ExpectedErrors, ExpectedWarnings,
329 ExpectedNotes);
330 }
331
332 // Check that the expected diagnostics occurred.
333 NumErrors += CheckResults(*Diags, *SourceMgr, *Buffer,
334 ExpectedErrors, ExpectedWarnings, ExpectedNotes);
335
336 Diags->setClient(CurClient);
337
338 // Reset the buffer, we have processed all the diagnostics in it.
339 Buffer.reset(new TextDiagnosticBuffer());
340}