1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef TOOLS_GN_VALUE_H_ 6 #define TOOLS_GN_VALUE_H_ 7 8 #include "base/basictypes.h" 9 #include "base/logging.h" 10 #include "base/strings/string_piece.h" 11 #include "tools/gn/err.h" 12 13 class ParseNode; 14 15 // Represents a variable value in the interpreter. 16 class Value { 17 public: 18 enum Type { 19 NONE = 0, 20 BOOLEAN, 21 INTEGER, 22 STRING, 23 LIST 24 }; 25 26 Value(); 27 Value(const ParseNode* origin, Type t); 28 Value(const ParseNode* origin, bool bool_val); 29 Value(const ParseNode* origin, int64 int_val); 30 Value(const ParseNode* origin, std::string str_val); 31 Value(const ParseNode* origin, const char* str_val); 32 ~Value(); 33 type()34 Type type() const { return type_; } 35 36 // Returns a string describing the given type. 37 static const char* DescribeType(Type t); 38 39 // Returns the node that made this. May be NULL. origin()40 const ParseNode* origin() const { return origin_; } set_origin(const ParseNode * o)41 void set_origin(const ParseNode* o) { origin_ = o; } 42 43 // Sets the origin of this value, recursively going into list child 44 // values and also setting their origins. 45 void RecursivelySetOrigin(const ParseNode* o); 46 boolean_value()47 bool& boolean_value() { 48 DCHECK(type_ == BOOLEAN); 49 return boolean_value_; 50 } boolean_value()51 const bool& boolean_value() const { 52 DCHECK(type_ == BOOLEAN); 53 return boolean_value_; 54 } 55 int_value()56 int64& int_value() { 57 DCHECK(type_ == INTEGER); 58 return int_value_; 59 } int_value()60 const int64& int_value() const { 61 DCHECK(type_ == INTEGER); 62 return int_value_; 63 } 64 string_value()65 std::string& string_value() { 66 DCHECK(type_ == STRING); 67 return string_value_; 68 } string_value()69 const std::string& string_value() const { 70 DCHECK(type_ == STRING); 71 return string_value_; 72 } 73 list_value()74 std::vector<Value>& list_value() { 75 DCHECK(type_ == LIST); 76 return list_value_; 77 } list_value()78 const std::vector<Value>& list_value() const { 79 DCHECK(type_ == LIST); 80 return list_value_; 81 } 82 83 // Converts the given value to a string. Returns true if strings should be 84 // quoted or the ToString of a string should be the string itself. 85 std::string ToString(bool quote_strings) const; 86 87 // Verifies that the value is of the given type. If it isn't, returns 88 // false and sets the error. 89 bool VerifyTypeIs(Type t, Err* err) const; 90 91 // Compares values. Only the "value" is compared, not the origin. 92 bool operator==(const Value& other) const; 93 bool operator!=(const Value& other) const; 94 95 private: 96 Type type_; 97 std::string string_value_; 98 bool boolean_value_; 99 int64 int_value_; 100 std::vector<Value> list_value_; 101 const ParseNode* origin_; 102 }; 103 104 #endif // TOOLS_GN_VALUE_H_ 105