1 /*
2  * Copyright 2017 WebAssembly Community Group participants
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef wasm_support_name_h
18 #define wasm_support_name_h
19 
20 #include <string>
21 
22 #include "emscripten-optimizer/istring.h"
23 
24 namespace wasm {
25 
26 // We use a Name for all of the identifiers. These are IStrings, so they are
27 // all interned - comparisons etc are just pointer comparisons, so there is no
28 // perf loss. Having names everywhere makes using the AST much nicer (for
29 // example, block names are strings and not offsets, which makes composition
30 // - adding blocks, removing blocks - easy). One exception is local variables,
31 // where we do use indices, as they are a large proportion of the AST,
32 // perf matters a lot there, and compositionality is not a problem.
33 // TODO: as an optimization, IString values < some threshold could be considered
34 //       numerical indices directly.
35 
36 struct Name : public cashew::IString {
NameName37   Name() : cashew::IString() {}
NameName38   Name(const char* str) : cashew::IString(str, false) {}
NameName39   Name(cashew::IString str) : cashew::IString(str) {}
NameName40   Name(const std::string& str) : cashew::IString(str.c_str(), false) {}
41 
42   friend std::ostream& operator<<(std::ostream& o, Name name) {
43     if (name.str) {
44       return o << name.str;
45     } else {
46       return o << "(null Name)";
47     }
48   }
49 
fromIntName50   static Name fromInt(size_t i) {
51     return cashew::IString(std::to_string(i).c_str(), false);
52   }
53 
hasSubstringName54   bool hasSubstring(cashew::IString substring) {
55     return strstr(c_str(), substring.c_str()) != nullptr;
56   }
57 };
58 
59 } // namespace wasm
60 
61 namespace std {
62 
63 template<> struct hash<wasm::Name> : hash<cashew::IString> {};
64 
65 } // namespace std
66 
67 #endif // wasm_support_name_h
68