1 /*
2  * Copyright (C) 2016 The Android Open Source Project
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 SCOPE_H_
18 #define SCOPE_H_
19 
20 #include <android-base/macros.h>
21 #include <android-base/logging.h>
22 #include <string>
23 #include <vector>
24 #include <map>
25 
26 namespace android {
27 
28 /* This class is used to represent declarations or notes
29  * which are otherwise not included in a HIDL HAL
30  */
31 template<typename T>
32 struct Scope {
ScopeScope33     Scope() {}
~ScopeScope34     ~Scope() {}
35 
36     void enter(std::string name, T item);
37     void leave(std::string name);
38 
39     T lookup(std::string name) const;
40 
41 private:
42     std::map<std::string, T> mScopeContents;
43 
44     DISALLOW_COPY_AND_ASSIGN(Scope);
45 };
46 
47 template<typename T>
enter(std::string name,T item)48 void Scope<T>::enter(std::string name, T item) {
49     auto it = mScopeContents.find(name);
50 
51     if (it != mScopeContents.end()) {
52         LOG(WARNING) << "Redeclaring variable in scope: " << name;
53         return;
54     }
55 
56     mScopeContents[name] = item;
57 }
58 
59 template<typename T>
leave(std::string name)60 void Scope<T>::leave(std::string name) {
61     auto it = mScopeContents.find(name);
62 
63     if (it == mScopeContents.end()) {
64         LOG(WARNING) << "Tried to undefined already undefined value in scope: " << name;
65         return;
66     }
67 
68     mScopeContents.erase(it);
69 }
70 
71 template<typename T>
lookup(std::string name)72 T Scope<T>::lookup(std::string name) const {
73     auto it = mScopeContents.find(name);
74 
75     if (it == mScopeContents.end()) {
76         return NULL;
77     }
78 
79     return (*it).second;
80 }
81 
82 }  // namespace android
83 
84 #endif  // SCOPE_H_