1 //===--- StringSwitch.h - Switch-on-literal-string Construct --------------===/
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //===----------------------------------------------------------------------===/
9 // This file implements the StringSwitch template, which mimics a switch()
10 // statement whose cases are string literals.
12 //===----------------------------------------------------------------------===/
13 #ifndef LLVM_ADT_STRINGSWITCH_H
14 #define LLVM_ADT_STRINGSWITCH_H
16 #include "llvm/ADT/StringRef.h"
22 /// \brief A switch()-like statement whose cases are string literals.
24 /// The StringSwitch class is a simple form of a switch() statement that
25 /// determines whether the given string matches one of the given string
26 /// literals. The template type parameter \p T is the type of the value that
27 /// will be returned from the string-switch expression. For example,
28 /// the following code switches on the name of a color in \c argv[i]:
31 /// Color color = StringSwitch<Color>(argv[i])
33 /// .Case("orange", Orange)
34 /// .Case("yellow", Yellow)
35 /// .Case("green", Green)
36 /// .Case("blue", Blue)
37 /// .Case("indigo", Indigo)
38 /// .Cases("violet", "purple", Violet)
39 /// .Default(UnknownColor);
43 /// \brief The string we are matching.
46 /// \brief The result of this switch statement, once known.
49 /// \brief Set true when the result of this switch is already known; in this
50 /// case, Result is valid.
54 explicit StringSwitch(StringRef Str)
55 : Str(Str), ResultKnown(false) { }
58 StringSwitch& Case(const char (&S)[N], const T& Value) {
59 if (!ResultKnown && N-1 == Str.size() &&
60 (std::memcmp(S, Str.data(), N-1) == 0)) {
68 template<unsigned N0, unsigned N1>
69 StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
71 return Case(S0, Value).Case(S1, Value);
74 template<unsigned N0, unsigned N1, unsigned N2>
75 StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
76 const char (&S2)[N2], const T& Value) {
77 return Case(S0, Value).Case(S1, Value).Case(S2, Value);
80 template<unsigned N0, unsigned N1, unsigned N2, unsigned N3>
81 StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
82 const char (&S2)[N2], const char (&S3)[N3],
84 return Case(S0, Value).Case(S1, Value).Case(S2, Value).Case(S3, Value);
87 template<unsigned N0, unsigned N1, unsigned N2, unsigned N3, unsigned N4>
88 StringSwitch& Cases(const char (&S0)[N0], const char (&S1)[N1],
89 const char (&S2)[N2], const char (&S3)[N3],
90 const char (&S4)[N4], const T& Value) {
91 return Case(S0, Value).Case(S1, Value).Case(S2, Value).Case(S3, Value)
95 T Default(const T& Value) {
103 assert(ResultKnown && "Fell off the end of a string-switch");
108 } // end namespace llvm
110 #endif // LLVM_ADT_STRINGSWITCH_H