1 //===---- VerifyDiagnosticConsumer.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/Basic/FileManager.h"
15 #include "clang/Frontend/VerifyDiagnosticConsumer.h"
16 #include "clang/Frontend/FrontendDiagnostic.h"
17 #include "clang/Frontend/TextDiagnosticBuffer.h"
18 #include "clang/Lex/Preprocessor.h"
19 #include "llvm/ADT/SmallString.h"
20 #include "llvm/Support/Regex.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 using namespace clang;
24 typedef VerifyDiagnosticConsumer::Directive Directive;
25 typedef VerifyDiagnosticConsumer::DirectiveList DirectiveList;
26 typedef VerifyDiagnosticConsumer::ExpectedData ExpectedData;
27 
28 VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Diags)
29   : Diags(_Diags), PrimaryClient(Diags.getClient()),
30     OwnsPrimaryClient(Diags.ownsClient()),
31     Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0)
32 {
33   Diags.takeClient();
34 }
35 
36 VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
37   CheckDiagnostics();
38   Diags.takeClient();
39   if (OwnsPrimaryClient)
40     delete PrimaryClient;
41 }
42 
43 // DiagnosticConsumer interface.
44 
45 void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
46                                                const Preprocessor *PP) {
47   CurrentPreprocessor = PP;
48   if (PP) const_cast<Preprocessor*>(PP)->addCommentHandler(this);
49 
50   PrimaryClient->BeginSourceFile(LangOpts, PP);
51 }
52 
53 void VerifyDiagnosticConsumer::EndSourceFile() {
54   if (CurrentPreprocessor)
55     const_cast<Preprocessor*>(CurrentPreprocessor)->removeCommentHandler(this);
56   CheckDiagnostics();
57 
58   PrimaryClient->EndSourceFile();
59 
60   CurrentPreprocessor = 0;
61 }
62 
63 void VerifyDiagnosticConsumer::HandleDiagnostic(
64       DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
65   if (Info.hasSourceManager()) {
66     const SourceManager &SM = Info.getSourceManager();
67     FilesWithDiagnostics.insert(SM.getFileID(Info.getLocation()));
68   }
69   // Send the diagnostic to the buffer, we will check it once we reach the end
70   // of the source file (or are destructed).
71   Buffer->HandleDiagnostic(DiagLevel, Info);
72 }
73 
74 //===----------------------------------------------------------------------===//
75 // Checking diagnostics implementation.
76 //===----------------------------------------------------------------------===//
77 
78 typedef TextDiagnosticBuffer::DiagList DiagList;
79 typedef TextDiagnosticBuffer::const_iterator const_diag_iterator;
80 
81 namespace {
82 
83 /// StandardDirective - Directive with string matching.
84 ///
85 class StandardDirective : public Directive {
86 public:
87   StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
88                     StringRef Text, unsigned Min, unsigned Max)
89     : Directive(DirectiveLoc, DiagnosticLoc, Text, Min, Max) { }
90 
91   virtual bool isValid(std::string &Error) {
92     // all strings are considered valid; even empty ones
93     return true;
94   }
95 
96   virtual bool match(StringRef S) {
97     return S.find(Text) != StringRef::npos;
98   }
99 };
100 
101 /// RegexDirective - Directive with regular-expression matching.
102 ///
103 class RegexDirective : public Directive {
104 public:
105   RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
106                  StringRef Text, unsigned Min, unsigned Max)
107     : Directive(DirectiveLoc, DiagnosticLoc, Text, Min, Max), Regex(Text) { }
108 
109   virtual bool isValid(std::string &Error) {
110     if (Regex.isValid(Error))
111       return true;
112     return false;
113   }
114 
115   virtual bool match(StringRef S) {
116     return Regex.match(S);
117   }
118 
119 private:
120   llvm::Regex Regex;
121 };
122 
123 class ParseHelper
124 {
125 public:
126   ParseHelper(StringRef S)
127     : Begin(S.begin()), End(S.end()), C(Begin), P(Begin), PEnd(NULL) { }
128 
129   // Return true if string literal is next.
130   bool Next(StringRef S) {
131     P = C;
132     PEnd = C + S.size();
133     if (PEnd > End)
134       return false;
135     return !memcmp(P, S.data(), S.size());
136   }
137 
138   // Return true if number is next.
139   // Output N only if number is next.
140   bool Next(unsigned &N) {
141     unsigned TMP = 0;
142     P = C;
143     for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) {
144       TMP *= 10;
145       TMP += P[0] - '0';
146     }
147     if (P == C)
148       return false;
149     PEnd = P;
150     N = TMP;
151     return true;
152   }
153 
154   // Return true if string literal is found.
155   // When true, P marks begin-position of S in content.
156   bool Search(StringRef S) {
157     P = std::search(C, End, S.begin(), S.end());
158     PEnd = P + S.size();
159     return P != End;
160   }
161 
162   // Advance 1-past previous next/search.
163   // Behavior is undefined if previous next/search failed.
164   bool Advance() {
165     C = PEnd;
166     return C < End;
167   }
168 
169   // Skip zero or more whitespace.
170   void SkipWhitespace() {
171     for (; C < End && isspace(*C); ++C)
172       ;
173   }
174 
175   // Return true if EOF reached.
176   bool Done() {
177     return !(C < End);
178   }
179 
180   const char * const Begin; // beginning of expected content
181   const char * const End;   // end of expected content (1-past)
182   const char *C;            // position of next char in content
183   const char *P;
184 
185 private:
186   const char *PEnd; // previous next/search subject end (1-past)
187 };
188 
189 } // namespace anonymous
190 
191 /// ParseDirective - Go through the comment and see if it indicates expected
192 /// diagnostics. If so, then put them in the appropriate directive list.
193 ///
194 /// Returns true if any valid directives were found.
195 static bool ParseDirective(StringRef S, ExpectedData &ED, SourceManager &SM,
196                            SourceLocation Pos, DiagnosticsEngine &Diags) {
197   // A single comment may contain multiple directives.
198   bool FoundDirective = false;
199   for (ParseHelper PH(S); !PH.Done();) {
200     // Search for token: expected
201     if (!PH.Search("expected"))
202       break;
203     PH.Advance();
204 
205     // Next token: -
206     if (!PH.Next("-"))
207       continue;
208     PH.Advance();
209 
210     // Next token: { error | warning | note }
211     DirectiveList* DL = NULL;
212     if (PH.Next("error"))
213       DL = &ED.Errors;
214     else if (PH.Next("warning"))
215       DL = &ED.Warnings;
216     else if (PH.Next("note"))
217       DL = &ED.Notes;
218     else
219       continue;
220     PH.Advance();
221 
222     // Default directive kind.
223     bool RegexKind = false;
224     const char* KindStr = "string";
225 
226     // Next optional token: -
227     if (PH.Next("-re")) {
228       PH.Advance();
229       RegexKind = true;
230       KindStr = "regex";
231     }
232 
233     // Next optional token: @
234     SourceLocation ExpectedLoc;
235     if (!PH.Next("@")) {
236       ExpectedLoc = Pos;
237     } else {
238       PH.Advance();
239       unsigned Line = 0;
240       bool FoundPlus = PH.Next("+");
241       if (FoundPlus || PH.Next("-")) {
242         // Relative to current line.
243         PH.Advance();
244         bool Invalid = false;
245         unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
246         if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) {
247           if (FoundPlus) ExpectedLine += Line;
248           else ExpectedLine -= Line;
249           ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
250         }
251       } else {
252         // Absolute line number.
253         if (PH.Next(Line) && Line > 0)
254           ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
255       }
256 
257       if (ExpectedLoc.isInvalid()) {
258         Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
259                      diag::err_verify_missing_line) << KindStr;
260         continue;
261       }
262       PH.Advance();
263     }
264 
265     // Skip optional whitespace.
266     PH.SkipWhitespace();
267 
268     // Next optional token: positive integer or a '+'.
269     unsigned Min = 1;
270     unsigned Max = 1;
271     if (PH.Next(Min)) {
272       PH.Advance();
273       // A positive integer can be followed by a '+' meaning min
274       // or more, or by a '-' meaning a range from min to max.
275       if (PH.Next("+")) {
276         Max = Directive::MaxCount;
277         PH.Advance();
278       } else if (PH.Next("-")) {
279         PH.Advance();
280         if (!PH.Next(Max) || Max < Min) {
281           Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
282                        diag::err_verify_invalid_range) << KindStr;
283           continue;
284         }
285         PH.Advance();
286       } else {
287         Max = Min;
288       }
289     } else if (PH.Next("+")) {
290       // '+' on its own means "1 or more".
291       Max = Directive::MaxCount;
292       PH.Advance();
293     }
294 
295     // Skip optional whitespace.
296     PH.SkipWhitespace();
297 
298     // Next token: {{
299     if (!PH.Next("{{")) {
300       Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
301                    diag::err_verify_missing_start) << KindStr;
302       continue;
303     }
304     PH.Advance();
305     const char* const ContentBegin = PH.C; // mark content begin
306 
307     // Search for token: }}
308     if (!PH.Search("}}")) {
309       Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
310                    diag::err_verify_missing_end) << KindStr;
311       continue;
312     }
313     const char* const ContentEnd = PH.P; // mark content end
314     PH.Advance();
315 
316     // Build directive text; convert \n to newlines.
317     std::string Text;
318     StringRef NewlineStr = "\\n";
319     StringRef Content(ContentBegin, ContentEnd-ContentBegin);
320     size_t CPos = 0;
321     size_t FPos;
322     while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
323       Text += Content.substr(CPos, FPos-CPos);
324       Text += '\n';
325       CPos = FPos + NewlineStr.size();
326     }
327     if (Text.empty())
328       Text.assign(ContentBegin, ContentEnd);
329 
330     // Construct new directive.
331     Directive *D = Directive::create(RegexKind, Pos, ExpectedLoc, Text,
332                                      Min, Max);
333     std::string Error;
334     if (D->isValid(Error)) {
335       DL->push_back(D);
336       FoundDirective = true;
337     } else {
338       Diags.Report(Pos.getLocWithOffset(ContentBegin-PH.Begin),
339                    diag::err_verify_invalid_content)
340         << KindStr << Error;
341     }
342   }
343 
344   return FoundDirective;
345 }
346 
347 /// HandleComment - Hook into the preprocessor and extract comments containing
348 ///  expected errors and warnings.
349 bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP,
350                                              SourceRange Comment) {
351   SourceManager &SM = PP.getSourceManager();
352   SourceLocation CommentBegin = Comment.getBegin();
353 
354   const char *CommentRaw = SM.getCharacterData(CommentBegin);
355   StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
356 
357   if (C.empty())
358     return false;
359 
360   // Fold any "\<EOL>" sequences
361   size_t loc = C.find('\\');
362   if (loc == StringRef::npos) {
363     if (ParseDirective(C, ED, SM, CommentBegin, PP.getDiagnostics()))
364       if (const FileEntry *E = SM.getFileEntryForID(SM.getFileID(CommentBegin)))
365         FilesWithDirectives.insert(E);
366     return false;
367   }
368 
369   std::string C2;
370   C2.reserve(C.size());
371 
372   for (size_t last = 0;; loc = C.find('\\', last)) {
373     if (loc == StringRef::npos || loc == C.size()) {
374       C2 += C.substr(last);
375       break;
376     }
377     C2 += C.substr(last, loc-last);
378     last = loc + 1;
379 
380     if (C[last] == '\n' || C[last] == '\r') {
381       ++last;
382 
383       // Escape \r\n  or \n\r, but not \n\n.
384       if (last < C.size())
385         if (C[last] == '\n' || C[last] == '\r')
386           if (C[last] != C[last-1])
387             ++last;
388     } else {
389       // This was just a normal backslash.
390       C2 += '\\';
391     }
392   }
393 
394   if (!C2.empty())
395     if (ParseDirective(C2, ED, SM, CommentBegin, PP.getDiagnostics()))
396       if (const FileEntry *E = SM.getFileEntryForID(SM.getFileID(CommentBegin)))
397         FilesWithDirectives.insert(E);
398   return false;
399 }
400 
401 /// FindExpectedDiags - Lex the main source file to find all of the
402 //   expected errors and warnings.
403 static void FindExpectedDiags(const Preprocessor &PP, ExpectedData &ED,
404                               FileID FID) {
405   // Create a raw lexer to pull all the comments out of FID.
406   if (FID.isInvalid())
407     return;
408 
409   SourceManager& SM = PP.getSourceManager();
410   // Create a lexer to lex all the tokens of the main file in raw mode.
411   const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID);
412   Lexer RawLex(FID, FromFile, SM, PP.getLangOpts());
413 
414   // Return comments as tokens, this is how we find expected diagnostics.
415   RawLex.SetCommentRetentionState(true);
416 
417   Token Tok;
418   Tok.setKind(tok::comment);
419   while (Tok.isNot(tok::eof)) {
420     RawLex.Lex(Tok);
421     if (!Tok.is(tok::comment)) continue;
422 
423     std::string Comment = PP.getSpelling(Tok);
424     if (Comment.empty()) continue;
425 
426     // Find all expected errors/warnings/notes.
427     ParseDirective(Comment, ED, SM, Tok.getLocation(), PP.getDiagnostics());
428   };
429 }
430 
431 /// \brief Takes a list of diagnostics that have been generated but not matched
432 /// by an expected-* directive and produces a diagnostic to the user from this.
433 static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
434                                 const_diag_iterator diag_begin,
435                                 const_diag_iterator diag_end,
436                                 const char *Kind) {
437   if (diag_begin == diag_end) return 0;
438 
439   SmallString<256> Fmt;
440   llvm::raw_svector_ostream OS(Fmt);
441   for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
442     if (I->first.isInvalid() || !SourceMgr)
443       OS << "\n  (frontend)";
444     else
445       OS << "\n  Line " << SourceMgr->getPresumedLineNumber(I->first);
446     OS << ": " << I->second;
447   }
448 
449   Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
450     << Kind << /*Unexpected=*/true << OS.str();
451   return std::distance(diag_begin, diag_end);
452 }
453 
454 /// \brief Takes a list of diagnostics that were expected to have been generated
455 /// but were not and produces a diagnostic to the user from this.
456 static unsigned PrintExpected(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
457                               DirectiveList &DL, const char *Kind) {
458   if (DL.empty())
459     return 0;
460 
461   SmallString<256> Fmt;
462   llvm::raw_svector_ostream OS(Fmt);
463   for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) {
464     Directive &D = **I;
465     OS << "\n  Line " << SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
466     if (D.DirectiveLoc != D.DiagnosticLoc)
467       OS << " (directive at "
468          << SourceMgr.getFilename(D.DirectiveLoc) << ":"
469          << SourceMgr.getPresumedLineNumber(D.DirectiveLoc) << ")";
470     OS << ": " << D.Text;
471   }
472 
473   Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
474     << Kind << /*Unexpected=*/false << OS.str();
475   return DL.size();
476 }
477 
478 /// CheckLists - Compare expected to seen diagnostic lists and return the
479 /// the difference between them.
480 ///
481 static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
482                            const char *Label,
483                            DirectiveList &Left,
484                            const_diag_iterator d2_begin,
485                            const_diag_iterator d2_end) {
486   DirectiveList LeftOnly;
487   DiagList Right(d2_begin, d2_end);
488 
489   for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) {
490     Directive& D = **I;
491     unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
492 
493     for (unsigned i = 0; i < D.Max; ++i) {
494       DiagList::iterator II, IE;
495       for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
496         unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
497         if (LineNo1 != LineNo2)
498           continue;
499 
500         const std::string &RightText = II->second;
501         if (D.match(RightText))
502           break;
503       }
504       if (II == IE) {
505         // Not found.
506         if (i >= D.Min) break;
507         LeftOnly.push_back(*I);
508       } else {
509         // Found. The same cannot be found twice.
510         Right.erase(II);
511       }
512     }
513   }
514   // Now all that's left in Right are those that were not matched.
515   unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
516   num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
517   return num;
518 }
519 
520 /// CheckResults - This compares the expected results to those that
521 /// were actually reported. It emits any discrepencies. Return "true" if there
522 /// were problems. Return "false" otherwise.
523 ///
524 static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
525                              const TextDiagnosticBuffer &Buffer,
526                              ExpectedData &ED) {
527   // We want to capture the delta between what was expected and what was
528   // seen.
529   //
530   //   Expected \ Seen - set expected but not seen
531   //   Seen \ Expected - set seen but not expected
532   unsigned NumProblems = 0;
533 
534   // See if there are error mismatches.
535   NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
536                             Buffer.err_begin(), Buffer.err_end());
537 
538   // See if there are warning mismatches.
539   NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
540                             Buffer.warn_begin(), Buffer.warn_end());
541 
542   // See if there are note mismatches.
543   NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
544                             Buffer.note_begin(), Buffer.note_end());
545 
546   return NumProblems;
547 }
548 
549 void VerifyDiagnosticConsumer::CheckDiagnostics() {
550   // Ensure any diagnostics go to the primary client.
551   bool OwnsCurClient = Diags.ownsClient();
552   DiagnosticConsumer *CurClient = Diags.takeClient();
553   Diags.setClient(PrimaryClient, false);
554 
555   // If we have a preprocessor, scan the source for expected diagnostic
556   // markers. If not then any diagnostics are unexpected.
557   if (CurrentPreprocessor) {
558     SourceManager &SM = CurrentPreprocessor->getSourceManager();
559     // Only check for expectations in other diagnostic locations not
560     // captured during normal parsing.
561     // FIXME: This check is currently necessary while synthesized files may
562     // not have their expected-* directives captured during parsing.  These
563     // cases should be fixed and the following loop replaced with one which
564     // checks only during a debug build and asserts on a mismatch.
565     for (FilesWithDiagnosticsSet::iterator I = FilesWithDiagnostics.begin(),
566                                          End = FilesWithDiagnostics.end();
567             I != End; ++I) {
568       const FileEntry *E = SM.getFileEntryForID(*I);
569       if (!E || !FilesWithDirectives.count(E)) {
570         if (E)
571           FilesWithDirectives.insert(E);
572         FindExpectedDiags(*CurrentPreprocessor, ED, *I);
573       }
574     }
575 
576     // Check that the expected diagnostics occurred.
577     NumErrors += CheckResults(Diags, SM, *Buffer, ED);
578   } else {
579     NumErrors += (PrintUnexpected(Diags, 0, Buffer->err_begin(),
580                                   Buffer->err_end(), "error") +
581                   PrintUnexpected(Diags, 0, Buffer->warn_begin(),
582                                   Buffer->warn_end(), "warn") +
583                   PrintUnexpected(Diags, 0, Buffer->note_begin(),
584                                   Buffer->note_end(), "note"));
585   }
586 
587   Diags.takeClient();
588   Diags.setClient(CurClient, OwnsCurClient);
589 
590   // Reset the buffer, we have processed all the diagnostics in it.
591   Buffer.reset(new TextDiagnosticBuffer());
592   ED.Errors.clear();
593   ED.Warnings.clear();
594   ED.Notes.clear();
595 }
596 
597 DiagnosticConsumer *
598 VerifyDiagnosticConsumer::clone(DiagnosticsEngine &Diags) const {
599   if (!Diags.getClient())
600     Diags.setClient(PrimaryClient->clone(Diags));
601 
602   return new VerifyDiagnosticConsumer(Diags);
603 }
604 
605 Directive *Directive::create(bool RegexKind, SourceLocation DirectiveLoc,
606                              SourceLocation DiagnosticLoc, StringRef Text,
607                              unsigned Min, unsigned Max) {
608   if (RegexKind)
609     return new RegexDirective(DirectiveLoc, DiagnosticLoc, Text, Min, Max);
610   return new StandardDirective(DirectiveLoc, DiagnosticLoc, Text, Min, Max);
611 }
612