xref: /openbsd-src/gnu/llvm/clang/lib/Frontend/VerifyDiagnosticConsumer.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ---------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This is a concrete diagnostic client, which buffers the diagnostic messages.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "clang/Frontend/VerifyDiagnosticConsumer.h"
14e5dd7070Spatrick #include "clang/Basic/CharInfo.h"
15e5dd7070Spatrick #include "clang/Basic/Diagnostic.h"
16e5dd7070Spatrick #include "clang/Basic/DiagnosticOptions.h"
17e5dd7070Spatrick #include "clang/Basic/FileManager.h"
18e5dd7070Spatrick #include "clang/Basic/LLVM.h"
19e5dd7070Spatrick #include "clang/Basic/SourceLocation.h"
20e5dd7070Spatrick #include "clang/Basic/SourceManager.h"
21e5dd7070Spatrick #include "clang/Basic/TokenKinds.h"
22e5dd7070Spatrick #include "clang/Frontend/FrontendDiagnostic.h"
23e5dd7070Spatrick #include "clang/Frontend/TextDiagnosticBuffer.h"
24e5dd7070Spatrick #include "clang/Lex/HeaderSearch.h"
25e5dd7070Spatrick #include "clang/Lex/Lexer.h"
26e5dd7070Spatrick #include "clang/Lex/PPCallbacks.h"
27e5dd7070Spatrick #include "clang/Lex/Preprocessor.h"
28e5dd7070Spatrick #include "clang/Lex/Token.h"
29e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
30e5dd7070Spatrick #include "llvm/ADT/SmallPtrSet.h"
31e5dd7070Spatrick #include "llvm/ADT/SmallString.h"
32e5dd7070Spatrick #include "llvm/ADT/StringRef.h"
33e5dd7070Spatrick #include "llvm/ADT/Twine.h"
34e5dd7070Spatrick #include "llvm/Support/ErrorHandling.h"
35e5dd7070Spatrick #include "llvm/Support/Regex.h"
36e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
37e5dd7070Spatrick #include <algorithm>
38e5dd7070Spatrick #include <cassert>
39e5dd7070Spatrick #include <cstddef>
40e5dd7070Spatrick #include <cstring>
41e5dd7070Spatrick #include <iterator>
42e5dd7070Spatrick #include <memory>
43e5dd7070Spatrick #include <string>
44e5dd7070Spatrick #include <utility>
45e5dd7070Spatrick #include <vector>
46e5dd7070Spatrick 
47e5dd7070Spatrick using namespace clang;
48e5dd7070Spatrick 
49e5dd7070Spatrick using Directive = VerifyDiagnosticConsumer::Directive;
50e5dd7070Spatrick using DirectiveList = VerifyDiagnosticConsumer::DirectiveList;
51e5dd7070Spatrick using ExpectedData = VerifyDiagnosticConsumer::ExpectedData;
52e5dd7070Spatrick 
53e5dd7070Spatrick #ifndef NDEBUG
54e5dd7070Spatrick 
55e5dd7070Spatrick namespace {
56e5dd7070Spatrick 
57e5dd7070Spatrick class VerifyFileTracker : public PPCallbacks {
58e5dd7070Spatrick   VerifyDiagnosticConsumer &Verify;
59e5dd7070Spatrick   SourceManager &SM;
60e5dd7070Spatrick 
61e5dd7070Spatrick public:
VerifyFileTracker(VerifyDiagnosticConsumer & Verify,SourceManager & SM)62e5dd7070Spatrick   VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM)
63e5dd7070Spatrick       : Verify(Verify), SM(SM) {}
64e5dd7070Spatrick 
65e5dd7070Spatrick   /// Hook into the preprocessor and update the list of parsed
66e5dd7070Spatrick   /// files when the preprocessor indicates a new file is entered.
FileChanged(SourceLocation Loc,FileChangeReason Reason,SrcMgr::CharacteristicKind FileType,FileID PrevFID)67e5dd7070Spatrick   void FileChanged(SourceLocation Loc, FileChangeReason Reason,
68e5dd7070Spatrick                    SrcMgr::CharacteristicKind FileType,
69e5dd7070Spatrick                    FileID PrevFID) override {
70e5dd7070Spatrick     Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc),
71e5dd7070Spatrick                                   VerifyDiagnosticConsumer::IsParsed);
72e5dd7070Spatrick   }
73e5dd7070Spatrick };
74e5dd7070Spatrick 
75e5dd7070Spatrick } // namespace
76e5dd7070Spatrick 
77e5dd7070Spatrick #endif
78e5dd7070Spatrick 
79e5dd7070Spatrick //===----------------------------------------------------------------------===//
80e5dd7070Spatrick // Checking diagnostics implementation.
81e5dd7070Spatrick //===----------------------------------------------------------------------===//
82e5dd7070Spatrick 
83e5dd7070Spatrick using DiagList = TextDiagnosticBuffer::DiagList;
84e5dd7070Spatrick using const_diag_iterator = TextDiagnosticBuffer::const_iterator;
85e5dd7070Spatrick 
86e5dd7070Spatrick namespace {
87e5dd7070Spatrick 
88e5dd7070Spatrick /// StandardDirective - Directive with string matching.
89e5dd7070Spatrick class StandardDirective : public Directive {
90e5dd7070Spatrick public:
StandardDirective(SourceLocation DirectiveLoc,SourceLocation DiagnosticLoc,bool MatchAnyFileAndLine,bool MatchAnyLine,StringRef Text,unsigned Min,unsigned Max)91e5dd7070Spatrick   StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
92ec727ea7Spatrick                     bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
93ec727ea7Spatrick                     unsigned Min, unsigned Max)
94ec727ea7Spatrick       : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
95ec727ea7Spatrick                   MatchAnyLine, Text, Min, Max) {}
96e5dd7070Spatrick 
isValid(std::string & Error)97e5dd7070Spatrick   bool isValid(std::string &Error) override {
98e5dd7070Spatrick     // all strings are considered valid; even empty ones
99e5dd7070Spatrick     return true;
100e5dd7070Spatrick   }
101e5dd7070Spatrick 
match(StringRef S)102*12c85518Srobert   bool match(StringRef S) override { return S.contains(Text); }
103e5dd7070Spatrick };
104e5dd7070Spatrick 
105e5dd7070Spatrick /// RegexDirective - Directive with regular-expression matching.
106e5dd7070Spatrick class RegexDirective : public Directive {
107e5dd7070Spatrick public:
RegexDirective(SourceLocation DirectiveLoc,SourceLocation DiagnosticLoc,bool MatchAnyFileAndLine,bool MatchAnyLine,StringRef Text,unsigned Min,unsigned Max,StringRef RegexStr)108e5dd7070Spatrick   RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc,
109ec727ea7Spatrick                  bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text,
110ec727ea7Spatrick                  unsigned Min, unsigned Max, StringRef RegexStr)
111ec727ea7Spatrick       : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine,
112ec727ea7Spatrick                   MatchAnyLine, Text, Min, Max),
113e5dd7070Spatrick         Regex(RegexStr) {}
114e5dd7070Spatrick 
isValid(std::string & Error)115e5dd7070Spatrick   bool isValid(std::string &Error) override {
116e5dd7070Spatrick     return Regex.isValid(Error);
117e5dd7070Spatrick   }
118e5dd7070Spatrick 
match(StringRef S)119e5dd7070Spatrick   bool match(StringRef S) override {
120e5dd7070Spatrick     return Regex.match(S);
121e5dd7070Spatrick   }
122e5dd7070Spatrick 
123e5dd7070Spatrick private:
124e5dd7070Spatrick   llvm::Regex Regex;
125e5dd7070Spatrick };
126e5dd7070Spatrick 
127e5dd7070Spatrick class ParseHelper
128e5dd7070Spatrick {
129e5dd7070Spatrick public:
ParseHelper(StringRef S)130e5dd7070Spatrick   ParseHelper(StringRef S)
131e5dd7070Spatrick       : Begin(S.begin()), End(S.end()), C(Begin), P(Begin) {}
132e5dd7070Spatrick 
133e5dd7070Spatrick   // Return true if string literal is next.
Next(StringRef S)134e5dd7070Spatrick   bool Next(StringRef S) {
135e5dd7070Spatrick     P = C;
136e5dd7070Spatrick     PEnd = C + S.size();
137e5dd7070Spatrick     if (PEnd > End)
138e5dd7070Spatrick       return false;
139e5dd7070Spatrick     return memcmp(P, S.data(), S.size()) == 0;
140e5dd7070Spatrick   }
141e5dd7070Spatrick 
142e5dd7070Spatrick   // Return true if number is next.
143e5dd7070Spatrick   // Output N only if number is next.
Next(unsigned & N)144e5dd7070Spatrick   bool Next(unsigned &N) {
145e5dd7070Spatrick     unsigned TMP = 0;
146e5dd7070Spatrick     P = C;
147e5dd7070Spatrick     PEnd = P;
148e5dd7070Spatrick     for (; PEnd < End && *PEnd >= '0' && *PEnd <= '9'; ++PEnd) {
149e5dd7070Spatrick       TMP *= 10;
150e5dd7070Spatrick       TMP += *PEnd - '0';
151e5dd7070Spatrick     }
152e5dd7070Spatrick     if (PEnd == C)
153e5dd7070Spatrick       return false;
154e5dd7070Spatrick     N = TMP;
155e5dd7070Spatrick     return true;
156e5dd7070Spatrick   }
157e5dd7070Spatrick 
158e5dd7070Spatrick   // Return true if a marker is next.
159e5dd7070Spatrick   // A marker is the longest match for /#[A-Za-z0-9_-]+/.
NextMarker()160e5dd7070Spatrick   bool NextMarker() {
161e5dd7070Spatrick     P = C;
162e5dd7070Spatrick     if (P == End || *P != '#')
163e5dd7070Spatrick       return false;
164e5dd7070Spatrick     PEnd = P;
165e5dd7070Spatrick     ++PEnd;
166e5dd7070Spatrick     while ((isAlphanumeric(*PEnd) || *PEnd == '-' || *PEnd == '_') &&
167e5dd7070Spatrick            PEnd < End)
168e5dd7070Spatrick       ++PEnd;
169e5dd7070Spatrick     return PEnd > P + 1;
170e5dd7070Spatrick   }
171e5dd7070Spatrick 
172e5dd7070Spatrick   // Return true if string literal S is matched in content.
173e5dd7070Spatrick   // When true, P marks begin-position of the match, and calling Advance sets C
174e5dd7070Spatrick   // to end-position of the match.
175e5dd7070Spatrick   // If S is the empty string, then search for any letter instead (makes sense
176e5dd7070Spatrick   // with FinishDirectiveToken=true).
177e5dd7070Spatrick   // If EnsureStartOfWord, then skip matches that don't start a new word.
178e5dd7070Spatrick   // If FinishDirectiveToken, then assume the match is the start of a comment
179e5dd7070Spatrick   // directive for -verify, and extend the match to include the entire first
180e5dd7070Spatrick   // token of that directive.
Search(StringRef S,bool EnsureStartOfWord=false,bool FinishDirectiveToken=false)181e5dd7070Spatrick   bool Search(StringRef S, bool EnsureStartOfWord = false,
182e5dd7070Spatrick               bool FinishDirectiveToken = false) {
183e5dd7070Spatrick     do {
184e5dd7070Spatrick       if (!S.empty()) {
185e5dd7070Spatrick         P = std::search(C, End, S.begin(), S.end());
186e5dd7070Spatrick         PEnd = P + S.size();
187e5dd7070Spatrick       }
188e5dd7070Spatrick       else {
189e5dd7070Spatrick         P = C;
190e5dd7070Spatrick         while (P != End && !isLetter(*P))
191e5dd7070Spatrick           ++P;
192e5dd7070Spatrick         PEnd = P + 1;
193e5dd7070Spatrick       }
194e5dd7070Spatrick       if (P == End)
195e5dd7070Spatrick         break;
196e5dd7070Spatrick       // If not start of word but required, skip and search again.
197e5dd7070Spatrick       if (EnsureStartOfWord
198e5dd7070Spatrick                // Check if string literal starts a new word.
199e5dd7070Spatrick           && !(P == Begin || isWhitespace(P[-1])
200e5dd7070Spatrick                // Or it could be preceded by the start of a comment.
201e5dd7070Spatrick                || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*')
202e5dd7070Spatrick                                    &&  P[-2] == '/')))
203e5dd7070Spatrick         continue;
204e5dd7070Spatrick       if (FinishDirectiveToken) {
205e5dd7070Spatrick         while (PEnd != End && (isAlphanumeric(*PEnd)
206e5dd7070Spatrick                                || *PEnd == '-' || *PEnd == '_'))
207e5dd7070Spatrick           ++PEnd;
208e5dd7070Spatrick         // Put back trailing digits and hyphens to be parsed later as a count
209e5dd7070Spatrick         // or count range.  Because -verify prefixes must start with letters,
210e5dd7070Spatrick         // we know the actual directive we found starts with a letter, so
211e5dd7070Spatrick         // we won't put back the entire directive word and thus record an empty
212e5dd7070Spatrick         // string.
213e5dd7070Spatrick         assert(isLetter(*P) && "-verify prefix must start with a letter");
214e5dd7070Spatrick         while (isDigit(PEnd[-1]) || PEnd[-1] == '-')
215e5dd7070Spatrick           --PEnd;
216e5dd7070Spatrick       }
217e5dd7070Spatrick       return true;
218e5dd7070Spatrick     } while (Advance());
219e5dd7070Spatrick     return false;
220e5dd7070Spatrick   }
221e5dd7070Spatrick 
222e5dd7070Spatrick   // Return true if a CloseBrace that closes the OpenBrace at the current nest
223e5dd7070Spatrick   // level is found. When true, P marks begin-position of CloseBrace.
SearchClosingBrace(StringRef OpenBrace,StringRef CloseBrace)224e5dd7070Spatrick   bool SearchClosingBrace(StringRef OpenBrace, StringRef CloseBrace) {
225e5dd7070Spatrick     unsigned Depth = 1;
226e5dd7070Spatrick     P = C;
227e5dd7070Spatrick     while (P < End) {
228e5dd7070Spatrick       StringRef S(P, End - P);
229e5dd7070Spatrick       if (S.startswith(OpenBrace)) {
230e5dd7070Spatrick         ++Depth;
231e5dd7070Spatrick         P += OpenBrace.size();
232e5dd7070Spatrick       } else if (S.startswith(CloseBrace)) {
233e5dd7070Spatrick         --Depth;
234e5dd7070Spatrick         if (Depth == 0) {
235e5dd7070Spatrick           PEnd = P + CloseBrace.size();
236e5dd7070Spatrick           return true;
237e5dd7070Spatrick         }
238e5dd7070Spatrick         P += CloseBrace.size();
239e5dd7070Spatrick       } else {
240e5dd7070Spatrick         ++P;
241e5dd7070Spatrick       }
242e5dd7070Spatrick     }
243e5dd7070Spatrick     return false;
244e5dd7070Spatrick   }
245e5dd7070Spatrick 
246e5dd7070Spatrick   // Advance 1-past previous next/search.
247e5dd7070Spatrick   // Behavior is undefined if previous next/search failed.
Advance()248e5dd7070Spatrick   bool Advance() {
249e5dd7070Spatrick     C = PEnd;
250e5dd7070Spatrick     return C < End;
251e5dd7070Spatrick   }
252e5dd7070Spatrick 
253e5dd7070Spatrick   // Return the text matched by the previous next/search.
254e5dd7070Spatrick   // Behavior is undefined if previous next/search failed.
Match()255e5dd7070Spatrick   StringRef Match() { return StringRef(P, PEnd - P); }
256e5dd7070Spatrick 
257e5dd7070Spatrick   // Skip zero or more whitespace.
SkipWhitespace()258e5dd7070Spatrick   void SkipWhitespace() {
259e5dd7070Spatrick     for (; C < End && isWhitespace(*C); ++C)
260e5dd7070Spatrick       ;
261e5dd7070Spatrick   }
262e5dd7070Spatrick 
263e5dd7070Spatrick   // Return true if EOF reached.
Done()264e5dd7070Spatrick   bool Done() {
265e5dd7070Spatrick     return !(C < End);
266e5dd7070Spatrick   }
267e5dd7070Spatrick 
268e5dd7070Spatrick   // Beginning of expected content.
269e5dd7070Spatrick   const char * const Begin;
270e5dd7070Spatrick 
271e5dd7070Spatrick   // End of expected content (1-past).
272e5dd7070Spatrick   const char * const End;
273e5dd7070Spatrick 
274e5dd7070Spatrick   // Position of next char in content.
275e5dd7070Spatrick   const char *C;
276e5dd7070Spatrick 
277e5dd7070Spatrick   // Previous next/search subject start.
278e5dd7070Spatrick   const char *P;
279e5dd7070Spatrick 
280e5dd7070Spatrick private:
281e5dd7070Spatrick   // Previous next/search subject end (1-past).
282e5dd7070Spatrick   const char *PEnd = nullptr;
283e5dd7070Spatrick };
284e5dd7070Spatrick 
285e5dd7070Spatrick // The information necessary to create a directive.
286e5dd7070Spatrick struct UnattachedDirective {
287e5dd7070Spatrick   DirectiveList *DL = nullptr;
288e5dd7070Spatrick   bool RegexKind = false;
289e5dd7070Spatrick   SourceLocation DirectivePos, ContentBegin;
290e5dd7070Spatrick   std::string Text;
291e5dd7070Spatrick   unsigned Min = 1, Max = 1;
292e5dd7070Spatrick };
293e5dd7070Spatrick 
294e5dd7070Spatrick // Attach the specified directive to the line of code indicated by
295e5dd7070Spatrick // \p ExpectedLoc.
attachDirective(DiagnosticsEngine & Diags,const UnattachedDirective & UD,SourceLocation ExpectedLoc,bool MatchAnyFileAndLine=false,bool MatchAnyLine=false)296e5dd7070Spatrick void attachDirective(DiagnosticsEngine &Diags, const UnattachedDirective &UD,
297ec727ea7Spatrick                      SourceLocation ExpectedLoc,
298ec727ea7Spatrick                      bool MatchAnyFileAndLine = false,
299ec727ea7Spatrick                      bool MatchAnyLine = false) {
300e5dd7070Spatrick   // Construct new directive.
301ec727ea7Spatrick   std::unique_ptr<Directive> D = Directive::create(
302ec727ea7Spatrick       UD.RegexKind, UD.DirectivePos, ExpectedLoc, MatchAnyFileAndLine,
303e5dd7070Spatrick       MatchAnyLine, UD.Text, UD.Min, UD.Max);
304e5dd7070Spatrick 
305e5dd7070Spatrick   std::string Error;
306e5dd7070Spatrick   if (!D->isValid(Error)) {
307e5dd7070Spatrick     Diags.Report(UD.ContentBegin, diag::err_verify_invalid_content)
308e5dd7070Spatrick       << (UD.RegexKind ? "regex" : "string") << Error;
309e5dd7070Spatrick   }
310e5dd7070Spatrick 
311e5dd7070Spatrick   UD.DL->push_back(std::move(D));
312e5dd7070Spatrick }
313e5dd7070Spatrick 
314e5dd7070Spatrick } // anonymous
315e5dd7070Spatrick 
316e5dd7070Spatrick // Tracker for markers in the input files. A marker is a comment of the form
317e5dd7070Spatrick //
318e5dd7070Spatrick //   n = 123; // #123
319e5dd7070Spatrick //
320e5dd7070Spatrick // ... that can be referred to by a later expected-* directive:
321e5dd7070Spatrick //
322e5dd7070Spatrick //   // expected-error@#123 {{undeclared identifier 'n'}}
323e5dd7070Spatrick //
324e5dd7070Spatrick // Marker declarations must be at the start of a comment or preceded by
325e5dd7070Spatrick // whitespace to distinguish them from uses of markers in directives.
326e5dd7070Spatrick class VerifyDiagnosticConsumer::MarkerTracker {
327e5dd7070Spatrick   DiagnosticsEngine &Diags;
328e5dd7070Spatrick 
329e5dd7070Spatrick   struct Marker {
330e5dd7070Spatrick     SourceLocation DefLoc;
331e5dd7070Spatrick     SourceLocation RedefLoc;
332e5dd7070Spatrick     SourceLocation UseLoc;
333e5dd7070Spatrick   };
334e5dd7070Spatrick   llvm::StringMap<Marker> Markers;
335e5dd7070Spatrick 
336e5dd7070Spatrick   // Directives that couldn't be created yet because they name an unknown
337e5dd7070Spatrick   // marker.
338e5dd7070Spatrick   llvm::StringMap<llvm::SmallVector<UnattachedDirective, 2>> DeferredDirectives;
339e5dd7070Spatrick 
340e5dd7070Spatrick public:
MarkerTracker(DiagnosticsEngine & Diags)341e5dd7070Spatrick   MarkerTracker(DiagnosticsEngine &Diags) : Diags(Diags) {}
342e5dd7070Spatrick 
343e5dd7070Spatrick   // Register a marker.
addMarker(StringRef MarkerName,SourceLocation Pos)344e5dd7070Spatrick   void addMarker(StringRef MarkerName, SourceLocation Pos) {
345e5dd7070Spatrick     auto InsertResult = Markers.insert(
346e5dd7070Spatrick         {MarkerName, Marker{Pos, SourceLocation(), SourceLocation()}});
347e5dd7070Spatrick 
348e5dd7070Spatrick     Marker &M = InsertResult.first->second;
349e5dd7070Spatrick     if (!InsertResult.second) {
350e5dd7070Spatrick       // Marker was redefined.
351e5dd7070Spatrick       M.RedefLoc = Pos;
352e5dd7070Spatrick     } else {
353e5dd7070Spatrick       // First definition: build any deferred directives.
354e5dd7070Spatrick       auto Deferred = DeferredDirectives.find(MarkerName);
355e5dd7070Spatrick       if (Deferred != DeferredDirectives.end()) {
356e5dd7070Spatrick         for (auto &UD : Deferred->second) {
357e5dd7070Spatrick           if (M.UseLoc.isInvalid())
358e5dd7070Spatrick             M.UseLoc = UD.DirectivePos;
359e5dd7070Spatrick           attachDirective(Diags, UD, Pos);
360e5dd7070Spatrick         }
361e5dd7070Spatrick         DeferredDirectives.erase(Deferred);
362e5dd7070Spatrick       }
363e5dd7070Spatrick     }
364e5dd7070Spatrick   }
365e5dd7070Spatrick 
366e5dd7070Spatrick   // Register a directive at the specified marker.
addDirective(StringRef MarkerName,const UnattachedDirective & UD)367e5dd7070Spatrick   void addDirective(StringRef MarkerName, const UnattachedDirective &UD) {
368e5dd7070Spatrick     auto MarkerIt = Markers.find(MarkerName);
369e5dd7070Spatrick     if (MarkerIt != Markers.end()) {
370e5dd7070Spatrick       Marker &M = MarkerIt->second;
371e5dd7070Spatrick       if (M.UseLoc.isInvalid())
372e5dd7070Spatrick         M.UseLoc = UD.DirectivePos;
373e5dd7070Spatrick       return attachDirective(Diags, UD, M.DefLoc);
374e5dd7070Spatrick     }
375e5dd7070Spatrick     DeferredDirectives[MarkerName].push_back(UD);
376e5dd7070Spatrick   }
377e5dd7070Spatrick 
378e5dd7070Spatrick   // Ensure we have no remaining deferred directives, and no
379e5dd7070Spatrick   // multiply-defined-and-used markers.
finalize()380e5dd7070Spatrick   void finalize() {
381e5dd7070Spatrick     for (auto &MarkerInfo : Markers) {
382e5dd7070Spatrick       StringRef Name = MarkerInfo.first();
383e5dd7070Spatrick       Marker &M = MarkerInfo.second;
384e5dd7070Spatrick       if (M.RedefLoc.isValid() && M.UseLoc.isValid()) {
385e5dd7070Spatrick         Diags.Report(M.UseLoc, diag::err_verify_ambiguous_marker) << Name;
386e5dd7070Spatrick         Diags.Report(M.DefLoc, diag::note_verify_ambiguous_marker) << Name;
387e5dd7070Spatrick         Diags.Report(M.RedefLoc, diag::note_verify_ambiguous_marker) << Name;
388e5dd7070Spatrick       }
389e5dd7070Spatrick     }
390e5dd7070Spatrick 
391e5dd7070Spatrick     for (auto &DeferredPair : DeferredDirectives) {
392e5dd7070Spatrick       Diags.Report(DeferredPair.second.front().DirectivePos,
393e5dd7070Spatrick                    diag::err_verify_no_such_marker)
394e5dd7070Spatrick           << DeferredPair.first();
395e5dd7070Spatrick     }
396e5dd7070Spatrick   }
397e5dd7070Spatrick };
398e5dd7070Spatrick 
399e5dd7070Spatrick /// ParseDirective - Go through the comment and see if it indicates expected
400e5dd7070Spatrick /// diagnostics. If so, then put them in the appropriate directive list.
401e5dd7070Spatrick ///
402e5dd7070Spatrick /// Returns true if any valid directives were found.
ParseDirective(StringRef S,ExpectedData * ED,SourceManager & SM,Preprocessor * PP,SourceLocation Pos,VerifyDiagnosticConsumer::DirectiveStatus & Status,VerifyDiagnosticConsumer::MarkerTracker & Markers)403e5dd7070Spatrick static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM,
404e5dd7070Spatrick                            Preprocessor *PP, SourceLocation Pos,
405e5dd7070Spatrick                            VerifyDiagnosticConsumer::DirectiveStatus &Status,
406e5dd7070Spatrick                            VerifyDiagnosticConsumer::MarkerTracker &Markers) {
407e5dd7070Spatrick   DiagnosticsEngine &Diags = PP ? PP->getDiagnostics() : SM.getDiagnostics();
408e5dd7070Spatrick 
409e5dd7070Spatrick   // First, scan the comment looking for markers.
410e5dd7070Spatrick   for (ParseHelper PH(S); !PH.Done();) {
411e5dd7070Spatrick     if (!PH.Search("#", true))
412e5dd7070Spatrick       break;
413e5dd7070Spatrick     PH.C = PH.P;
414e5dd7070Spatrick     if (!PH.NextMarker()) {
415e5dd7070Spatrick       PH.Next("#");
416e5dd7070Spatrick       PH.Advance();
417e5dd7070Spatrick       continue;
418e5dd7070Spatrick     }
419e5dd7070Spatrick     PH.Advance();
420e5dd7070Spatrick     Markers.addMarker(PH.Match(), Pos);
421e5dd7070Spatrick   }
422e5dd7070Spatrick 
423e5dd7070Spatrick   // A single comment may contain multiple directives.
424e5dd7070Spatrick   bool FoundDirective = false;
425e5dd7070Spatrick   for (ParseHelper PH(S); !PH.Done();) {
426e5dd7070Spatrick     // Search for the initial directive token.
427e5dd7070Spatrick     // If one prefix, save time by searching only for its directives.
428e5dd7070Spatrick     // Otherwise, search for any potential directive token and check it later.
429e5dd7070Spatrick     const auto &Prefixes = Diags.getDiagnosticOptions().VerifyPrefixes;
430e5dd7070Spatrick     if (!(Prefixes.size() == 1 ? PH.Search(*Prefixes.begin(), true, true)
431e5dd7070Spatrick                                : PH.Search("", true, true)))
432e5dd7070Spatrick       break;
433e5dd7070Spatrick 
434e5dd7070Spatrick     StringRef DToken = PH.Match();
435e5dd7070Spatrick     PH.Advance();
436e5dd7070Spatrick 
437e5dd7070Spatrick     // Default directive kind.
438e5dd7070Spatrick     UnattachedDirective D;
439e5dd7070Spatrick     const char *KindStr = "string";
440e5dd7070Spatrick 
441e5dd7070Spatrick     // Parse the initial directive token in reverse so we can easily determine
442e5dd7070Spatrick     // its exact actual prefix.  If we were to parse it from the front instead,
443e5dd7070Spatrick     // it would be harder to determine where the prefix ends because there
444e5dd7070Spatrick     // might be multiple matching -verify prefixes because some might prefix
445e5dd7070Spatrick     // others.
446e5dd7070Spatrick 
447e5dd7070Spatrick     // Regex in initial directive token: -re
448e5dd7070Spatrick     if (DToken.endswith("-re")) {
449e5dd7070Spatrick       D.RegexKind = true;
450e5dd7070Spatrick       KindStr = "regex";
451e5dd7070Spatrick       DToken = DToken.substr(0, DToken.size()-3);
452e5dd7070Spatrick     }
453e5dd7070Spatrick 
454e5dd7070Spatrick     // Type in initial directive token: -{error|warning|note|no-diagnostics}
455e5dd7070Spatrick     bool NoDiag = false;
456e5dd7070Spatrick     StringRef DType;
457e5dd7070Spatrick     if (DToken.endswith(DType="-error"))
458e5dd7070Spatrick       D.DL = ED ? &ED->Errors : nullptr;
459e5dd7070Spatrick     else if (DToken.endswith(DType="-warning"))
460e5dd7070Spatrick       D.DL = ED ? &ED->Warnings : nullptr;
461e5dd7070Spatrick     else if (DToken.endswith(DType="-remark"))
462e5dd7070Spatrick       D.DL = ED ? &ED->Remarks : nullptr;
463e5dd7070Spatrick     else if (DToken.endswith(DType="-note"))
464e5dd7070Spatrick       D.DL = ED ? &ED->Notes : nullptr;
465e5dd7070Spatrick     else if (DToken.endswith(DType="-no-diagnostics")) {
466e5dd7070Spatrick       NoDiag = true;
467e5dd7070Spatrick       if (D.RegexKind)
468e5dd7070Spatrick         continue;
469e5dd7070Spatrick     }
470e5dd7070Spatrick     else
471e5dd7070Spatrick       continue;
472e5dd7070Spatrick     DToken = DToken.substr(0, DToken.size()-DType.size());
473e5dd7070Spatrick 
474e5dd7070Spatrick     // What's left in DToken is the actual prefix.  That might not be a -verify
475e5dd7070Spatrick     // prefix even if there is only one -verify prefix (for example, the full
476e5dd7070Spatrick     // DToken is foo-bar-warning, but foo is the only -verify prefix).
477e5dd7070Spatrick     if (!std::binary_search(Prefixes.begin(), Prefixes.end(), DToken))
478e5dd7070Spatrick       continue;
479e5dd7070Spatrick 
480e5dd7070Spatrick     if (NoDiag) {
481e5dd7070Spatrick       if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives)
482e5dd7070Spatrick         Diags.Report(Pos, diag::err_verify_invalid_no_diags)
483e5dd7070Spatrick           << /*IsExpectedNoDiagnostics=*/true;
484e5dd7070Spatrick       else
485e5dd7070Spatrick         Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics;
486e5dd7070Spatrick       continue;
487e5dd7070Spatrick     }
488e5dd7070Spatrick     if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) {
489e5dd7070Spatrick       Diags.Report(Pos, diag::err_verify_invalid_no_diags)
490e5dd7070Spatrick         << /*IsExpectedNoDiagnostics=*/false;
491e5dd7070Spatrick       continue;
492e5dd7070Spatrick     }
493e5dd7070Spatrick     Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives;
494e5dd7070Spatrick 
495e5dd7070Spatrick     // If a directive has been found but we're not interested
496e5dd7070Spatrick     // in storing the directive information, return now.
497e5dd7070Spatrick     if (!D.DL)
498e5dd7070Spatrick       return true;
499e5dd7070Spatrick 
500e5dd7070Spatrick     // Next optional token: @
501e5dd7070Spatrick     SourceLocation ExpectedLoc;
502e5dd7070Spatrick     StringRef Marker;
503ec727ea7Spatrick     bool MatchAnyFileAndLine = false;
504e5dd7070Spatrick     bool MatchAnyLine = false;
505e5dd7070Spatrick     if (!PH.Next("@")) {
506e5dd7070Spatrick       ExpectedLoc = Pos;
507e5dd7070Spatrick     } else {
508e5dd7070Spatrick       PH.Advance();
509e5dd7070Spatrick       unsigned Line = 0;
510e5dd7070Spatrick       bool FoundPlus = PH.Next("+");
511e5dd7070Spatrick       if (FoundPlus || PH.Next("-")) {
512e5dd7070Spatrick         // Relative to current line.
513e5dd7070Spatrick         PH.Advance();
514e5dd7070Spatrick         bool Invalid = false;
515e5dd7070Spatrick         unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid);
516e5dd7070Spatrick         if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) {
517e5dd7070Spatrick           if (FoundPlus) ExpectedLine += Line;
518e5dd7070Spatrick           else ExpectedLine -= Line;
519e5dd7070Spatrick           ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1);
520e5dd7070Spatrick         }
521e5dd7070Spatrick       } else if (PH.Next(Line)) {
522e5dd7070Spatrick         // Absolute line number.
523e5dd7070Spatrick         if (Line > 0)
524e5dd7070Spatrick           ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1);
525e5dd7070Spatrick       } else if (PH.NextMarker()) {
526e5dd7070Spatrick         Marker = PH.Match();
527e5dd7070Spatrick       } else if (PP && PH.Search(":")) {
528e5dd7070Spatrick         // Specific source file.
529e5dd7070Spatrick         StringRef Filename(PH.C, PH.P-PH.C);
530e5dd7070Spatrick         PH.Advance();
531e5dd7070Spatrick 
532ec727ea7Spatrick         if (Filename == "*") {
533ec727ea7Spatrick           MatchAnyFileAndLine = true;
534ec727ea7Spatrick           if (!PH.Next("*")) {
535ec727ea7Spatrick             Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
536ec727ea7Spatrick                          diag::err_verify_missing_line)
537ec727ea7Spatrick                 << "'*'";
538ec727ea7Spatrick             continue;
539ec727ea7Spatrick           }
540ec727ea7Spatrick           MatchAnyLine = true;
541ec727ea7Spatrick           ExpectedLoc = SourceLocation();
542ec727ea7Spatrick         } else {
543e5dd7070Spatrick           // Lookup file via Preprocessor, like a #include.
544*12c85518Srobert           OptionalFileEntryRef File =
545*12c85518Srobert               PP->LookupFile(Pos, Filename, false, nullptr, nullptr, nullptr,
546e5dd7070Spatrick                              nullptr, nullptr, nullptr, nullptr, nullptr);
547e5dd7070Spatrick           if (!File) {
548e5dd7070Spatrick             Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin),
549ec727ea7Spatrick                          diag::err_verify_missing_file)
550ec727ea7Spatrick                 << Filename << KindStr;
551e5dd7070Spatrick             continue;
552e5dd7070Spatrick           }
553e5dd7070Spatrick 
554a9ac8606Spatrick           FileID FID = SM.translateFile(*File);
555a9ac8606Spatrick           if (FID.isInvalid())
556a9ac8606Spatrick             FID = SM.createFileID(*File, Pos, SrcMgr::C_User);
557e5dd7070Spatrick 
558e5dd7070Spatrick           if (PH.Next(Line) && Line > 0)
559a9ac8606Spatrick             ExpectedLoc = SM.translateLineCol(FID, Line, 1);
560e5dd7070Spatrick           else if (PH.Next("*")) {
561e5dd7070Spatrick             MatchAnyLine = true;
562a9ac8606Spatrick             ExpectedLoc = SM.translateLineCol(FID, 1, 1);
563e5dd7070Spatrick           }
564ec727ea7Spatrick         }
565e5dd7070Spatrick       } else if (PH.Next("*")) {
566e5dd7070Spatrick         MatchAnyLine = true;
567e5dd7070Spatrick         ExpectedLoc = SourceLocation();
568e5dd7070Spatrick       }
569e5dd7070Spatrick 
570e5dd7070Spatrick       if (ExpectedLoc.isInvalid() && !MatchAnyLine && Marker.empty()) {
571e5dd7070Spatrick         Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
572e5dd7070Spatrick                      diag::err_verify_missing_line) << KindStr;
573e5dd7070Spatrick         continue;
574e5dd7070Spatrick       }
575e5dd7070Spatrick       PH.Advance();
576e5dd7070Spatrick     }
577e5dd7070Spatrick 
578e5dd7070Spatrick     // Skip optional whitespace.
579e5dd7070Spatrick     PH.SkipWhitespace();
580e5dd7070Spatrick 
581e5dd7070Spatrick     // Next optional token: positive integer or a '+'.
582e5dd7070Spatrick     if (PH.Next(D.Min)) {
583e5dd7070Spatrick       PH.Advance();
584e5dd7070Spatrick       // A positive integer can be followed by a '+' meaning min
585e5dd7070Spatrick       // or more, or by a '-' meaning a range from min to max.
586e5dd7070Spatrick       if (PH.Next("+")) {
587e5dd7070Spatrick         D.Max = Directive::MaxCount;
588e5dd7070Spatrick         PH.Advance();
589e5dd7070Spatrick       } else if (PH.Next("-")) {
590e5dd7070Spatrick         PH.Advance();
591e5dd7070Spatrick         if (!PH.Next(D.Max) || D.Max < D.Min) {
592e5dd7070Spatrick           Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
593e5dd7070Spatrick                        diag::err_verify_invalid_range) << KindStr;
594e5dd7070Spatrick           continue;
595e5dd7070Spatrick         }
596e5dd7070Spatrick         PH.Advance();
597e5dd7070Spatrick       } else {
598e5dd7070Spatrick         D.Max = D.Min;
599e5dd7070Spatrick       }
600e5dd7070Spatrick     } else if (PH.Next("+")) {
601e5dd7070Spatrick       // '+' on its own means "1 or more".
602e5dd7070Spatrick       D.Max = Directive::MaxCount;
603e5dd7070Spatrick       PH.Advance();
604e5dd7070Spatrick     }
605e5dd7070Spatrick 
606e5dd7070Spatrick     // Skip optional whitespace.
607e5dd7070Spatrick     PH.SkipWhitespace();
608e5dd7070Spatrick 
609e5dd7070Spatrick     // Next token: {{
610e5dd7070Spatrick     if (!PH.Next("{{")) {
611e5dd7070Spatrick       Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
612e5dd7070Spatrick                    diag::err_verify_missing_start) << KindStr;
613e5dd7070Spatrick       continue;
614e5dd7070Spatrick     }
615e5dd7070Spatrick     PH.Advance();
616e5dd7070Spatrick     const char* const ContentBegin = PH.C; // mark content begin
617e5dd7070Spatrick     // Search for token: }}
618e5dd7070Spatrick     if (!PH.SearchClosingBrace("{{", "}}")) {
619e5dd7070Spatrick       Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin),
620e5dd7070Spatrick                    diag::err_verify_missing_end) << KindStr;
621e5dd7070Spatrick       continue;
622e5dd7070Spatrick     }
623e5dd7070Spatrick     const char* const ContentEnd = PH.P; // mark content end
624e5dd7070Spatrick     PH.Advance();
625e5dd7070Spatrick 
626e5dd7070Spatrick     D.DirectivePos = Pos;
627e5dd7070Spatrick     D.ContentBegin = Pos.getLocWithOffset(ContentBegin - PH.Begin);
628e5dd7070Spatrick 
629e5dd7070Spatrick     // Build directive text; convert \n to newlines.
630e5dd7070Spatrick     StringRef NewlineStr = "\\n";
631e5dd7070Spatrick     StringRef Content(ContentBegin, ContentEnd-ContentBegin);
632e5dd7070Spatrick     size_t CPos = 0;
633e5dd7070Spatrick     size_t FPos;
634e5dd7070Spatrick     while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) {
635e5dd7070Spatrick       D.Text += Content.substr(CPos, FPos-CPos);
636e5dd7070Spatrick       D.Text += '\n';
637e5dd7070Spatrick       CPos = FPos + NewlineStr.size();
638e5dd7070Spatrick     }
639e5dd7070Spatrick     if (D.Text.empty())
640e5dd7070Spatrick       D.Text.assign(ContentBegin, ContentEnd);
641e5dd7070Spatrick 
642e5dd7070Spatrick     // Check that regex directives contain at least one regex.
643e5dd7070Spatrick     if (D.RegexKind && D.Text.find("{{") == StringRef::npos) {
644e5dd7070Spatrick       Diags.Report(D.ContentBegin, diag::err_verify_missing_regex) << D.Text;
645e5dd7070Spatrick       return false;
646e5dd7070Spatrick     }
647e5dd7070Spatrick 
648e5dd7070Spatrick     if (Marker.empty())
649ec727ea7Spatrick       attachDirective(Diags, D, ExpectedLoc, MatchAnyFileAndLine, MatchAnyLine);
650e5dd7070Spatrick     else
651e5dd7070Spatrick       Markers.addDirective(Marker, D);
652e5dd7070Spatrick     FoundDirective = true;
653e5dd7070Spatrick   }
654e5dd7070Spatrick 
655e5dd7070Spatrick   return FoundDirective;
656e5dd7070Spatrick }
657e5dd7070Spatrick 
VerifyDiagnosticConsumer(DiagnosticsEngine & Diags_)658e5dd7070Spatrick VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &Diags_)
659e5dd7070Spatrick     : Diags(Diags_), PrimaryClient(Diags.getClient()),
660e5dd7070Spatrick       PrimaryClientOwner(Diags.takeClient()),
661e5dd7070Spatrick       Buffer(new TextDiagnosticBuffer()), Markers(new MarkerTracker(Diags)),
662e5dd7070Spatrick       Status(HasNoDirectives) {
663e5dd7070Spatrick   if (Diags.hasSourceManager())
664e5dd7070Spatrick     setSourceManager(Diags.getSourceManager());
665e5dd7070Spatrick }
666e5dd7070Spatrick 
~VerifyDiagnosticConsumer()667e5dd7070Spatrick VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() {
668e5dd7070Spatrick   assert(!ActiveSourceFiles && "Incomplete parsing of source files!");
669e5dd7070Spatrick   assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!");
670e5dd7070Spatrick   SrcManager = nullptr;
671e5dd7070Spatrick   CheckDiagnostics();
672e5dd7070Spatrick   assert(!Diags.ownsClient() &&
673e5dd7070Spatrick          "The VerifyDiagnosticConsumer takes over ownership of the client!");
674e5dd7070Spatrick }
675e5dd7070Spatrick 
676e5dd7070Spatrick // DiagnosticConsumer interface.
677e5dd7070Spatrick 
BeginSourceFile(const LangOptions & LangOpts,const Preprocessor * PP)678e5dd7070Spatrick void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts,
679e5dd7070Spatrick                                                const Preprocessor *PP) {
680e5dd7070Spatrick   // Attach comment handler on first invocation.
681e5dd7070Spatrick   if (++ActiveSourceFiles == 1) {
682e5dd7070Spatrick     if (PP) {
683e5dd7070Spatrick       CurrentPreprocessor = PP;
684e5dd7070Spatrick       this->LangOpts = &LangOpts;
685e5dd7070Spatrick       setSourceManager(PP->getSourceManager());
686e5dd7070Spatrick       const_cast<Preprocessor *>(PP)->addCommentHandler(this);
687e5dd7070Spatrick #ifndef NDEBUG
688e5dd7070Spatrick       // Debug build tracks parsed files.
689e5dd7070Spatrick       const_cast<Preprocessor *>(PP)->addPPCallbacks(
690e5dd7070Spatrick                       std::make_unique<VerifyFileTracker>(*this, *SrcManager));
691e5dd7070Spatrick #endif
692e5dd7070Spatrick     }
693e5dd7070Spatrick   }
694e5dd7070Spatrick 
695e5dd7070Spatrick   assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!");
696e5dd7070Spatrick   PrimaryClient->BeginSourceFile(LangOpts, PP);
697e5dd7070Spatrick }
698e5dd7070Spatrick 
EndSourceFile()699e5dd7070Spatrick void VerifyDiagnosticConsumer::EndSourceFile() {
700e5dd7070Spatrick   assert(ActiveSourceFiles && "No active source files!");
701e5dd7070Spatrick   PrimaryClient->EndSourceFile();
702e5dd7070Spatrick 
703e5dd7070Spatrick   // Detach comment handler once last active source file completed.
704e5dd7070Spatrick   if (--ActiveSourceFiles == 0) {
705e5dd7070Spatrick     if (CurrentPreprocessor)
706e5dd7070Spatrick       const_cast<Preprocessor *>(CurrentPreprocessor)->
707e5dd7070Spatrick           removeCommentHandler(this);
708e5dd7070Spatrick 
709e5dd7070Spatrick     // Diagnose any used-but-not-defined markers.
710e5dd7070Spatrick     Markers->finalize();
711e5dd7070Spatrick 
712e5dd7070Spatrick     // Check diagnostics once last file completed.
713e5dd7070Spatrick     CheckDiagnostics();
714e5dd7070Spatrick     CurrentPreprocessor = nullptr;
715e5dd7070Spatrick     LangOpts = nullptr;
716e5dd7070Spatrick   }
717e5dd7070Spatrick }
718e5dd7070Spatrick 
HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,const Diagnostic & Info)719e5dd7070Spatrick void VerifyDiagnosticConsumer::HandleDiagnostic(
720e5dd7070Spatrick       DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) {
721e5dd7070Spatrick   if (Info.hasSourceManager()) {
722e5dd7070Spatrick     // If this diagnostic is for a different source manager, ignore it.
723e5dd7070Spatrick     if (SrcManager && &Info.getSourceManager() != SrcManager)
724e5dd7070Spatrick       return;
725e5dd7070Spatrick 
726e5dd7070Spatrick     setSourceManager(Info.getSourceManager());
727e5dd7070Spatrick   }
728e5dd7070Spatrick 
729e5dd7070Spatrick #ifndef NDEBUG
730e5dd7070Spatrick   // Debug build tracks unparsed files for possible
731e5dd7070Spatrick   // unparsed expected-* directives.
732e5dd7070Spatrick   if (SrcManager) {
733e5dd7070Spatrick     SourceLocation Loc = Info.getLocation();
734e5dd7070Spatrick     if (Loc.isValid()) {
735e5dd7070Spatrick       ParsedStatus PS = IsUnparsed;
736e5dd7070Spatrick 
737e5dd7070Spatrick       Loc = SrcManager->getExpansionLoc(Loc);
738e5dd7070Spatrick       FileID FID = SrcManager->getFileID(Loc);
739e5dd7070Spatrick 
740e5dd7070Spatrick       const FileEntry *FE = SrcManager->getFileEntryForID(FID);
741e5dd7070Spatrick       if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) {
742e5dd7070Spatrick         // If the file is a modules header file it shall not be parsed
743e5dd7070Spatrick         // for expected-* directives.
744e5dd7070Spatrick         HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo();
745e5dd7070Spatrick         if (HS.findModuleForHeader(FE))
746e5dd7070Spatrick           PS = IsUnparsedNoDirectives;
747e5dd7070Spatrick       }
748e5dd7070Spatrick 
749e5dd7070Spatrick       UpdateParsedFileStatus(*SrcManager, FID, PS);
750e5dd7070Spatrick     }
751e5dd7070Spatrick   }
752e5dd7070Spatrick #endif
753e5dd7070Spatrick 
754e5dd7070Spatrick   // Send the diagnostic to the buffer, we will check it once we reach the end
755e5dd7070Spatrick   // of the source file (or are destructed).
756e5dd7070Spatrick   Buffer->HandleDiagnostic(DiagLevel, Info);
757e5dd7070Spatrick }
758e5dd7070Spatrick 
759e5dd7070Spatrick /// HandleComment - Hook into the preprocessor and extract comments containing
760e5dd7070Spatrick ///  expected errors and warnings.
HandleComment(Preprocessor & PP,SourceRange Comment)761e5dd7070Spatrick bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP,
762e5dd7070Spatrick                                              SourceRange Comment) {
763e5dd7070Spatrick   SourceManager &SM = PP.getSourceManager();
764e5dd7070Spatrick 
765e5dd7070Spatrick   // If this comment is for a different source manager, ignore it.
766e5dd7070Spatrick   if (SrcManager && &SM != SrcManager)
767e5dd7070Spatrick     return false;
768e5dd7070Spatrick 
769e5dd7070Spatrick   SourceLocation CommentBegin = Comment.getBegin();
770e5dd7070Spatrick 
771e5dd7070Spatrick   const char *CommentRaw = SM.getCharacterData(CommentBegin);
772e5dd7070Spatrick   StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw);
773e5dd7070Spatrick 
774e5dd7070Spatrick   if (C.empty())
775e5dd7070Spatrick     return false;
776e5dd7070Spatrick 
777e5dd7070Spatrick   // Fold any "\<EOL>" sequences
778e5dd7070Spatrick   size_t loc = C.find('\\');
779e5dd7070Spatrick   if (loc == StringRef::npos) {
780e5dd7070Spatrick     ParseDirective(C, &ED, SM, &PP, CommentBegin, Status, *Markers);
781e5dd7070Spatrick     return false;
782e5dd7070Spatrick   }
783e5dd7070Spatrick 
784e5dd7070Spatrick   std::string C2;
785e5dd7070Spatrick   C2.reserve(C.size());
786e5dd7070Spatrick 
787e5dd7070Spatrick   for (size_t last = 0;; loc = C.find('\\', last)) {
788e5dd7070Spatrick     if (loc == StringRef::npos || loc == C.size()) {
789e5dd7070Spatrick       C2 += C.substr(last);
790e5dd7070Spatrick       break;
791e5dd7070Spatrick     }
792e5dd7070Spatrick     C2 += C.substr(last, loc-last);
793e5dd7070Spatrick     last = loc + 1;
794e5dd7070Spatrick 
795e5dd7070Spatrick     if (C[last] == '\n' || C[last] == '\r') {
796e5dd7070Spatrick       ++last;
797e5dd7070Spatrick 
798e5dd7070Spatrick       // Escape \r\n  or \n\r, but not \n\n.
799e5dd7070Spatrick       if (last < C.size())
800e5dd7070Spatrick         if (C[last] == '\n' || C[last] == '\r')
801e5dd7070Spatrick           if (C[last] != C[last-1])
802e5dd7070Spatrick             ++last;
803e5dd7070Spatrick     } else {
804e5dd7070Spatrick       // This was just a normal backslash.
805e5dd7070Spatrick       C2 += '\\';
806e5dd7070Spatrick     }
807e5dd7070Spatrick   }
808e5dd7070Spatrick 
809e5dd7070Spatrick   if (!C2.empty())
810e5dd7070Spatrick     ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status, *Markers);
811e5dd7070Spatrick   return false;
812e5dd7070Spatrick }
813e5dd7070Spatrick 
814e5dd7070Spatrick #ifndef NDEBUG
815e5dd7070Spatrick /// Lex the specified source file to determine whether it contains
816e5dd7070Spatrick /// any expected-* directives.  As a Lexer is used rather than a full-blown
817e5dd7070Spatrick /// Preprocessor, directives inside skipped #if blocks will still be found.
818e5dd7070Spatrick ///
819e5dd7070Spatrick /// \return true if any directives were found.
findDirectives(SourceManager & SM,FileID FID,const LangOptions & LangOpts)820e5dd7070Spatrick static bool findDirectives(SourceManager &SM, FileID FID,
821e5dd7070Spatrick                            const LangOptions &LangOpts) {
822e5dd7070Spatrick   // Create a raw lexer to pull all the comments out of FID.
823e5dd7070Spatrick   if (FID.isInvalid())
824e5dd7070Spatrick     return false;
825e5dd7070Spatrick 
826e5dd7070Spatrick   // Create a lexer to lex all the tokens of the main file in raw mode.
827a9ac8606Spatrick   llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID);
828e5dd7070Spatrick   Lexer RawLex(FID, FromFile, SM, LangOpts);
829e5dd7070Spatrick 
830e5dd7070Spatrick   // Return comments as tokens, this is how we find expected diagnostics.
831e5dd7070Spatrick   RawLex.SetCommentRetentionState(true);
832e5dd7070Spatrick 
833e5dd7070Spatrick   Token Tok;
834e5dd7070Spatrick   Tok.setKind(tok::comment);
835e5dd7070Spatrick   VerifyDiagnosticConsumer::DirectiveStatus Status =
836e5dd7070Spatrick     VerifyDiagnosticConsumer::HasNoDirectives;
837e5dd7070Spatrick   while (Tok.isNot(tok::eof)) {
838e5dd7070Spatrick     RawLex.LexFromRawLexer(Tok);
839e5dd7070Spatrick     if (!Tok.is(tok::comment)) continue;
840e5dd7070Spatrick 
841e5dd7070Spatrick     std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts);
842e5dd7070Spatrick     if (Comment.empty()) continue;
843e5dd7070Spatrick 
844e5dd7070Spatrick     // We don't care about tracking markers for this phase.
845e5dd7070Spatrick     VerifyDiagnosticConsumer::MarkerTracker Markers(SM.getDiagnostics());
846e5dd7070Spatrick 
847e5dd7070Spatrick     // Find first directive.
848e5dd7070Spatrick     if (ParseDirective(Comment, nullptr, SM, nullptr, Tok.getLocation(),
849e5dd7070Spatrick                        Status, Markers))
850e5dd7070Spatrick       return true;
851e5dd7070Spatrick   }
852e5dd7070Spatrick   return false;
853e5dd7070Spatrick }
854e5dd7070Spatrick #endif // !NDEBUG
855e5dd7070Spatrick 
856e5dd7070Spatrick /// Takes a list of diagnostics that have been generated but not matched
857e5dd7070Spatrick /// by an expected-* directive and produces a diagnostic to the user from this.
PrintUnexpected(DiagnosticsEngine & Diags,SourceManager * SourceMgr,const_diag_iterator diag_begin,const_diag_iterator diag_end,const char * Kind)858e5dd7070Spatrick static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr,
859e5dd7070Spatrick                                 const_diag_iterator diag_begin,
860e5dd7070Spatrick                                 const_diag_iterator diag_end,
861e5dd7070Spatrick                                 const char *Kind) {
862e5dd7070Spatrick   if (diag_begin == diag_end) return 0;
863e5dd7070Spatrick 
864e5dd7070Spatrick   SmallString<256> Fmt;
865e5dd7070Spatrick   llvm::raw_svector_ostream OS(Fmt);
866e5dd7070Spatrick   for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) {
867e5dd7070Spatrick     if (I->first.isInvalid() || !SourceMgr)
868e5dd7070Spatrick       OS << "\n  (frontend)";
869e5dd7070Spatrick     else {
870e5dd7070Spatrick       OS << "\n ";
871e5dd7070Spatrick       if (const FileEntry *File = SourceMgr->getFileEntryForID(
872e5dd7070Spatrick                                                 SourceMgr->getFileID(I->first)))
873e5dd7070Spatrick         OS << " File " << File->getName();
874e5dd7070Spatrick       OS << " Line " << SourceMgr->getPresumedLineNumber(I->first);
875e5dd7070Spatrick     }
876e5dd7070Spatrick     OS << ": " << I->second;
877e5dd7070Spatrick   }
878e5dd7070Spatrick 
879e5dd7070Spatrick   Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
880e5dd7070Spatrick     << Kind << /*Unexpected=*/true << OS.str();
881e5dd7070Spatrick   return std::distance(diag_begin, diag_end);
882e5dd7070Spatrick }
883e5dd7070Spatrick 
884e5dd7070Spatrick /// Takes a list of diagnostics that were expected to have been generated
885e5dd7070Spatrick /// but were not and produces a diagnostic to the user from this.
PrintExpected(DiagnosticsEngine & Diags,SourceManager & SourceMgr,std::vector<Directive * > & DL,const char * Kind)886e5dd7070Spatrick static unsigned PrintExpected(DiagnosticsEngine &Diags,
887e5dd7070Spatrick                               SourceManager &SourceMgr,
888e5dd7070Spatrick                               std::vector<Directive *> &DL, const char *Kind) {
889e5dd7070Spatrick   if (DL.empty())
890e5dd7070Spatrick     return 0;
891e5dd7070Spatrick 
892e5dd7070Spatrick   SmallString<256> Fmt;
893e5dd7070Spatrick   llvm::raw_svector_ostream OS(Fmt);
894e5dd7070Spatrick   for (const auto *D : DL) {
895ec727ea7Spatrick     if (D->DiagnosticLoc.isInvalid() || D->MatchAnyFileAndLine)
896e5dd7070Spatrick       OS << "\n  File *";
897e5dd7070Spatrick     else
898e5dd7070Spatrick       OS << "\n  File " << SourceMgr.getFilename(D->DiagnosticLoc);
899e5dd7070Spatrick     if (D->MatchAnyLine)
900e5dd7070Spatrick       OS << " Line *";
901e5dd7070Spatrick     else
902e5dd7070Spatrick       OS << " Line " << SourceMgr.getPresumedLineNumber(D->DiagnosticLoc);
903e5dd7070Spatrick     if (D->DirectiveLoc != D->DiagnosticLoc)
904e5dd7070Spatrick       OS << " (directive at "
905e5dd7070Spatrick          << SourceMgr.getFilename(D->DirectiveLoc) << ':'
906e5dd7070Spatrick          << SourceMgr.getPresumedLineNumber(D->DirectiveLoc) << ')';
907e5dd7070Spatrick     OS << ": " << D->Text;
908e5dd7070Spatrick   }
909e5dd7070Spatrick 
910e5dd7070Spatrick   Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit()
911e5dd7070Spatrick     << Kind << /*Unexpected=*/false << OS.str();
912e5dd7070Spatrick   return DL.size();
913e5dd7070Spatrick }
914e5dd7070Spatrick 
915e5dd7070Spatrick /// Determine whether two source locations come from the same file.
IsFromSameFile(SourceManager & SM,SourceLocation DirectiveLoc,SourceLocation DiagnosticLoc)916e5dd7070Spatrick static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc,
917e5dd7070Spatrick                            SourceLocation DiagnosticLoc) {
918e5dd7070Spatrick   while (DiagnosticLoc.isMacroID())
919e5dd7070Spatrick     DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc);
920e5dd7070Spatrick 
921e5dd7070Spatrick   if (SM.isWrittenInSameFile(DirectiveLoc, DiagnosticLoc))
922e5dd7070Spatrick     return true;
923e5dd7070Spatrick 
924e5dd7070Spatrick   const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc));
925e5dd7070Spatrick   if (!DiagFile && SM.isWrittenInMainFile(DirectiveLoc))
926e5dd7070Spatrick     return true;
927e5dd7070Spatrick 
928e5dd7070Spatrick   return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc)));
929e5dd7070Spatrick }
930e5dd7070Spatrick 
931e5dd7070Spatrick /// CheckLists - Compare expected to seen diagnostic lists and return the
932e5dd7070Spatrick /// the difference between them.
CheckLists(DiagnosticsEngine & Diags,SourceManager & SourceMgr,const char * Label,DirectiveList & Left,const_diag_iterator d2_begin,const_diag_iterator d2_end,bool IgnoreUnexpected)933e5dd7070Spatrick static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
934e5dd7070Spatrick                            const char *Label,
935e5dd7070Spatrick                            DirectiveList &Left,
936e5dd7070Spatrick                            const_diag_iterator d2_begin,
937e5dd7070Spatrick                            const_diag_iterator d2_end,
938e5dd7070Spatrick                            bool IgnoreUnexpected) {
939e5dd7070Spatrick   std::vector<Directive *> LeftOnly;
940e5dd7070Spatrick   DiagList Right(d2_begin, d2_end);
941e5dd7070Spatrick 
942e5dd7070Spatrick   for (auto &Owner : Left) {
943e5dd7070Spatrick     Directive &D = *Owner;
944e5dd7070Spatrick     unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc);
945e5dd7070Spatrick 
946e5dd7070Spatrick     for (unsigned i = 0; i < D.Max; ++i) {
947e5dd7070Spatrick       DiagList::iterator II, IE;
948e5dd7070Spatrick       for (II = Right.begin(), IE = Right.end(); II != IE; ++II) {
949e5dd7070Spatrick         if (!D.MatchAnyLine) {
950e5dd7070Spatrick           unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first);
951e5dd7070Spatrick           if (LineNo1 != LineNo2)
952e5dd7070Spatrick             continue;
953e5dd7070Spatrick         }
954e5dd7070Spatrick 
955ec727ea7Spatrick         if (!D.DiagnosticLoc.isInvalid() && !D.MatchAnyFileAndLine &&
956e5dd7070Spatrick             !IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first))
957e5dd7070Spatrick           continue;
958e5dd7070Spatrick 
959e5dd7070Spatrick         const std::string &RightText = II->second;
960e5dd7070Spatrick         if (D.match(RightText))
961e5dd7070Spatrick           break;
962e5dd7070Spatrick       }
963e5dd7070Spatrick       if (II == IE) {
964e5dd7070Spatrick         // Not found.
965e5dd7070Spatrick         if (i >= D.Min) break;
966e5dd7070Spatrick         LeftOnly.push_back(&D);
967e5dd7070Spatrick       } else {
968e5dd7070Spatrick         // Found. The same cannot be found twice.
969e5dd7070Spatrick         Right.erase(II);
970e5dd7070Spatrick       }
971e5dd7070Spatrick     }
972e5dd7070Spatrick   }
973e5dd7070Spatrick   // Now all that's left in Right are those that were not matched.
974e5dd7070Spatrick   unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label);
975e5dd7070Spatrick   if (!IgnoreUnexpected)
976e5dd7070Spatrick     num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label);
977e5dd7070Spatrick   return num;
978e5dd7070Spatrick }
979e5dd7070Spatrick 
980e5dd7070Spatrick /// CheckResults - This compares the expected results to those that
981e5dd7070Spatrick /// were actually reported. It emits any discrepencies. Return "true" if there
982e5dd7070Spatrick /// were problems. Return "false" otherwise.
CheckResults(DiagnosticsEngine & Diags,SourceManager & SourceMgr,const TextDiagnosticBuffer & Buffer,ExpectedData & ED)983e5dd7070Spatrick static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr,
984e5dd7070Spatrick                              const TextDiagnosticBuffer &Buffer,
985e5dd7070Spatrick                              ExpectedData &ED) {
986e5dd7070Spatrick   // We want to capture the delta between what was expected and what was
987e5dd7070Spatrick   // seen.
988e5dd7070Spatrick   //
989e5dd7070Spatrick   //   Expected \ Seen - set expected but not seen
990e5dd7070Spatrick   //   Seen \ Expected - set seen but not expected
991e5dd7070Spatrick   unsigned NumProblems = 0;
992e5dd7070Spatrick 
993e5dd7070Spatrick   const DiagnosticLevelMask DiagMask =
994e5dd7070Spatrick     Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
995e5dd7070Spatrick 
996e5dd7070Spatrick   // See if there are error mismatches.
997e5dd7070Spatrick   NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors,
998e5dd7070Spatrick                             Buffer.err_begin(), Buffer.err_end(),
999e5dd7070Spatrick                             bool(DiagnosticLevelMask::Error & DiagMask));
1000e5dd7070Spatrick 
1001e5dd7070Spatrick   // See if there are warning mismatches.
1002e5dd7070Spatrick   NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings,
1003e5dd7070Spatrick                             Buffer.warn_begin(), Buffer.warn_end(),
1004e5dd7070Spatrick                             bool(DiagnosticLevelMask::Warning & DiagMask));
1005e5dd7070Spatrick 
1006e5dd7070Spatrick   // See if there are remark mismatches.
1007e5dd7070Spatrick   NumProblems += CheckLists(Diags, SourceMgr, "remark", ED.Remarks,
1008e5dd7070Spatrick                             Buffer.remark_begin(), Buffer.remark_end(),
1009e5dd7070Spatrick                             bool(DiagnosticLevelMask::Remark & DiagMask));
1010e5dd7070Spatrick 
1011e5dd7070Spatrick   // See if there are note mismatches.
1012e5dd7070Spatrick   NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes,
1013e5dd7070Spatrick                             Buffer.note_begin(), Buffer.note_end(),
1014e5dd7070Spatrick                             bool(DiagnosticLevelMask::Note & DiagMask));
1015e5dd7070Spatrick 
1016e5dd7070Spatrick   return NumProblems;
1017e5dd7070Spatrick }
1018e5dd7070Spatrick 
UpdateParsedFileStatus(SourceManager & SM,FileID FID,ParsedStatus PS)1019e5dd7070Spatrick void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM,
1020e5dd7070Spatrick                                                       FileID FID,
1021e5dd7070Spatrick                                                       ParsedStatus PS) {
1022e5dd7070Spatrick   // Check SourceManager hasn't changed.
1023e5dd7070Spatrick   setSourceManager(SM);
1024e5dd7070Spatrick 
1025e5dd7070Spatrick #ifndef NDEBUG
1026e5dd7070Spatrick   if (FID.isInvalid())
1027e5dd7070Spatrick     return;
1028e5dd7070Spatrick 
1029e5dd7070Spatrick   const FileEntry *FE = SM.getFileEntryForID(FID);
1030e5dd7070Spatrick 
1031e5dd7070Spatrick   if (PS == IsParsed) {
1032e5dd7070Spatrick     // Move the FileID from the unparsed set to the parsed set.
1033e5dd7070Spatrick     UnparsedFiles.erase(FID);
1034e5dd7070Spatrick     ParsedFiles.insert(std::make_pair(FID, FE));
1035e5dd7070Spatrick   } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) {
1036e5dd7070Spatrick     // Add the FileID to the unparsed set if we haven't seen it before.
1037e5dd7070Spatrick 
1038e5dd7070Spatrick     // Check for directives.
1039e5dd7070Spatrick     bool FoundDirectives;
1040e5dd7070Spatrick     if (PS == IsUnparsedNoDirectives)
1041e5dd7070Spatrick       FoundDirectives = false;
1042e5dd7070Spatrick     else
1043e5dd7070Spatrick       FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts);
1044e5dd7070Spatrick 
1045e5dd7070Spatrick     // Add the FileID to the unparsed set.
1046e5dd7070Spatrick     UnparsedFiles.insert(std::make_pair(FID,
1047e5dd7070Spatrick                                       UnparsedFileStatus(FE, FoundDirectives)));
1048e5dd7070Spatrick   }
1049e5dd7070Spatrick #endif
1050e5dd7070Spatrick }
1051e5dd7070Spatrick 
CheckDiagnostics()1052e5dd7070Spatrick void VerifyDiagnosticConsumer::CheckDiagnostics() {
1053e5dd7070Spatrick   // Ensure any diagnostics go to the primary client.
1054e5dd7070Spatrick   DiagnosticConsumer *CurClient = Diags.getClient();
1055e5dd7070Spatrick   std::unique_ptr<DiagnosticConsumer> Owner = Diags.takeClient();
1056e5dd7070Spatrick   Diags.setClient(PrimaryClient, false);
1057e5dd7070Spatrick 
1058e5dd7070Spatrick #ifndef NDEBUG
1059e5dd7070Spatrick   // In a debug build, scan through any files that may have been missed
1060e5dd7070Spatrick   // during parsing and issue a fatal error if directives are contained
1061e5dd7070Spatrick   // within these files.  If a fatal error occurs, this suggests that
1062e5dd7070Spatrick   // this file is being parsed separately from the main file, in which
1063e5dd7070Spatrick   // case consider moving the directives to the correct place, if this
1064e5dd7070Spatrick   // is applicable.
1065e5dd7070Spatrick   if (!UnparsedFiles.empty()) {
1066e5dd7070Spatrick     // Generate a cache of parsed FileEntry pointers for alias lookups.
1067e5dd7070Spatrick     llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache;
1068e5dd7070Spatrick     for (const auto &I : ParsedFiles)
1069e5dd7070Spatrick       if (const FileEntry *FE = I.second)
1070e5dd7070Spatrick         ParsedFileCache.insert(FE);
1071e5dd7070Spatrick 
1072e5dd7070Spatrick     // Iterate through list of unparsed files.
1073e5dd7070Spatrick     for (const auto &I : UnparsedFiles) {
1074e5dd7070Spatrick       const UnparsedFileStatus &Status = I.second;
1075e5dd7070Spatrick       const FileEntry *FE = Status.getFile();
1076e5dd7070Spatrick 
1077e5dd7070Spatrick       // Skip files that have been parsed via an alias.
1078e5dd7070Spatrick       if (FE && ParsedFileCache.count(FE))
1079e5dd7070Spatrick         continue;
1080e5dd7070Spatrick 
1081e5dd7070Spatrick       // Report a fatal error if this file contained directives.
1082e5dd7070Spatrick       if (Status.foundDirectives()) {
1083e5dd7070Spatrick         llvm::report_fatal_error(Twine("-verify directives found after rather"
1084e5dd7070Spatrick                                        " than during normal parsing of ",
1085e5dd7070Spatrick                                  StringRef(FE ? FE->getName() : "(unknown)")));
1086e5dd7070Spatrick       }
1087e5dd7070Spatrick     }
1088e5dd7070Spatrick 
1089e5dd7070Spatrick     // UnparsedFiles has been processed now, so clear it.
1090e5dd7070Spatrick     UnparsedFiles.clear();
1091e5dd7070Spatrick   }
1092e5dd7070Spatrick #endif // !NDEBUG
1093e5dd7070Spatrick 
1094e5dd7070Spatrick   if (SrcManager) {
1095e5dd7070Spatrick     // Produce an error if no expected-* directives could be found in the
1096e5dd7070Spatrick     // source file(s) processed.
1097e5dd7070Spatrick     if (Status == HasNoDirectives) {
1098e5dd7070Spatrick       Diags.Report(diag::err_verify_no_directives).setForceEmit();
1099e5dd7070Spatrick       ++NumErrors;
1100e5dd7070Spatrick       Status = HasNoDirectivesReported;
1101e5dd7070Spatrick     }
1102e5dd7070Spatrick 
1103e5dd7070Spatrick     // Check that the expected diagnostics occurred.
1104e5dd7070Spatrick     NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED);
1105e5dd7070Spatrick   } else {
1106e5dd7070Spatrick     const DiagnosticLevelMask DiagMask =
1107e5dd7070Spatrick         ~Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected();
1108e5dd7070Spatrick     if (bool(DiagnosticLevelMask::Error & DiagMask))
1109e5dd7070Spatrick       NumErrors += PrintUnexpected(Diags, nullptr, Buffer->err_begin(),
1110e5dd7070Spatrick                                    Buffer->err_end(), "error");
1111e5dd7070Spatrick     if (bool(DiagnosticLevelMask::Warning & DiagMask))
1112e5dd7070Spatrick       NumErrors += PrintUnexpected(Diags, nullptr, Buffer->warn_begin(),
1113e5dd7070Spatrick                                    Buffer->warn_end(), "warn");
1114e5dd7070Spatrick     if (bool(DiagnosticLevelMask::Remark & DiagMask))
1115e5dd7070Spatrick       NumErrors += PrintUnexpected(Diags, nullptr, Buffer->remark_begin(),
1116e5dd7070Spatrick                                    Buffer->remark_end(), "remark");
1117e5dd7070Spatrick     if (bool(DiagnosticLevelMask::Note & DiagMask))
1118e5dd7070Spatrick       NumErrors += PrintUnexpected(Diags, nullptr, Buffer->note_begin(),
1119e5dd7070Spatrick                                    Buffer->note_end(), "note");
1120e5dd7070Spatrick   }
1121e5dd7070Spatrick 
1122e5dd7070Spatrick   Diags.setClient(CurClient, Owner.release() != nullptr);
1123e5dd7070Spatrick 
1124e5dd7070Spatrick   // Reset the buffer, we have processed all the diagnostics in it.
1125e5dd7070Spatrick   Buffer.reset(new TextDiagnosticBuffer());
1126e5dd7070Spatrick   ED.Reset();
1127e5dd7070Spatrick }
1128e5dd7070Spatrick 
create(bool RegexKind,SourceLocation DirectiveLoc,SourceLocation DiagnosticLoc,bool MatchAnyFileAndLine,bool MatchAnyLine,StringRef Text,unsigned Min,unsigned Max)1129e5dd7070Spatrick std::unique_ptr<Directive> Directive::create(bool RegexKind,
1130e5dd7070Spatrick                                              SourceLocation DirectiveLoc,
1131e5dd7070Spatrick                                              SourceLocation DiagnosticLoc,
1132ec727ea7Spatrick                                              bool MatchAnyFileAndLine,
1133e5dd7070Spatrick                                              bool MatchAnyLine, StringRef Text,
1134e5dd7070Spatrick                                              unsigned Min, unsigned Max) {
1135e5dd7070Spatrick   if (!RegexKind)
1136e5dd7070Spatrick     return std::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc,
1137ec727ea7Spatrick                                                MatchAnyFileAndLine,
1138e5dd7070Spatrick                                                MatchAnyLine, Text, Min, Max);
1139e5dd7070Spatrick 
1140e5dd7070Spatrick   // Parse the directive into a regular expression.
1141e5dd7070Spatrick   std::string RegexStr;
1142e5dd7070Spatrick   StringRef S = Text;
1143e5dd7070Spatrick   while (!S.empty()) {
1144e5dd7070Spatrick     if (S.startswith("{{")) {
1145e5dd7070Spatrick       S = S.drop_front(2);
1146e5dd7070Spatrick       size_t RegexMatchLength = S.find("}}");
1147e5dd7070Spatrick       assert(RegexMatchLength != StringRef::npos);
1148e5dd7070Spatrick       // Append the regex, enclosed in parentheses.
1149e5dd7070Spatrick       RegexStr += "(";
1150e5dd7070Spatrick       RegexStr.append(S.data(), RegexMatchLength);
1151e5dd7070Spatrick       RegexStr += ")";
1152e5dd7070Spatrick       S = S.drop_front(RegexMatchLength + 2);
1153e5dd7070Spatrick     } else {
1154e5dd7070Spatrick       size_t VerbatimMatchLength = S.find("{{");
1155e5dd7070Spatrick       if (VerbatimMatchLength == StringRef::npos)
1156e5dd7070Spatrick         VerbatimMatchLength = S.size();
1157e5dd7070Spatrick       // Escape and append the fixed string.
1158e5dd7070Spatrick       RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength));
1159e5dd7070Spatrick       S = S.drop_front(VerbatimMatchLength);
1160e5dd7070Spatrick     }
1161e5dd7070Spatrick   }
1162e5dd7070Spatrick 
1163ec727ea7Spatrick   return std::make_unique<RegexDirective>(DirectiveLoc, DiagnosticLoc,
1164ec727ea7Spatrick                                           MatchAnyFileAndLine, MatchAnyLine,
1165ec727ea7Spatrick                                           Text, Min, Max, RegexStr);
1166e5dd7070Spatrick }
1167