add newline to make cl.exe happy.
[oota-llvm.git] / include / llvm / ADT / StringSwitch.h
1 //===--- StringSwitch.h - Switch-on-literal-string Construct --------------===/
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 //  This file implements the StringSwitch template, which mimics a switch()
10 //  statements whose cases are string literals.
11 //
12 //===----------------------------------------------------------------------===/
13 #ifndef LLVM_ADT_STRINGSWITCH_H
14 #define LLVM_ADT_STRINGSWITCH_H
15
16 #include "llvm/ADT/StringRef.h"
17 #include <cassert>
18 #include <cstring>
19
20 namespace llvm {
21   
22 /// \brief A switch()-like statement whose cases are string literals.
23 ///
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]:
29 ///
30 /// \code
31 /// Color color = StringSwitch<Color>(argv[i])
32 ///   .Case("red", Red)
33 ///   .Case("orange", Orange)
34 ///   .Case("yellow", Yellow)
35 ///   .Case("green", Green)
36 ///   .Case("blue", Blue)
37 ///   .Case("indigo", Indigo)
38 ///   .Case("violet", Violet)
39 ///   .Default(UnknownColor);
40 /// \endcode
41 template<typename T>
42 class StringSwitch {
43   /// \brief The string we are matching.
44   StringRef Str;
45   
46   /// \brief The result of this switch statement, once known.
47   T Result;
48   
49   /// \brief Set true when the result of this switch is already known; in this
50   /// case, Result is valid.
51   bool ResultKnown;
52   
53 public:
54   explicit StringSwitch(StringRef Str) 
55   : Str(Str), ResultKnown(false) { }
56   
57   template<unsigned N>
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)) {
61       Result = Value;
62       ResultKnown = true;
63     }
64     
65     return *this;
66   }
67   
68   T Default(const T& Value) {
69     if (ResultKnown)
70       return Result;
71     
72     return Value;
73   }
74   
75   operator T() {
76     assert(ResultKnown && "Fell off the end of a string-switch");
77     return Result;
78   }
79 };
80
81 } // end namespace llvm
82
83 #endif // LLVM_ADT_STRINGSWITCH_H