10b57cec5SDimitry Andric //===- StringMatcher.cpp - Generate a matcher for input strings -----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements the StringMatcher class.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/TableGen/StringMatcher.h"
140b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
15bdd1243dSDimitry Andric #include "llvm/Support/ErrorHandling.h"
160b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
170b57cec5SDimitry Andric #include <cassert>
180b57cec5SDimitry Andric #include <map>
190b57cec5SDimitry Andric #include <string>
200b57cec5SDimitry Andric #include <utility>
210b57cec5SDimitry Andric #include <vector>
220b57cec5SDimitry Andric 
230b57cec5SDimitry Andric using namespace llvm;
240b57cec5SDimitry Andric 
250b57cec5SDimitry Andric /// FindFirstNonCommonLetter - Find the first character in the keys of the
260b57cec5SDimitry Andric /// string pairs that is not shared across the whole set of strings.  All
270b57cec5SDimitry Andric /// strings are assumed to have the same length.
280b57cec5SDimitry Andric static unsigned
FindFirstNonCommonLetter(const std::vector<const StringMatcher::StringPair * > & Matches)290b57cec5SDimitry Andric FindFirstNonCommonLetter(const std::vector<const
300b57cec5SDimitry Andric                               StringMatcher::StringPair*> &Matches) {
310b57cec5SDimitry Andric   assert(!Matches.empty());
320b57cec5SDimitry Andric   for (unsigned i = 0, e = Matches[0]->first.size(); i != e; ++i) {
330b57cec5SDimitry Andric     // Check to see if letter i is the same across the set.
340b57cec5SDimitry Andric     char Letter = Matches[0]->first[i];
350b57cec5SDimitry Andric 
360eae32dcSDimitry Andric     for (const StringMatcher::StringPair *Match : Matches)
370eae32dcSDimitry Andric       if (Match->first[i] != Letter)
380b57cec5SDimitry Andric         return i;
390b57cec5SDimitry Andric   }
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric   return Matches[0]->first.size();
420b57cec5SDimitry Andric }
430b57cec5SDimitry Andric 
440b57cec5SDimitry Andric /// EmitStringMatcherForChar - Given a set of strings that are known to be the
450b57cec5SDimitry Andric /// same length and whose characters leading up to CharNo are the same, emit
460b57cec5SDimitry Andric /// code to verify that CharNo and later are the same.
470b57cec5SDimitry Andric ///
480b57cec5SDimitry Andric /// \return - True if control can leave the emitted code fragment.
EmitStringMatcherForChar(const std::vector<const StringPair * > & Matches,unsigned CharNo,unsigned IndentCount,bool IgnoreDuplicates) const490b57cec5SDimitry Andric bool StringMatcher::EmitStringMatcherForChar(
500b57cec5SDimitry Andric     const std::vector<const StringPair *> &Matches, unsigned CharNo,
510b57cec5SDimitry Andric     unsigned IndentCount, bool IgnoreDuplicates) const {
520b57cec5SDimitry Andric   assert(!Matches.empty() && "Must have at least one string to match!");
530b57cec5SDimitry Andric   std::string Indent(IndentCount * 2 + 4, ' ');
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric   // If we have verified that the entire string matches, we're done: output the
560b57cec5SDimitry Andric   // matching code.
570b57cec5SDimitry Andric   if (CharNo == Matches[0]->first.size()) {
580b57cec5SDimitry Andric     if (Matches.size() > 1 && !IgnoreDuplicates)
590b57cec5SDimitry Andric       report_fatal_error("Had duplicate keys to match on");
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric     // If the to-execute code has \n's in it, indent each subsequent line.
620b57cec5SDimitry Andric     StringRef Code = Matches[0]->second;
630b57cec5SDimitry Andric 
640b57cec5SDimitry Andric     std::pair<StringRef, StringRef> Split = Code.split('\n');
650b57cec5SDimitry Andric     OS << Indent << Split.first << "\t // \"" << Matches[0]->first << "\"\n";
660b57cec5SDimitry Andric 
670b57cec5SDimitry Andric     Code = Split.second;
680b57cec5SDimitry Andric     while (!Code.empty()) {
690b57cec5SDimitry Andric       Split = Code.split('\n');
700b57cec5SDimitry Andric       OS << Indent << Split.first << "\n";
710b57cec5SDimitry Andric       Code = Split.second;
720b57cec5SDimitry Andric     }
730b57cec5SDimitry Andric     return false;
740b57cec5SDimitry Andric   }
750b57cec5SDimitry Andric 
760b57cec5SDimitry Andric   // Bucket the matches by the character we are comparing.
770b57cec5SDimitry Andric   std::map<char, std::vector<const StringPair*>> MatchesByLetter;
780b57cec5SDimitry Andric 
790eae32dcSDimitry Andric   for (const StringPair *Match : Matches)
800eae32dcSDimitry Andric     MatchesByLetter[Match->first[CharNo]].push_back(Match);
810b57cec5SDimitry Andric 
820b57cec5SDimitry Andric   // If we have exactly one bucket to match, see how many characters are common
830b57cec5SDimitry Andric   // across the whole set and match all of them at once.
840b57cec5SDimitry Andric   if (MatchesByLetter.size() == 1) {
850b57cec5SDimitry Andric     unsigned FirstNonCommonLetter = FindFirstNonCommonLetter(Matches);
860b57cec5SDimitry Andric     unsigned NumChars = FirstNonCommonLetter-CharNo;
870b57cec5SDimitry Andric 
880b57cec5SDimitry Andric     // Emit code to break out if the prefix doesn't match.
890b57cec5SDimitry Andric     if (NumChars == 1) {
900b57cec5SDimitry Andric       // Do the comparison with if (Str[1] != 'f')
910b57cec5SDimitry Andric       // FIXME: Need to escape general characters.
920b57cec5SDimitry Andric       OS << Indent << "if (" << StrVariableName << "[" << CharNo << "] != '"
930b57cec5SDimitry Andric       << Matches[0]->first[CharNo] << "')\n";
940b57cec5SDimitry Andric       OS << Indent << "  break;\n";
950b57cec5SDimitry Andric     } else {
960b57cec5SDimitry Andric       // Do the comparison with if memcmp(Str.data()+1, "foo", 3).
970b57cec5SDimitry Andric       // FIXME: Need to escape general strings.
980b57cec5SDimitry Andric       OS << Indent << "if (memcmp(" << StrVariableName << ".data()+" << CharNo
990b57cec5SDimitry Andric          << ", \"" << Matches[0]->first.substr(CharNo, NumChars) << "\", "
1000b57cec5SDimitry Andric          << NumChars << ") != 0)\n";
1010b57cec5SDimitry Andric       OS << Indent << "  break;\n";
1020b57cec5SDimitry Andric     }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric     return EmitStringMatcherForChar(Matches, FirstNonCommonLetter, IndentCount,
1050b57cec5SDimitry Andric                                     IgnoreDuplicates);
1060b57cec5SDimitry Andric   }
1070b57cec5SDimitry Andric 
1080b57cec5SDimitry Andric   // Otherwise, we have multiple possible things, emit a switch on the
1090b57cec5SDimitry Andric   // character.
1100b57cec5SDimitry Andric   OS << Indent << "switch (" << StrVariableName << "[" << CharNo << "]) {\n";
1110b57cec5SDimitry Andric   OS << Indent << "default: break;\n";
1120b57cec5SDimitry Andric 
113fe6060f1SDimitry Andric   for (const auto &LI : MatchesByLetter) {
1140b57cec5SDimitry Andric     // TODO: escape hard stuff (like \n) if we ever care about it.
115fe6060f1SDimitry Andric     OS << Indent << "case '" << LI.first << "':\t // " << LI.second.size()
116fe6060f1SDimitry Andric        << " string";
117fe6060f1SDimitry Andric     if (LI.second.size() != 1)
118fe6060f1SDimitry Andric       OS << 's';
1190b57cec5SDimitry Andric     OS << " to match.\n";
120fe6060f1SDimitry Andric     if (EmitStringMatcherForChar(LI.second, CharNo + 1, IndentCount + 1,
1210b57cec5SDimitry Andric                                  IgnoreDuplicates))
1220b57cec5SDimitry Andric       OS << Indent << "  break;\n";
1230b57cec5SDimitry Andric   }
1240b57cec5SDimitry Andric 
1250b57cec5SDimitry Andric   OS << Indent << "}\n";
1260b57cec5SDimitry Andric   return true;
1270b57cec5SDimitry Andric }
1280b57cec5SDimitry Andric 
1290b57cec5SDimitry Andric /// Emit - Top level entry point.
1300b57cec5SDimitry Andric ///
Emit(unsigned Indent,bool IgnoreDuplicates) const1310b57cec5SDimitry Andric void StringMatcher::Emit(unsigned Indent, bool IgnoreDuplicates) const {
1320b57cec5SDimitry Andric   // If nothing to match, just fall through.
1330b57cec5SDimitry Andric   if (Matches.empty()) return;
1340b57cec5SDimitry Andric 
1350b57cec5SDimitry Andric   // First level categorization: group strings by length.
1360b57cec5SDimitry Andric   std::map<unsigned, std::vector<const StringPair*>> MatchesByLength;
1370b57cec5SDimitry Andric 
1380eae32dcSDimitry Andric   for (const StringPair &Match : Matches)
1390eae32dcSDimitry Andric     MatchesByLength[Match.first.size()].push_back(&Match);
1400b57cec5SDimitry Andric 
1410b57cec5SDimitry Andric   // Output a switch statement on length and categorize the elements within each
1420b57cec5SDimitry Andric   // bin.
1430b57cec5SDimitry Andric   OS.indent(Indent*2+2) << "switch (" << StrVariableName << ".size()) {\n";
1440b57cec5SDimitry Andric   OS.indent(Indent*2+2) << "default: break;\n";
1450b57cec5SDimitry Andric 
146fe6060f1SDimitry Andric   for (const auto &LI : MatchesByLength) {
147fe6060f1SDimitry Andric     OS.indent(Indent * 2 + 2)
148fe6060f1SDimitry Andric         << "case " << LI.first << ":\t // " << LI.second.size() << " string"
149fe6060f1SDimitry Andric         << (LI.second.size() == 1 ? "" : "s") << " to match.\n";
150fe6060f1SDimitry Andric     if (EmitStringMatcherForChar(LI.second, 0, Indent, IgnoreDuplicates))
1510b57cec5SDimitry Andric       OS.indent(Indent*2+4) << "break;\n";
1520b57cec5SDimitry Andric   }
1530b57cec5SDimitry Andric 
1540b57cec5SDimitry Andric   OS.indent(Indent*2+2) << "}\n";
1550b57cec5SDimitry Andric }
156