1ee3c74fbSChris Lattner //===- FileCheck.cpp - Check that File's Contents match what is expected --===//
2ee3c74fbSChris Lattner //
3ee3c74fbSChris Lattner //                     The LLVM Compiler Infrastructure
4ee3c74fbSChris Lattner //
5ee3c74fbSChris Lattner // This file is distributed under the University of Illinois Open Source
6ee3c74fbSChris Lattner // License. See LICENSE.TXT for details.
7ee3c74fbSChris Lattner //
8ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
9ee3c74fbSChris Lattner //
10ee3c74fbSChris Lattner // FileCheck does a line-by line check of a file that validates whether it
11ee3c74fbSChris Lattner // contains the expected content.  This is useful for regression tests etc.
12ee3c74fbSChris Lattner //
13b5ecceffSJames Henderson // This program exits with an exit status of 2 on error, exit status of 0 if
14ee3c74fbSChris Lattner // the file matched the expected contents, and exit status of 1 if it did not
15ee3c74fbSChris Lattner // contain the expected contents.
16ee3c74fbSChris Lattner //
17ee3c74fbSChris Lattner //===----------------------------------------------------------------------===//
18ee3c74fbSChris Lattner 
19ee3c74fbSChris Lattner #include "llvm/Support/CommandLine.h"
20197194b6SRui Ueyama #include "llvm/Support/InitLLVM.h"
213e66509fSJoel E. Denny #include "llvm/Support/Process.h"
223c5d267eSJoel E. Denny #include "llvm/Support/WithColor.h"
23ee3c74fbSChris Lattner #include "llvm/Support/raw_ostream.h"
24ffa9d2e4SAditya Nandakumar #include "llvm/Support/FileCheck.h"
25ee3c74fbSChris Lattner using namespace llvm;
26ee3c74fbSChris Lattner 
27ee3c74fbSChris Lattner static cl::opt<std::string>
283c5d267eSJoel E. Denny     CheckFilename(cl::Positional, cl::desc("<check-file>"), cl::Optional);
29ee3c74fbSChris Lattner 
30ee3c74fbSChris Lattner static cl::opt<std::string>
31ee3c74fbSChris Lattner     InputFilename("input-file", cl::desc("File to check (defaults to stdin)"),
32ee3c74fbSChris Lattner                   cl::init("-"), cl::value_desc("filename"));
33ee3c74fbSChris Lattner 
34e8f2fb20SChandler Carruth static cl::list<std::string> CheckPrefixes(
35e8f2fb20SChandler Carruth     "check-prefix",
36ee3c74fbSChris Lattner     cl::desc("Prefix to use from check file (defaults to 'CHECK')"));
37fd557cb0SDaniel Sanders static cl::alias CheckPrefixesAlias(
38fd557cb0SDaniel Sanders     "check-prefixes", cl::aliasopt(CheckPrefixes), cl::CommaSeparated,
39fd557cb0SDaniel Sanders     cl::NotHidden,
40fd557cb0SDaniel Sanders     cl::desc(
41fd557cb0SDaniel Sanders         "Alias for -check-prefix permitting multiple comma separated values"));
42ee3c74fbSChris Lattner 
43e8f2fb20SChandler Carruth static cl::opt<bool> NoCanonicalizeWhiteSpace(
44e8f2fb20SChandler Carruth     "strict-whitespace",
452c3e5cdfSChris Lattner     cl::desc("Do not treat all horizontal whitespace as equivalent"));
462c3e5cdfSChris Lattner 
4756ccdbbdSAlexander Kornienko static cl::list<std::string> ImplicitCheckNot(
4856ccdbbdSAlexander Kornienko     "implicit-check-not",
4956ccdbbdSAlexander Kornienko     cl::desc("Add an implicit negative check with this pattern to every\n"
5056ccdbbdSAlexander Kornienko              "positive check. This can be used to ensure that no instances of\n"
5156ccdbbdSAlexander Kornienko              "this pattern occur which are not matched by a positive pattern"),
5256ccdbbdSAlexander Kornienko     cl::value_desc("pattern"));
5356ccdbbdSAlexander Kornienko 
5446e1fd61SAlexander Richardson static cl::list<std::string> GlobalDefines("D", cl::Prefix,
5546e1fd61SAlexander Richardson     cl::desc("Define a variable to be used in capture patterns."),
5646e1fd61SAlexander Richardson     cl::value_desc("VAR=VALUE"));
5746e1fd61SAlexander Richardson 
581b9f936fSJustin Bogner static cl::opt<bool> AllowEmptyInput(
591b9f936fSJustin Bogner     "allow-empty", cl::init(false),
601b9f936fSJustin Bogner     cl::desc("Allow the input file to be empty. This is useful when making\n"
611b9f936fSJustin Bogner              "checks that some error message does not occur, for example."));
621b9f936fSJustin Bogner 
6385913ccaSJames Y Knight static cl::opt<bool> MatchFullLines(
6485913ccaSJames Y Knight     "match-full-lines", cl::init(false),
6585913ccaSJames Y Knight     cl::desc("Require all positive matches to cover an entire input line.\n"
6685913ccaSJames Y Knight              "Allows leading and trailing whitespace if --strict-whitespace\n"
6785913ccaSJames Y Knight              "is not also passed."));
6885913ccaSJames Y Knight 
69f55e72a5SArtem Belevich static cl::opt<bool> EnableVarScope(
70f55e72a5SArtem Belevich     "enable-var-scope", cl::init(false),
71f55e72a5SArtem Belevich     cl::desc("Enables scope for regex variables. Variables with names that\n"
72f55e72a5SArtem Belevich              "do not start with '$' will be reset at the beginning of\n"
73f55e72a5SArtem Belevich              "each CHECK-LABEL block."));
74f55e72a5SArtem Belevich 
75bcf5b441SJoel E. Denny static cl::opt<bool> AllowDeprecatedDagOverlap(
76bcf5b441SJoel E. Denny     "allow-deprecated-dag-overlap", cl::init(false),
77bcf5b441SJoel E. Denny     cl::desc("Enable overlapping among matches in a group of consecutive\n"
78bcf5b441SJoel E. Denny              "CHECK-DAG directives.  This option is deprecated and is only\n"
79bcf5b441SJoel E. Denny              "provided for convenience as old tests are migrated to the new\n"
80bcf5b441SJoel E. Denny              "non-overlapping CHECK-DAG implementation.\n"));
81bcf5b441SJoel E. Denny 
82dc5ba317SJoel E. Denny static cl::opt<bool> Verbose("v", cl::init(false),
83dc5ba317SJoel E. Denny                              cl::desc("Print directive pattern matches.\n"));
84dc5ba317SJoel E. Denny 
85dc5ba317SJoel E. Denny static cl::opt<bool> VerboseVerbose(
86dc5ba317SJoel E. Denny     "vv", cl::init(false),
87dc5ba317SJoel E. Denny     cl::desc("Print information helpful in diagnosing internal FileCheck\n"
88dc5ba317SJoel E. Denny              "issues.  Implies -v.\n"));
89346dfbe2SGeorge Karpenkov static const char * DumpInputEnv = "FILECHECK_DUMP_INPUT_ON_FAILURE";
90346dfbe2SGeorge Karpenkov 
91346dfbe2SGeorge Karpenkov static cl::opt<bool> DumpInputOnFailure(
92346dfbe2SGeorge Karpenkov     "dump-input-on-failure", cl::init(std::getenv(DumpInputEnv)),
93346dfbe2SGeorge Karpenkov     cl::desc("Dump original input to stderr before failing.\n"
94346dfbe2SGeorge Karpenkov              "The value can be also controlled using\n"
953c5d267eSJoel E. Denny              "FILECHECK_DUMP_INPUT_ON_FAILURE environment variable.\n"
963c5d267eSJoel E. Denny              "This option is deprecated in favor of -dump-input=fail.\n"));
973c5d267eSJoel E. Denny 
983c5d267eSJoel E. Denny enum DumpInputValue {
993c5d267eSJoel E. Denny   DumpInputDefault,
1003c5d267eSJoel E. Denny   DumpInputHelp,
1013c5d267eSJoel E. Denny   DumpInputNever,
1023c5d267eSJoel E. Denny   DumpInputFail,
1033c5d267eSJoel E. Denny   DumpInputAlways
1043c5d267eSJoel E. Denny };
1053c5d267eSJoel E. Denny 
1063c5d267eSJoel E. Denny static cl::opt<DumpInputValue> DumpInput(
1073c5d267eSJoel E. Denny     "dump-input", cl::init(DumpInputDefault),
1083c5d267eSJoel E. Denny     cl::desc("Dump input to stderr, adding annotations representing\n"
1093c5d267eSJoel E. Denny              " currently enabled diagnostics\n"),
1103c5d267eSJoel E. Denny     cl::value_desc("mode"),
1113c5d267eSJoel E. Denny     cl::values(clEnumValN(DumpInputHelp, "help",
1123c5d267eSJoel E. Denny                           "Explain dump format and quit"),
1133c5d267eSJoel E. Denny                clEnumValN(DumpInputNever, "never", "Never dump input"),
1143c5d267eSJoel E. Denny                clEnumValN(DumpInputFail, "fail", "Dump input on failure"),
1153c5d267eSJoel E. Denny                clEnumValN(DumpInputAlways, "always", "Always dump input")));
116dc5ba317SJoel E. Denny 
11713df4626SMatt Arsenault typedef cl::list<std::string>::const_iterator prefix_iterator;
11813df4626SMatt Arsenault 
11913df4626SMatt Arsenault 
12013df4626SMatt Arsenault 
121726774cbSChandler Carruth 
122726774cbSChandler Carruth 
123726774cbSChandler Carruth 
124c2735158SRui Ueyama 
1252bd4f8b6SXinliang David Li static void DumpCommandLine(int argc, char **argv) {
1262bd4f8b6SXinliang David Li   errs() << "FileCheck command line: ";
1272bd4f8b6SXinliang David Li   for (int I = 0; I < argc; I++)
1282bd4f8b6SXinliang David Li     errs() << " " << argv[I];
1292bd4f8b6SXinliang David Li   errs() << "\n";
1302bd4f8b6SXinliang David Li }
1312bd4f8b6SXinliang David Li 
1323c5d267eSJoel E. Denny struct MarkerStyle {
1333c5d267eSJoel E. Denny   /// The starting char (before tildes) for marking the line.
1343c5d267eSJoel E. Denny   char Lead;
1353c5d267eSJoel E. Denny   /// What color to use for this annotation.
1363c5d267eSJoel E. Denny   raw_ostream::Colors Color;
1373c5d267eSJoel E. Denny   /// A note to follow the marker, or empty string if none.
1383c5d267eSJoel E. Denny   std::string Note;
1393c5d267eSJoel E. Denny   MarkerStyle() {}
140*7df86967SJoel E. Denny   MarkerStyle(char Lead, raw_ostream::Colors Color,
141*7df86967SJoel E. Denny               const std::string &Note = "")
1423c5d267eSJoel E. Denny       : Lead(Lead), Color(Color), Note(Note) {}
1433c5d267eSJoel E. Denny };
1443c5d267eSJoel E. Denny 
1453c5d267eSJoel E. Denny static MarkerStyle GetMarker(FileCheckDiag::MatchType MatchTy) {
1463c5d267eSJoel E. Denny   switch (MatchTy) {
147*7df86967SJoel E. Denny   case FileCheckDiag::MatchFinalAndExpected:
148*7df86967SJoel E. Denny     return MarkerStyle('^', raw_ostream::GREEN);
1490e7e3fa0SJoel E. Denny   case FileCheckDiag::MatchFinalButExcluded:
1500e7e3fa0SJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: no match expected");
151cadfcef4SJoel E. Denny   case FileCheckDiag::MatchFinalButWrongLine:
152cadfcef4SJoel E. Denny     return MarkerStyle('!', raw_ostream::RED, "error: match on wrong line");
1533c5d267eSJoel E. Denny   case FileCheckDiag::MatchNoneButExpected:
1543c5d267eSJoel E. Denny     return MarkerStyle('X', raw_ostream::RED, "error: no match found");
1552c007c80SJoel E. Denny   case FileCheckDiag::MatchFuzzy:
1562c007c80SJoel E. Denny     return MarkerStyle('?', raw_ostream::MAGENTA, "possible intended match");
1573c5d267eSJoel E. Denny   case FileCheckDiag::MatchTypeCount:
1583c5d267eSJoel E. Denny     llvm_unreachable_internal("unexpected match type");
1593c5d267eSJoel E. Denny   }
1603c5d267eSJoel E. Denny   llvm_unreachable_internal("unexpected match type");
1613c5d267eSJoel E. Denny }
1623c5d267eSJoel E. Denny 
1633c5d267eSJoel E. Denny static void DumpInputAnnotationHelp(raw_ostream &OS) {
1643c5d267eSJoel E. Denny   OS << "The following description was requested by -dump-input=help to\n"
1653c5d267eSJoel E. Denny      << "explain the input annotations printed by -dump-input=always and\n"
1663c5d267eSJoel E. Denny      << "-dump-input=fail:\n\n";
1673c5d267eSJoel E. Denny 
1683c5d267eSJoel E. Denny   // Labels for input lines.
1693c5d267eSJoel E. Denny   OS << "  - ";
1703c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "L:";
1713c5d267eSJoel E. Denny   OS << "     labels line number L of the input file\n";
1723c5d267eSJoel E. Denny 
1733c5d267eSJoel E. Denny   // Labels for annotation lines.
1743c5d267eSJoel E. Denny   OS << "  - ";
1753c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L";
1762c007c80SJoel E. Denny   OS << "    labels the only match result for a pattern of type T from "
1773c5d267eSJoel E. Denny      << "line L of\n"
1783c5d267eSJoel E. Denny      << "           the check file\n";
1792c007c80SJoel E. Denny   OS << "  - ";
1802c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "T:L'N";
1812c007c80SJoel E. Denny   OS << "  labels the Nth match result for a pattern of type T from line "
1822c007c80SJoel E. Denny      << "L of\n"
1832c007c80SJoel E. Denny      << "           the check file\n";
1843c5d267eSJoel E. Denny 
1853c5d267eSJoel E. Denny   // Markers on annotation lines.
1863c5d267eSJoel E. Denny   OS << "  - ";
187*7df86967SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "^~~";
188*7df86967SJoel E. Denny   OS << "    marks good match (reported if -v)\n"
189*7df86967SJoel E. Denny      << "  - ";
190cadfcef4SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "!~~";
191cadfcef4SJoel E. Denny   OS << "    marks bad match, such as:\n"
192cadfcef4SJoel E. Denny      << "           - CHECK-NEXT on same line as previous match (error)\n"
1930e7e3fa0SJoel E. Denny      << "           - CHECK-NOT found (error)\n"
194cadfcef4SJoel E. Denny      << "  - ";
1953c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "X~~";
196cadfcef4SJoel E. Denny   OS << "    marks search range when no match is found, such as:\n"
197cadfcef4SJoel E. Denny      << "           - CHECK-NEXT not found (error)\n"
1982c007c80SJoel E. Denny      << "  - ";
1992c007c80SJoel E. Denny   WithColor(OS, raw_ostream::SAVEDCOLOR, true) << "?";
2002c007c80SJoel E. Denny   OS << "      marks fuzzy match when no match is found\n";
2013c5d267eSJoel E. Denny 
2023c5d267eSJoel E. Denny   // Colors.
2033c5d267eSJoel E. Denny   OS << "  - colors ";
204*7df86967SJoel E. Denny   WithColor(OS, raw_ostream::GREEN, true) << "success";
205*7df86967SJoel E. Denny   OS << ", ";
2063c5d267eSJoel E. Denny   WithColor(OS, raw_ostream::RED, true) << "error";
2072c007c80SJoel E. Denny   OS << ", ";
2082c007c80SJoel E. Denny   WithColor(OS, raw_ostream::MAGENTA, true) << "fuzzy match";
209*7df86967SJoel E. Denny   OS << ", ";
210*7df86967SJoel E. Denny   WithColor(OS, raw_ostream::CYAN, true, true) << "unmatched input";
2113c5d267eSJoel E. Denny   OS << "\n\n"
2123c5d267eSJoel E. Denny      << "If you are not seeing color above or in input dumps, try: -color\n";
2133c5d267eSJoel E. Denny }
2143c5d267eSJoel E. Denny 
2153c5d267eSJoel E. Denny /// An annotation for a single input line.
2163c5d267eSJoel E. Denny struct InputAnnotation {
2173c5d267eSJoel E. Denny   /// The check file line (one-origin indexing) where the directive that
2183c5d267eSJoel E. Denny   /// produced this annotation is located.
2193c5d267eSJoel E. Denny   unsigned CheckLine;
2202c007c80SJoel E. Denny   /// The index of the match result for this check.
2212c007c80SJoel E. Denny   unsigned CheckDiagIndex;
2223c5d267eSJoel E. Denny   /// The label for this annotation.
2233c5d267eSJoel E. Denny   std::string Label;
2243c5d267eSJoel E. Denny   /// What input line (one-origin indexing) this annotation marks.  This might
2253c5d267eSJoel E. Denny   /// be different from the starting line of the original diagnostic if this is
2263c5d267eSJoel E. Denny   /// a non-initial fragment of a diagnostic that has been broken across
2273c5d267eSJoel E. Denny   /// multiple lines.
2283c5d267eSJoel E. Denny   unsigned InputLine;
2293c5d267eSJoel E. Denny   /// The column range (one-origin indexing, open end) in which to to mark the
2303c5d267eSJoel E. Denny   /// input line.  If InputEndCol is UINT_MAX, treat it as the last column
2313c5d267eSJoel E. Denny   /// before the newline.
2323c5d267eSJoel E. Denny   unsigned InputStartCol, InputEndCol;
2333c5d267eSJoel E. Denny   /// The marker to use.
2343c5d267eSJoel E. Denny   MarkerStyle Marker;
235*7df86967SJoel E. Denny   /// Whether this annotation represents a final match for an expected pattern.
236*7df86967SJoel E. Denny   bool FinalAndExpectedMatch;
2373c5d267eSJoel E. Denny };
2383c5d267eSJoel E. Denny 
2393c5d267eSJoel E. Denny /// Get an abbreviation for the check type.
2403c5d267eSJoel E. Denny std::string GetCheckTypeAbbreviation(Check::FileCheckType Ty) {
2413c5d267eSJoel E. Denny   switch (Ty) {
2423c5d267eSJoel E. Denny   case Check::CheckPlain:
2433c5d267eSJoel E. Denny     if (Ty.getCount() > 1)
2443c5d267eSJoel E. Denny       return "count";
2453c5d267eSJoel E. Denny     return "check";
2463c5d267eSJoel E. Denny   case Check::CheckNext:
2473c5d267eSJoel E. Denny     return "next";
2483c5d267eSJoel E. Denny   case Check::CheckSame:
2493c5d267eSJoel E. Denny     return "same";
2503c5d267eSJoel E. Denny   case Check::CheckNot:
2513c5d267eSJoel E. Denny     return "not";
2523c5d267eSJoel E. Denny   case Check::CheckDAG:
2533c5d267eSJoel E. Denny     return "dag";
2543c5d267eSJoel E. Denny   case Check::CheckLabel:
2553c5d267eSJoel E. Denny     return "label";
2563c5d267eSJoel E. Denny   case Check::CheckEmpty:
2573c5d267eSJoel E. Denny     return "empty";
2583c5d267eSJoel E. Denny   case Check::CheckEOF:
2593c5d267eSJoel E. Denny     return "eof";
2603c5d267eSJoel E. Denny   case Check::CheckBadNot:
2613c5d267eSJoel E. Denny     return "bad-not";
2623c5d267eSJoel E. Denny   case Check::CheckBadCount:
2633c5d267eSJoel E. Denny     return "bad-count";
2643c5d267eSJoel E. Denny   case Check::CheckNone:
2653c5d267eSJoel E. Denny     llvm_unreachable("invalid FileCheckType");
2663c5d267eSJoel E. Denny   }
2673c5d267eSJoel E. Denny   llvm_unreachable("unknown FileCheckType");
2683c5d267eSJoel E. Denny }
2693c5d267eSJoel E. Denny 
2703c5d267eSJoel E. Denny static void BuildInputAnnotations(const std::vector<FileCheckDiag> &Diags,
2713c5d267eSJoel E. Denny                                   std::vector<InputAnnotation> &Annotations,
2723c5d267eSJoel E. Denny                                   unsigned &LabelWidth) {
2732c007c80SJoel E. Denny   // How many diagnostics has the current check seen so far?
2742c007c80SJoel E. Denny   unsigned CheckDiagCount = 0;
2753c5d267eSJoel E. Denny   // What's the widest label?
2763c5d267eSJoel E. Denny   LabelWidth = 0;
2773c5d267eSJoel E. Denny   for (auto DiagItr = Diags.begin(), DiagEnd = Diags.end(); DiagItr != DiagEnd;
2783c5d267eSJoel E. Denny        ++DiagItr) {
2793c5d267eSJoel E. Denny     InputAnnotation A;
2803c5d267eSJoel E. Denny 
2813c5d267eSJoel E. Denny     // Build label, which uniquely identifies this check result.
2823c5d267eSJoel E. Denny     A.CheckLine = DiagItr->CheckLine;
2833c5d267eSJoel E. Denny     llvm::raw_string_ostream Label(A.Label);
2843c5d267eSJoel E. Denny     Label << GetCheckTypeAbbreviation(DiagItr->CheckTy) << ":"
2853c5d267eSJoel E. Denny           << DiagItr->CheckLine;
2862c007c80SJoel E. Denny     A.CheckDiagIndex = UINT_MAX;
2872c007c80SJoel E. Denny     auto DiagNext = std::next(DiagItr);
2882c007c80SJoel E. Denny     if (DiagNext != DiagEnd && DiagItr->CheckTy == DiagNext->CheckTy &&
2892c007c80SJoel E. Denny         DiagItr->CheckLine == DiagNext->CheckLine)
2902c007c80SJoel E. Denny       A.CheckDiagIndex = CheckDiagCount++;
2912c007c80SJoel E. Denny     else if (CheckDiagCount) {
2922c007c80SJoel E. Denny       A.CheckDiagIndex = CheckDiagCount;
2932c007c80SJoel E. Denny       CheckDiagCount = 0;
2942c007c80SJoel E. Denny     }
2952c007c80SJoel E. Denny     if (A.CheckDiagIndex != UINT_MAX)
2962c007c80SJoel E. Denny       Label << "'" << A.CheckDiagIndex;
2972c007c80SJoel E. Denny     else
2982c007c80SJoel E. Denny       A.CheckDiagIndex = 0;
2993c5d267eSJoel E. Denny     Label.flush();
3003c5d267eSJoel E. Denny     LabelWidth = std::max((std::string::size_type)LabelWidth, A.Label.size());
3013c5d267eSJoel E. Denny 
3023c5d267eSJoel E. Denny     MarkerStyle Marker = GetMarker(DiagItr->MatchTy);
3033c5d267eSJoel E. Denny     A.Marker = Marker;
304*7df86967SJoel E. Denny     A.FinalAndExpectedMatch =
305*7df86967SJoel E. Denny         DiagItr->MatchTy == FileCheckDiag::MatchFinalAndExpected;
3063c5d267eSJoel E. Denny 
3073c5d267eSJoel E. Denny     // Compute the mark location, and break annotation into multiple
3083c5d267eSJoel E. Denny     // annotations if it spans multiple lines.
3093c5d267eSJoel E. Denny     A.InputLine = DiagItr->InputStartLine;
3103c5d267eSJoel E. Denny     A.InputStartCol = DiagItr->InputStartCol;
3113c5d267eSJoel E. Denny     if (DiagItr->InputStartLine == DiagItr->InputEndLine) {
3123c5d267eSJoel E. Denny       // Sometimes ranges are empty in order to indicate a specific point, but
3133c5d267eSJoel E. Denny       // that would mean nothing would be marked, so adjust the range to
3143c5d267eSJoel E. Denny       // include the following character.
3153c5d267eSJoel E. Denny       A.InputEndCol =
3163c5d267eSJoel E. Denny           std::max(DiagItr->InputStartCol + 1, DiagItr->InputEndCol);
3173c5d267eSJoel E. Denny       Annotations.push_back(A);
3183c5d267eSJoel E. Denny     } else {
3193c5d267eSJoel E. Denny       assert(DiagItr->InputStartLine < DiagItr->InputEndLine &&
3203c5d267eSJoel E. Denny              "expected input range not to be inverted");
3213c5d267eSJoel E. Denny       A.InputEndCol = UINT_MAX;
3223c5d267eSJoel E. Denny       A.Marker.Note = "";
3233c5d267eSJoel E. Denny       Annotations.push_back(A);
3243c5d267eSJoel E. Denny       for (unsigned L = DiagItr->InputStartLine + 1, E = DiagItr->InputEndLine;
3253c5d267eSJoel E. Denny            L <= E; ++L) {
3263c5d267eSJoel E. Denny         // If a range ends before the first column on a line, then it has no
3273c5d267eSJoel E. Denny         // characters on that line, so there's nothing to render.
3283c5d267eSJoel E. Denny         if (DiagItr->InputEndCol == 1 && L == E) {
3293c5d267eSJoel E. Denny           Annotations.back().Marker.Note = Marker.Note;
3303c5d267eSJoel E. Denny           break;
3313c5d267eSJoel E. Denny         }
3323c5d267eSJoel E. Denny         InputAnnotation B;
3333c5d267eSJoel E. Denny         B.CheckLine = A.CheckLine;
3342c007c80SJoel E. Denny         B.CheckDiagIndex = A.CheckDiagIndex;
3353c5d267eSJoel E. Denny         B.Label = A.Label;
3363c5d267eSJoel E. Denny         B.InputLine = L;
3373c5d267eSJoel E. Denny         B.Marker = Marker;
3383c5d267eSJoel E. Denny         B.Marker.Lead = '~';
3393c5d267eSJoel E. Denny         B.InputStartCol = 1;
3403c5d267eSJoel E. Denny         if (L != E) {
3413c5d267eSJoel E. Denny           B.InputEndCol = UINT_MAX;
3423c5d267eSJoel E. Denny           B.Marker.Note = "";
3433c5d267eSJoel E. Denny         } else
3443c5d267eSJoel E. Denny           B.InputEndCol = DiagItr->InputEndCol;
345*7df86967SJoel E. Denny         B.FinalAndExpectedMatch = A.FinalAndExpectedMatch;
3463c5d267eSJoel E. Denny         Annotations.push_back(B);
3473c5d267eSJoel E. Denny       }
3483c5d267eSJoel E. Denny     }
3493c5d267eSJoel E. Denny   }
3503c5d267eSJoel E. Denny }
3513c5d267eSJoel E. Denny 
352*7df86967SJoel E. Denny static void DumpAnnotatedInput(raw_ostream &OS, const FileCheckRequest &Req,
353*7df86967SJoel E. Denny                                StringRef InputFileText,
354*7df86967SJoel E. Denny                                std::vector<InputAnnotation> &Annotations,
355*7df86967SJoel E. Denny                                unsigned LabelWidth) {
3563c5d267eSJoel E. Denny   OS << "Full input was:\n<<<<<<\n";
3573c5d267eSJoel E. Denny 
3583c5d267eSJoel E. Denny   // Sort annotations.
3593c5d267eSJoel E. Denny   //
3603c5d267eSJoel E. Denny   // First, sort in the order of input lines to make it easier to find relevant
3613c5d267eSJoel E. Denny   // annotations while iterating input lines in the implementation below.
3623c5d267eSJoel E. Denny   // FileCheck diagnostics are not always reported and recorded in the order of
3633c5d267eSJoel E. Denny   // input lines due to, for example, CHECK-DAG and CHECK-NOT.
3643c5d267eSJoel E. Denny   //
3653c5d267eSJoel E. Denny   // Second, for annotations for the same input line, sort in the order of the
3663c5d267eSJoel E. Denny   // FileCheck directive's line in the check file (where there's at most one
3672c007c80SJoel E. Denny   // directive per line) and then by the index of the match result for that
3682c007c80SJoel E. Denny   // directive.  The rationale of this choice is that, for any input line, this
3692c007c80SJoel E. Denny   // sort establishes a total order of annotations that, with respect to match
3702c007c80SJoel E. Denny   // results, is consistent across multiple lines, thus making match results
3712c007c80SJoel E. Denny   // easier to track from one line to the next when they span multiple lines.
3723c5d267eSJoel E. Denny   std::sort(Annotations.begin(), Annotations.end(),
3733c5d267eSJoel E. Denny             [](const InputAnnotation &A, const InputAnnotation &B) {
3743c5d267eSJoel E. Denny               if (A.InputLine != B.InputLine)
3753c5d267eSJoel E. Denny                 return A.InputLine < B.InputLine;
3762c007c80SJoel E. Denny               if (A.CheckLine != B.CheckLine)
3773c5d267eSJoel E. Denny                 return A.CheckLine < B.CheckLine;
378*7df86967SJoel E. Denny               // FIXME: Sometimes CHECK-LABEL reports its match twice with
379*7df86967SJoel E. Denny               // other diagnostics in between, and then diag index incrementing
380*7df86967SJoel E. Denny               // fails to work properly, and then this assert fails.  We should
381*7df86967SJoel E. Denny               // suppress one of those diagnostics or do a better job of
382*7df86967SJoel E. Denny               // computing this index.  For now, we just produce a redundant
383*7df86967SJoel E. Denny               // CHECK-LABEL annotation.
384*7df86967SJoel E. Denny               // assert(A.CheckDiagIndex != B.CheckDiagIndex &&
385*7df86967SJoel E. Denny               //        "expected diagnostic indices to be unique within a "
386*7df86967SJoel E. Denny               //        " check line");
3872c007c80SJoel E. Denny               return A.CheckDiagIndex < B.CheckDiagIndex;
3883c5d267eSJoel E. Denny             });
3893c5d267eSJoel E. Denny 
3903c5d267eSJoel E. Denny   // Compute the width of the label column.
3913c5d267eSJoel E. Denny   const unsigned char *InputFilePtr = InputFileText.bytes_begin(),
3923c5d267eSJoel E. Denny                       *InputFileEnd = InputFileText.bytes_end();
3933c5d267eSJoel E. Denny   unsigned LineCount = InputFileText.count('\n');
3943c5d267eSJoel E. Denny   if (InputFileEnd[-1] != '\n')
3953c5d267eSJoel E. Denny     ++LineCount;
3963c5d267eSJoel E. Denny   unsigned LineNoWidth = log10(LineCount) + 1;
3973c5d267eSJoel E. Denny   // +3 below adds spaces (1) to the left of the (right-aligned) line numbers
3983c5d267eSJoel E. Denny   // on input lines and (2) to the right of the (left-aligned) labels on
3993c5d267eSJoel E. Denny   // annotation lines so that input lines and annotation lines are more
4003c5d267eSJoel E. Denny   // visually distinct.  For example, the spaces on the annotation lines ensure
4013c5d267eSJoel E. Denny   // that input line numbers and check directive line numbers never align
4023c5d267eSJoel E. Denny   // horizontally.  Those line numbers might not even be for the same file.
4033c5d267eSJoel E. Denny   // One space would be enough to achieve that, but more makes it even easier
4043c5d267eSJoel E. Denny   // to see.
4053c5d267eSJoel E. Denny   LabelWidth = std::max(LabelWidth, LineNoWidth) + 3;
4063c5d267eSJoel E. Denny 
4073c5d267eSJoel E. Denny   // Print annotated input lines.
4083c5d267eSJoel E. Denny   auto AnnotationItr = Annotations.begin(), AnnotationEnd = Annotations.end();
4093c5d267eSJoel E. Denny   for (unsigned Line = 1;
4103c5d267eSJoel E. Denny        InputFilePtr != InputFileEnd || AnnotationItr != AnnotationEnd;
4113c5d267eSJoel E. Denny        ++Line) {
4123c5d267eSJoel E. Denny     const unsigned char *InputFileLine = InputFilePtr;
4133c5d267eSJoel E. Denny 
4143c5d267eSJoel E. Denny     // Print right-aligned line number.
4153c5d267eSJoel E. Denny     WithColor(OS, raw_ostream::BLACK, true)
4163c5d267eSJoel E. Denny         << format_decimal(Line, LabelWidth) << ": ";
4173c5d267eSJoel E. Denny 
418*7df86967SJoel E. Denny     // For case where -v and colors are enabled, find the annotations for final
419*7df86967SJoel E. Denny     // matches for expected patterns in order to highlight everything else in
420*7df86967SJoel E. Denny     // the line.  There are no such annotations if -v is disabled.
421*7df86967SJoel E. Denny     std::vector<InputAnnotation> FinalAndExpectedMatches;
422*7df86967SJoel E. Denny     if (Req.Verbose && WithColor(OS).colorsEnabled()) {
423*7df86967SJoel E. Denny       for (auto I = AnnotationItr; I != AnnotationEnd && I->InputLine == Line;
424*7df86967SJoel E. Denny            ++I) {
425*7df86967SJoel E. Denny         if (I->FinalAndExpectedMatch)
426*7df86967SJoel E. Denny           FinalAndExpectedMatches.push_back(*I);
427*7df86967SJoel E. Denny       }
428*7df86967SJoel E. Denny     }
429*7df86967SJoel E. Denny 
430*7df86967SJoel E. Denny     // Print numbered line with highlighting where there are no matches for
431*7df86967SJoel E. Denny     // expected patterns.
4323c5d267eSJoel E. Denny     bool Newline = false;
433*7df86967SJoel E. Denny     {
434*7df86967SJoel E. Denny       WithColor COS(OS);
435*7df86967SJoel E. Denny       bool InMatch = false;
436*7df86967SJoel E. Denny       if (Req.Verbose)
437*7df86967SJoel E. Denny         COS.changeColor(raw_ostream::CYAN, true, true);
438*7df86967SJoel E. Denny       for (unsigned Col = 1; InputFilePtr != InputFileEnd && !Newline; ++Col) {
439*7df86967SJoel E. Denny         bool WasInMatch = InMatch;
440*7df86967SJoel E. Denny         InMatch = false;
441*7df86967SJoel E. Denny         for (auto M : FinalAndExpectedMatches) {
442*7df86967SJoel E. Denny           if (M.InputStartCol <= Col && Col < M.InputEndCol) {
443*7df86967SJoel E. Denny             InMatch = true;
444*7df86967SJoel E. Denny             break;
445*7df86967SJoel E. Denny           }
446*7df86967SJoel E. Denny         }
447*7df86967SJoel E. Denny         if (!WasInMatch && InMatch)
448*7df86967SJoel E. Denny           COS.resetColor();
449*7df86967SJoel E. Denny         else if (WasInMatch && !InMatch)
450*7df86967SJoel E. Denny           COS.changeColor(raw_ostream::CYAN, true, true);
4513c5d267eSJoel E. Denny         if (*InputFilePtr == '\n')
4523c5d267eSJoel E. Denny           Newline = true;
4533c5d267eSJoel E. Denny         else
454*7df86967SJoel E. Denny           COS << *InputFilePtr;
4553c5d267eSJoel E. Denny         ++InputFilePtr;
4563c5d267eSJoel E. Denny       }
457*7df86967SJoel E. Denny     }
4583c5d267eSJoel E. Denny     OS << '\n';
4593c5d267eSJoel E. Denny     unsigned InputLineWidth = InputFilePtr - InputFileLine - Newline;
4603c5d267eSJoel E. Denny 
4613c5d267eSJoel E. Denny     // Print any annotations.
4623c5d267eSJoel E. Denny     while (AnnotationItr != AnnotationEnd &&
4633c5d267eSJoel E. Denny            AnnotationItr->InputLine == Line) {
4643c5d267eSJoel E. Denny       WithColor COS(OS, AnnotationItr->Marker.Color, true);
4653c5d267eSJoel E. Denny       // The two spaces below are where the ": " appears on input lines.
4663c5d267eSJoel E. Denny       COS << left_justify(AnnotationItr->Label, LabelWidth) << "  ";
4673c5d267eSJoel E. Denny       unsigned Col;
4683c5d267eSJoel E. Denny       for (Col = 1; Col < AnnotationItr->InputStartCol; ++Col)
4693c5d267eSJoel E. Denny         COS << ' ';
4703c5d267eSJoel E. Denny       COS << AnnotationItr->Marker.Lead;
4713c5d267eSJoel E. Denny       // If InputEndCol=UINT_MAX, stop at InputLineWidth.
4723c5d267eSJoel E. Denny       for (++Col; Col < AnnotationItr->InputEndCol && Col <= InputLineWidth;
4733c5d267eSJoel E. Denny            ++Col)
4743c5d267eSJoel E. Denny         COS << '~';
4753c5d267eSJoel E. Denny       const std::string &Note = AnnotationItr->Marker.Note;
4763c5d267eSJoel E. Denny       if (!Note.empty()) {
4773c5d267eSJoel E. Denny         // Put the note at the end of the input line.  If we were to instead
4783c5d267eSJoel E. Denny         // put the note right after the marker, subsequent annotations for the
4793c5d267eSJoel E. Denny         // same input line might appear to mark this note instead of the input
4803c5d267eSJoel E. Denny         // line.
4813c5d267eSJoel E. Denny         for (; Col <= InputLineWidth; ++Col)
4823c5d267eSJoel E. Denny           COS << ' ';
4833c5d267eSJoel E. Denny         COS << ' ' << Note;
4843c5d267eSJoel E. Denny       }
4853c5d267eSJoel E. Denny       COS << '\n';
4863c5d267eSJoel E. Denny       ++AnnotationItr;
4873c5d267eSJoel E. Denny     }
4883c5d267eSJoel E. Denny   }
4893c5d267eSJoel E. Denny 
4903c5d267eSJoel E. Denny   OS << ">>>>>>\n";
4913c5d267eSJoel E. Denny }
4923c5d267eSJoel E. Denny 
493ee3c74fbSChris Lattner int main(int argc, char **argv) {
4943e66509fSJoel E. Denny   // Enable use of ANSI color codes because FileCheck is using them to
4953e66509fSJoel E. Denny   // highlight text.
4963e66509fSJoel E. Denny   llvm::sys::Process::UseANSIEscapeCodes(true);
4973e66509fSJoel E. Denny 
498197194b6SRui Ueyama   InitLLVM X(argc, argv);
49924994d77SJoel E. Denny   cl::ParseCommandLineOptions(argc, argv, /*Overview*/ "", /*Errs*/ nullptr,
50024994d77SJoel E. Denny                               "FILECHECK_OPTS");
5013c5d267eSJoel E. Denny   if (DumpInput == DumpInputHelp) {
5023c5d267eSJoel E. Denny     DumpInputAnnotationHelp(outs());
5033c5d267eSJoel E. Denny     return 0;
5043c5d267eSJoel E. Denny   }
5053c5d267eSJoel E. Denny   if (CheckFilename.empty()) {
5063c5d267eSJoel E. Denny     errs() << "<check-file> not specified\n";
5073c5d267eSJoel E. Denny     return 2;
5083c5d267eSJoel E. Denny   }
509ee3c74fbSChris Lattner 
510ffa9d2e4SAditya Nandakumar   FileCheckRequest Req;
511ffa9d2e4SAditya Nandakumar   for (auto Prefix : CheckPrefixes)
512ffa9d2e4SAditya Nandakumar     Req.CheckPrefixes.push_back(Prefix);
513ffa9d2e4SAditya Nandakumar 
514ffa9d2e4SAditya Nandakumar   for (auto CheckNot : ImplicitCheckNot)
515ffa9d2e4SAditya Nandakumar     Req.ImplicitCheckNot.push_back(CheckNot);
516ffa9d2e4SAditya Nandakumar 
517ffa9d2e4SAditya Nandakumar   for (auto G : GlobalDefines)
518ffa9d2e4SAditya Nandakumar     Req.GlobalDefines.push_back(G);
519ffa9d2e4SAditya Nandakumar 
520ffa9d2e4SAditya Nandakumar   Req.AllowEmptyInput = AllowEmptyInput;
521ffa9d2e4SAditya Nandakumar   Req.EnableVarScope = EnableVarScope;
522ffa9d2e4SAditya Nandakumar   Req.AllowDeprecatedDagOverlap = AllowDeprecatedDagOverlap;
523ffa9d2e4SAditya Nandakumar   Req.Verbose = Verbose;
524ffa9d2e4SAditya Nandakumar   Req.VerboseVerbose = VerboseVerbose;
525ffa9d2e4SAditya Nandakumar   Req.NoCanonicalizeWhiteSpace = NoCanonicalizeWhiteSpace;
526ffa9d2e4SAditya Nandakumar   Req.MatchFullLines = MatchFullLines;
527ffa9d2e4SAditya Nandakumar 
528ffa9d2e4SAditya Nandakumar   if (VerboseVerbose)
529ffa9d2e4SAditya Nandakumar     Req.Verbose = true;
530ffa9d2e4SAditya Nandakumar 
531ffa9d2e4SAditya Nandakumar   FileCheck FC(Req);
532ffa9d2e4SAditya Nandakumar   if (!FC.ValidateCheckPrefixes()) {
53313df4626SMatt Arsenault     errs() << "Supplied check-prefix is invalid! Prefixes must be unique and "
53413df4626SMatt Arsenault               "start with a letter and contain only alphanumeric characters, "
53513df4626SMatt Arsenault               "hyphens and underscores\n";
536c2735158SRui Ueyama     return 2;
537c2735158SRui Ueyama   }
538c2735158SRui Ueyama 
539ffa9d2e4SAditya Nandakumar   Regex PrefixRE = FC.buildCheckPrefixRegex();
540726774cbSChandler Carruth   std::string REError;
541726774cbSChandler Carruth   if (!PrefixRE.isValid(REError)) {
542726774cbSChandler Carruth     errs() << "Unable to combine check-prefix strings into a prefix regular "
543726774cbSChandler Carruth               "expression! This is likely a bug in FileCheck's verification of "
544726774cbSChandler Carruth               "the check-prefix strings. Regular expression parsing failed "
545726774cbSChandler Carruth               "with the following error: "
546726774cbSChandler Carruth            << REError << "\n";
547726774cbSChandler Carruth     return 2;
548726774cbSChandler Carruth   }
54913df4626SMatt Arsenault 
550ee3c74fbSChris Lattner   SourceMgr SM;
551ee3c74fbSChris Lattner 
552ee3c74fbSChris Lattner   // Read the expected strings from the check file.
55320247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> CheckFileOrErr =
55420247900SChandler Carruth       MemoryBuffer::getFileOrSTDIN(CheckFilename);
55520247900SChandler Carruth   if (std::error_code EC = CheckFileOrErr.getError()) {
55620247900SChandler Carruth     errs() << "Could not open check file '" << CheckFilename
55720247900SChandler Carruth            << "': " << EC.message() << '\n';
55820247900SChandler Carruth     return 2;
55920247900SChandler Carruth   }
56020247900SChandler Carruth   MemoryBuffer &CheckFile = *CheckFileOrErr.get();
56120247900SChandler Carruth 
56220247900SChandler Carruth   SmallString<4096> CheckFileBuffer;
563ffa9d2e4SAditya Nandakumar   StringRef CheckFileText = FC.CanonicalizeFile(CheckFile, CheckFileBuffer);
56420247900SChandler Carruth 
56520247900SChandler Carruth   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
56620247900SChandler Carruth                             CheckFileText, CheckFile.getBufferIdentifier()),
56720247900SChandler Carruth                         SMLoc());
56820247900SChandler Carruth 
569ffa9d2e4SAditya Nandakumar   std::vector<FileCheckString> CheckStrings;
570ffa9d2e4SAditya Nandakumar   if (FC.ReadCheckFile(SM, CheckFileText, PrefixRE, CheckStrings))
571ee3c74fbSChris Lattner     return 2;
572ee3c74fbSChris Lattner 
573ee3c74fbSChris Lattner   // Open the file to check and add it to SourceMgr.
57420247900SChandler Carruth   ErrorOr<std::unique_ptr<MemoryBuffer>> InputFileOrErr =
575adf21f2aSRafael Espindola       MemoryBuffer::getFileOrSTDIN(InputFilename);
57620247900SChandler Carruth   if (std::error_code EC = InputFileOrErr.getError()) {
577adf21f2aSRafael Espindola     errs() << "Could not open input file '" << InputFilename
578adf21f2aSRafael Espindola            << "': " << EC.message() << '\n';
5798e1c6477SEli Bendersky     return 2;
580ee3c74fbSChris Lattner   }
58120247900SChandler Carruth   MemoryBuffer &InputFile = *InputFileOrErr.get();
5822c3e5cdfSChris Lattner 
58320247900SChandler Carruth   if (InputFile.getBufferSize() == 0 && !AllowEmptyInput) {
584b692bed7SChris Lattner     errs() << "FileCheck error: '" << InputFilename << "' is empty.\n";
5852bd4f8b6SXinliang David Li     DumpCommandLine(argc, argv);
5868e1c6477SEli Bendersky     return 2;
587b692bed7SChris Lattner   }
588b692bed7SChris Lattner 
58920247900SChandler Carruth   SmallString<4096> InputFileBuffer;
590ffa9d2e4SAditya Nandakumar   StringRef InputFileText = FC.CanonicalizeFile(InputFile, InputFileBuffer);
5912c3e5cdfSChris Lattner 
592e8f2fb20SChandler Carruth   SM.AddNewSourceBuffer(MemoryBuffer::getMemBuffer(
593e8f2fb20SChandler Carruth                             InputFileText, InputFile.getBufferIdentifier()),
594e8f2fb20SChandler Carruth                         SMLoc());
595ee3c74fbSChris Lattner 
5963c5d267eSJoel E. Denny   if (DumpInput == DumpInputDefault)
5973c5d267eSJoel E. Denny     DumpInput = DumpInputOnFailure ? DumpInputFail : DumpInputNever;
5983c5d267eSJoel E. Denny 
5993c5d267eSJoel E. Denny   std::vector<FileCheckDiag> Diags;
6003c5d267eSJoel E. Denny   int ExitCode = FC.CheckInput(SM, InputFileText, CheckStrings,
6013c5d267eSJoel E. Denny                                DumpInput == DumpInputNever ? nullptr : &Diags)
6023c5d267eSJoel E. Denny                      ? EXIT_SUCCESS
6033c5d267eSJoel E. Denny                      : 1;
6043c5d267eSJoel E. Denny   if (DumpInput == DumpInputAlways ||
6053c5d267eSJoel E. Denny       (ExitCode == 1 && DumpInput == DumpInputFail)) {
6063c5d267eSJoel E. Denny     errs() << "\n"
6073c5d267eSJoel E. Denny            << "Input file: "
6083c5d267eSJoel E. Denny            << (InputFilename == "-" ? "<stdin>" : InputFilename.getValue())
6093c5d267eSJoel E. Denny            << "\n"
6103c5d267eSJoel E. Denny            << "Check file: " << CheckFilename << "\n"
6113c5d267eSJoel E. Denny            << "\n"
6123c5d267eSJoel E. Denny            << "-dump-input=help describes the format of the following dump.\n"
6133c5d267eSJoel E. Denny            << "\n";
6143c5d267eSJoel E. Denny     std::vector<InputAnnotation> Annotations;
6153c5d267eSJoel E. Denny     unsigned LabelWidth;
6163c5d267eSJoel E. Denny     BuildInputAnnotations(Diags, Annotations, LabelWidth);
617*7df86967SJoel E. Denny     DumpAnnotatedInput(errs(), Req, InputFileText, Annotations, LabelWidth);
6183c5d267eSJoel E. Denny   }
619346dfbe2SGeorge Karpenkov 
620346dfbe2SGeorge Karpenkov   return ExitCode;
621ee3c74fbSChris Lattner }
622