factor the snazzy string matcher code that Daniel hates
[oota-llvm.git] / utils / TableGen / StringMatcher.cpp
1 //===- StringMatcher.cpp - Generate a matcher for input strings -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the StringMatcher class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "StringMatcher.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include <map>
17 using namespace llvm;
18
19 /// FindFirstNonCommonLetter - Find the first character in the keys of the
20 /// string pairs that is not shared across the whole set of strings.  All
21 /// strings are assumed to have the same length.
22 static unsigned 
23 FindFirstNonCommonLetter(const std::vector<const
24                               StringMatcher::StringPair*> &Matches) {
25   assert(!Matches.empty());
26   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
27     // Check to see if letter i is the same across the set.
28     char Letter = Matches[0]->first[i];
29     
30     for (unsigned str = 0, e = Matches.size(); str != e; ++str)
31       if (Matches[str]->first[i] != Letter)
32         return i;
33   }
34   
35   return Matches[0]->first.size();
36 }
37
38 /// EmitStringMatcherForChar - Given a set of strings that are known to be the
39 /// same length and whose characters leading up to CharNo are the same, emit
40 /// code to verify that CharNo and later are the same.
41 ///
42 /// \return - True if control can leave the emitted code fragment.
43 bool StringMatcher::
44 EmitStringMatcherForChar(const std::vector<const StringPair*> &Matches,
45                          unsigned CharNo, unsigned IndentCount) const {
46   assert(!Matches.empty() && "Must have at least one string to match!");
47   std::string Indent(IndentCount*2+4, ' ');
48   
49   // If we have verified that the entire string matches, we're done: output the
50   // matching code.
51   if (CharNo == Matches[0]->first.size()) {
52     assert(Matches.size() == 1 && "Had duplicate keys to match on");
53     
54     // FIXME: If Matches[0].first has embeded \n, this will be bad.
55     OS << Indent << Matches[0]->second << "\t // \"" << Matches[0]->first
56     << "\"\n";
57     return false;
58   }
59   
60   // Bucket the matches by the character we are comparing.
61   std::map<char, std::vector<const StringPair*> > MatchesByLetter;
62   
63   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
64     MatchesByLetter[Matches[i]->first[CharNo]].push_back(Matches[i]);
65   
66   
67   // If we have exactly one bucket to match, see how many characters are common
68   // across the whole set and match all of them at once.
69   if (MatchesByLetter.size() == 1) {
70     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
71     unsigned NumChars = FirstNonCommonLetter-CharNo;
72     
73     // Emit code to break out if the prefix doesn't match.
74     if (NumChars == 1) {
75       // Do the comparison with if (Str[1] != 'f')
76       // FIXME: Need to escape general characters.
77       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
78       << Matches[0]->first[CharNo] << "')\n";
79       OS << Indent << "  break;\n";
80     } else {
81       // Do the comparison with if (Str.substr(1,3) != "foo").    
82       // FIXME: Need to escape general strings.
83       OS << Indent << "if (" << StrVariableName << ".substr(" << CharNo << ","
84       << NumChars << ") != \"";
85       OS << Matches[0]->first.substr(CharNo, NumChars) << "\")\n";
86       OS << Indent << "  break;\n";
87     }
88     
89     return EmitStringMatcherForChar(Matches, FirstNonCommonLetter, IndentCount);
90   }
91   
92   // Otherwise, we have multiple possible things, emit a switch on the
93   // character.
94   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
95   OS << Indent << "default: break;\n";
96   
97   for (std::map<char, std::vector<const StringPair*> >::iterator LI = 
98        MatchesByLetter.begin(), E = MatchesByLetter.end(); LI != E; ++LI) {
99     // TODO: escape hard stuff (like \n) if we ever care about it.
100     OS << Indent << "case '" << LI->first << "':\t // "
101     << LI->second.size() << " strings to match.\n";
102     if (EmitStringMatcherForChar(LI->second, CharNo+1, IndentCount+1))
103       OS << Indent << "  break;\n";
104   }
105   
106   OS << Indent << "}\n";
107   return true;
108 }
109
110
111 /// Emit - Top level entry point.
112 ///
113 void StringMatcher::Emit() const {
114   // First level categorization: group strings by length.
115   std::map<unsigned, std::vector<const StringPair*> > MatchesByLength;
116   
117   for (unsigned i = 0, e = Matches.size(); i != e; ++i)
118     MatchesByLength[Matches[i].first.size()].push_back(&Matches[i]);
119   
120   // Output a switch statement on length and categorize the elements within each
121   // bin.
122   OS << "  switch (" << StrVariableName << ".size()) {\n";
123   OS << "  default: break;\n";
124   
125   for (std::map<unsigned, std::vector<const StringPair*> >::iterator LI =
126        MatchesByLength.begin(), E = MatchesByLength.end(); LI != E; ++LI) {
127     OS << "  case " << LI->first << ":\t // " << LI->second.size()
128     << " strings to match.\n";
129     if (EmitStringMatcherForChar(LI->second, 0, 0))
130       OS << "    break;\n";
131   }
132   
133   OS << "  }\n";
134 }