]> Gitweb @ Texas Instruments - Open Source Git Repositories - git.TI.com/gitweb - opencl/llvm.git/blob - utils/FileCheck/FileCheck.cpp
change 'not' matching to use Pattern, move pattern parsing logic into
[opencl/llvm.git] / utils / FileCheck / FileCheck.cpp
1 //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // FileCheck does a line-by line check of a file that validates whether it
11 // contains the expected content.  This is useful for regression tests etc.
12 //
13 // This program exits with an error status of 2 on error, exit status of 0 if
14 // the file matched the expected contents, and exit status of 1 if it did not
15 // contain the expected contents.
16 //
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Support/CommandLine.h"
20 #include "llvm/Support/MemoryBuffer.h"
21 #include "llvm/Support/PrettyStackTrace.h"
22 #include "llvm/Support/SourceMgr.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/System/Signals.h"
25 using namespace llvm;
27 static cl::opt<std::string>
28 CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Required);
30 static cl::opt<std::string>
31 InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
32               cl::init("-"), cl::value_desc("filename"));
34 static cl::opt<std::string>
35 CheckPrefix("check-prefix", cl::init("CHECK"),
36             cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
38 static cl::opt<bool>
39 NoCanonicalizeWhiteSpace("strict-whitespace",
40               cl::desc("Do not treat all horizontal whitespace as equivalent"));
42 //===----------------------------------------------------------------------===//
43 // Pattern Handling Code.
44 //===----------------------------------------------------------------------===//
46 class Pattern {
47   /// Str - The string to match.
48   std::string Str;
49 public:
50   
51   Pattern() { }
52   
53   bool ParsePattern(StringRef PatternStr, SourceMgr &SM);
54   
55   /// Match - Match the pattern string against the input buffer Buffer.  This
56   /// returns the position that is matched or npos if there is no match.  If
57   /// there is a match, the size of the matched string is returned in MatchLen.
58   size_t Match(StringRef Buffer, size_t &MatchLen) const {
59     MatchLen = Str.size();
60     return Buffer.find(Str);
61   }
62   
63 private:
64   /// CanonicalizeCheckString - Replace all sequences of horizontal whitespace
65   /// in the check strings with a single space.
66   void CanonicalizeCheckString() {
67     for (unsigned C = 0; C != Str.size(); ++C) {
68       // If C is not a horizontal whitespace, skip it.
69       if (Str[C] != ' ' && Str[C] != '\t')
70         continue;
71       
72       // Replace the character with space, then remove any other space
73       // characters after it.
74       Str[C] = ' ';
75       
76       while (C+1 != Str.size() &&
77              (Str[C+1] == ' ' || Str[C+1] == '\t'))
78         Str.erase(Str.begin()+C+1);
79     }
80   }
81 };
83 bool Pattern::ParsePattern(StringRef PatternStr, SourceMgr &SM) {
84   // Ignore trailing whitespace.
85   while (!PatternStr.empty() &&
86          (PatternStr.back() == ' ' || PatternStr.back() == '\t'))
87     PatternStr = PatternStr.substr(0, PatternStr.size()-1);
88   
89   // Check that there is something on the line.
90   if (PatternStr.empty()) {
91     SM.PrintMessage(SMLoc::getFromPointer(PatternStr.data()),
92                     "found empty check string with prefix '"+CheckPrefix+":'",
93                     "error");
94     return true;
95   }
96   
97   Str = PatternStr.str();
98   
99   // Remove duplicate spaces in the check strings if requested.
100   if (!NoCanonicalizeWhiteSpace)
101     CanonicalizeCheckString();
102   
103   return false;
107 //===----------------------------------------------------------------------===//
108 // Check Strings.
109 //===----------------------------------------------------------------------===//
111 /// CheckString - This is a check that we found in the input file.
112 struct CheckString {
113   /// Pat - The pattern to match.
114   Pattern Pat;
115   
116   /// Loc - The location in the match file that the check string was specified.
117   SMLoc Loc;
118   
119   /// IsCheckNext - This is true if this is a CHECK-NEXT: directive (as opposed
120   /// to a CHECK: directive.
121   bool IsCheckNext;
122   
123   /// NotStrings - These are all of the strings that are disallowed from
124   /// occurring between this match string and the previous one (or start of
125   /// file).
126   std::vector<std::pair<SMLoc, Pattern> > NotStrings;
127   
128   CheckString(const Pattern &P, SMLoc L, bool isCheckNext)
129     : Pat(P), Loc(L), IsCheckNext(isCheckNext) {}
130 };
133 /// ReadCheckFile - Read the check file, which specifies the sequence of
134 /// expected strings.  The strings are added to the CheckStrings vector.
135 static bool ReadCheckFile(SourceMgr &SM,
136                           std::vector<CheckString> &CheckStrings) {
137   // Open the check file, and tell SourceMgr about it.
138   std::string ErrorStr;
139   MemoryBuffer *F =
140     MemoryBuffer::getFileOrSTDIN(CheckFilename.c_str(), &ErrorStr);
141   if (F == 0) {
142     errs() << "Could not open check file '" << CheckFilename << "': " 
143            << ErrorStr << '\n';
144     return true;
145   }
146   SM.AddNewSourceBuffer(F, SMLoc());
148   // Find all instances of CheckPrefix followed by : in the file.
149   StringRef Buffer = F->getBuffer();
151   std::vector<std::pair<SMLoc, Pattern> > NotMatches;
152   
153   while (1) {
154     // See if Prefix occurs in the memory buffer.
155     Buffer = Buffer.substr(Buffer.find(CheckPrefix));
156     
157     // If we didn't find a match, we're done.
158     if (Buffer.empty())
159       break;
160     
161     const char *CheckPrefixStart = Buffer.data();
162     
163     // When we find a check prefix, keep track of whether we find CHECK: or
164     // CHECK-NEXT:
165     bool IsCheckNext = false, IsCheckNot = false;
166     
167     // Verify that the : is present after the prefix.
168     if (Buffer[CheckPrefix.size()] == ':') {
169       Buffer = Buffer.substr(CheckPrefix.size()+1);
170     } else if (Buffer.size() > CheckPrefix.size()+6 &&
171                memcmp(Buffer.data()+CheckPrefix.size(), "-NEXT:", 6) == 0) {
172       Buffer = Buffer.substr(CheckPrefix.size()+7);
173       IsCheckNext = true;
174     } else if (Buffer.size() > CheckPrefix.size()+5 &&
175                memcmp(Buffer.data()+CheckPrefix.size(), "-NOT:", 5) == 0) {
176       Buffer = Buffer.substr(CheckPrefix.size()+6);
177       IsCheckNot = true;
178     } else {
179       Buffer = Buffer.substr(1);
180       continue;
181     }
182     
183     // Okay, we found the prefix, yay.  Remember the rest of the line, but
184     // ignore leading and trailing whitespace.
185     Buffer = Buffer.substr(Buffer.find_first_not_of(" \t"));
186     
187     // Scan ahead to the end of line.
188     size_t EOL = Buffer.find_first_of("\n\r");
190     // Parse the pattern.
191     Pattern P;
192     if (P.ParsePattern(Buffer.substr(0, EOL), SM))
193       return true;
194     
195     Buffer = Buffer.substr(EOL);
197     
198     // Verify that CHECK-NEXT lines have at least one CHECK line before them.
199     if (IsCheckNext && CheckStrings.empty()) {
200       SM.PrintMessage(SMLoc::getFromPointer(CheckPrefixStart),
201                       "found '"+CheckPrefix+"-NEXT:' without previous '"+
202                       CheckPrefix+ ": line", "error");
203       return true;
204     }
205     
206     // Handle CHECK-NOT.
207     if (IsCheckNot) {
208       NotMatches.push_back(std::make_pair(SMLoc::getFromPointer(Buffer.data()),
209                                           P));
210       continue;
211     }
212     
213     
214     // Okay, add the string we captured to the output vector and move on.
215     CheckStrings.push_back(CheckString(P,
216                                        SMLoc::getFromPointer(Buffer.data()),
217                                        IsCheckNext));
218     std::swap(NotMatches, CheckStrings.back().NotStrings);
219   }
220   
221   if (CheckStrings.empty()) {
222     errs() << "error: no check strings found with prefix '" << CheckPrefix
223            << ":'\n";
224     return true;
225   }
226   
227   if (!NotMatches.empty()) {
228     errs() << "error: '" << CheckPrefix
229            << "-NOT:' not supported after last check line.\n";
230     return true;
231   }
232   
233   return false;
236 /// CanonicalizeInputFile - Remove duplicate horizontal space from the specified
237 /// memory buffer, free it, and return a new one.
238 static MemoryBuffer *CanonicalizeInputFile(MemoryBuffer *MB) {
239   SmallVector<char, 16> NewFile;
240   NewFile.reserve(MB->getBufferSize());
241   
242   for (const char *Ptr = MB->getBufferStart(), *End = MB->getBufferEnd();
243        Ptr != End; ++Ptr) {
244     // If C is not a horizontal whitespace, skip it.
245     if (*Ptr != ' ' && *Ptr != '\t') {
246       NewFile.push_back(*Ptr);
247       continue;
248     }
249     
250     // Otherwise, add one space and advance over neighboring space.
251     NewFile.push_back(' ');
252     while (Ptr+1 != End &&
253            (Ptr[1] == ' ' || Ptr[1] == '\t'))
254       ++Ptr;
255   }
256   
257   // Free the old buffer and return a new one.
258   MemoryBuffer *MB2 =
259     MemoryBuffer::getMemBufferCopy(NewFile.data(), 
260                                    NewFile.data() + NewFile.size(),
261                                    MB->getBufferIdentifier());
263   delete MB;
264   return MB2;
268 static void PrintCheckFailed(const SourceMgr &SM, const CheckString &CheckStr,
269                              StringRef Buffer) {
270   // Otherwise, we have an error, emit an error message.
271   SM.PrintMessage(CheckStr.Loc, "expected string not found in input",
272                   "error");
273   
274   // Print the "scanning from here" line.  If the current position is at the
275   // end of a line, advance to the start of the next line.
276   Buffer = Buffer.substr(Buffer.find_first_not_of(" \t\n\r"));
277   
278   SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()), "scanning from here",
279                   "note");
282 /// CountNumNewlinesBetween - Count the number of newlines in the specified
283 /// range.
284 static unsigned CountNumNewlinesBetween(StringRef Range) {
285   unsigned NumNewLines = 0;
286   while (1) {
287     // Scan for newline.
288     Range = Range.substr(Range.find_first_of("\n\r"));
289     if (Range.empty()) return NumNewLines;
290     
291     ++NumNewLines;
292     
293     // Handle \n\r and \r\n as a single newline.
294     if (Range.size() > 1 &&
295         (Range[1] == '\n' || Range[1] == '\r') &&
296         (Range[0] != Range[1]))
297       Range = Range.substr(1);
298     Range = Range.substr(1);
299   }
302 int main(int argc, char **argv) {
303   sys::PrintStackTraceOnErrorSignal();
304   PrettyStackTraceProgram X(argc, argv);
305   cl::ParseCommandLineOptions(argc, argv);
307   SourceMgr SM;
308   
309   // Read the expected strings from the check file.
310   std::vector<CheckString> CheckStrings;
311   if (ReadCheckFile(SM, CheckStrings))
312     return 2;
314   // Open the file to check and add it to SourceMgr.
315   std::string ErrorStr;
316   MemoryBuffer *F =
317     MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), &ErrorStr);
318   if (F == 0) {
319     errs() << "Could not open input file '" << InputFilename << "': " 
320            << ErrorStr << '\n';
321     return true;
322   }
323   
324   // Remove duplicate spaces in the input file if requested.
325   if (!NoCanonicalizeWhiteSpace)
326     F = CanonicalizeInputFile(F);
327   
328   SM.AddNewSourceBuffer(F, SMLoc());
329   
330   // Check that we have all of the expected strings, in order, in the input
331   // file.
332   StringRef Buffer = F->getBuffer();
333   
334   const char *LastMatch = Buffer.data();
335   
336   for (unsigned StrNo = 0, e = CheckStrings.size(); StrNo != e; ++StrNo) {
337     const CheckString &CheckStr = CheckStrings[StrNo];
338     
339     StringRef SearchFrom = Buffer;
340     
341     // Find StrNo in the file.
342     size_t MatchLen = 0;
343     Buffer = Buffer.substr(CheckStr.Pat.Match(Buffer, MatchLen));
344     
345     // If we didn't find a match, reject the input.
346     if (Buffer.empty()) {
347       PrintCheckFailed(SM, CheckStr, SearchFrom);
348       return 1;
349     }
351     StringRef SkippedRegion(LastMatch, Buffer.data()-LastMatch);
353     // If this check is a "CHECK-NEXT", verify that the previous match was on
354     // the previous line (i.e. that there is one newline between them).
355     if (CheckStr.IsCheckNext) {
356       // Count the number of newlines between the previous match and this one.
357       assert(LastMatch != F->getBufferStart() &&
358              "CHECK-NEXT can't be the first check in a file");
360       unsigned NumNewLines = CountNumNewlinesBetween(SkippedRegion);
361       if (NumNewLines == 0) {
362         SM.PrintMessage(CheckStr.Loc,
363                     CheckPrefix+"-NEXT: is on the same line as previous match",
364                         "error");
365         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
366                         "'next' match was here", "note");
367         SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
368                         "previous match was here", "note");
369         return 1;
370       }
371       
372       if (NumNewLines != 1) {
373         SM.PrintMessage(CheckStr.Loc,
374                         CheckPrefix+
375                         "-NEXT: is not on the line after the previous match",
376                         "error");
377         SM.PrintMessage(SMLoc::getFromPointer(Buffer.data()),
378                         "'next' match was here", "note");
379         SM.PrintMessage(SMLoc::getFromPointer(LastMatch),
380                         "previous match was here", "note");
381         return 1;
382       }
383     }
384     
385     // If this match had "not strings", verify that they don't exist in the
386     // skipped region.
387     for (unsigned i = 0, e = CheckStr.NotStrings.size(); i != e; ++i) {
388       size_t MatchLen = 0;
389       size_t Pos = CheckStr.NotStrings[i].second.Match(SkippedRegion, MatchLen);
390       if (Pos == StringRef::npos) continue;
391      
392       SM.PrintMessage(SMLoc::getFromPointer(LastMatch+Pos),
393                       CheckPrefix+"-NOT: string occurred!", "error");
394       SM.PrintMessage(CheckStr.NotStrings[i].first,
395                       CheckPrefix+"-NOT: pattern specified here", "note");
396       return 1;
397     }
398     
400     // Otherwise, everything is good.  Step over the matched text and remember
401     // the position after the match as the end of the last match.
402     Buffer = Buffer.substr(MatchLen);
403     LastMatch = Buffer.data();
404   }
405   
406   return 0;