Coverage Report

Created: 2019-07-24 05:18

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