1 // Copyright 2015 Google Inc. All rights reserved 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #ifndef SYMTAB_H_ 16 #define SYMTAB_H_ 17 18 #include <string> 19 #include <vector> 20 21 #include "string_piece.h" 22 23 using namespace std; 24 25 extern vector<string*>* g_symbols; 26 27 class Symtab; 28 class Var; 29 30 class Symbol { 31 public: 32 struct IsUninitialized {}; Symbol(IsUninitialized)33 explicit Symbol(IsUninitialized) : v_(-1) {} 34 str()35 const string& str() const { return *((*g_symbols)[v_]); } 36 c_str()37 const char* c_str() const { return str().c_str(); } 38 empty()39 bool empty() const { return !v_; } 40 val()41 int val() const { return v_; } 42 get(size_t i)43 char get(size_t i) const { 44 const string& s = str(); 45 if (i >= s.size()) 46 return 0; 47 return s[i]; 48 } 49 IsValid()50 bool IsValid() const { return v_ >= 0; } 51 52 Var* PeekGlobalVar() const; 53 Var* GetGlobalVar() const; 54 void SetGlobalVar(Var* v, 55 bool is_override = false, 56 bool* readonly = nullptr) const; 57 58 private: 59 explicit Symbol(int v); 60 61 int v_; 62 63 friend class Symtab; 64 }; 65 66 class ScopedGlobalVar { 67 public: 68 ScopedGlobalVar(Symbol name, Var* var); 69 ~ScopedGlobalVar(); 70 71 private: 72 Symbol name_; 73 Var* orig_; 74 }; 75 76 inline bool operator==(const Symbol& x, const Symbol& y) { 77 return x.val() == y.val(); 78 } 79 80 inline bool operator<(const Symbol& x, const Symbol& y) { 81 return x.val() < y.val(); 82 } 83 84 namespace std { 85 template <> 86 struct hash<Symbol> { 87 size_t operator()(const Symbol& s) const { return s.val(); } 88 }; 89 } // namespace std 90 91 extern Symbol kEmptySym; 92 extern Symbol kShellSym; 93 94 void InitSymtab(); 95 void QuitSymtab(); 96 Symbol Intern(StringPiece s); 97 98 string JoinSymbols(const vector<Symbol>& syms, const char* sep); 99 100 #endif // SYMTAB_H_ 101