diff options
Diffstat (limited to 'tiger-compiler/lib/misc/scoped-map.hxx')
| -rw-r--r-- | tiger-compiler/lib/misc/scoped-map.hxx | 86 |
1 files changed, 86 insertions, 0 deletions
diff --git a/tiger-compiler/lib/misc/scoped-map.hxx b/tiger-compiler/lib/misc/scoped-map.hxx new file mode 100644 index 0000000..14258b9 --- /dev/null +++ b/tiger-compiler/lib/misc/scoped-map.hxx @@ -0,0 +1,86 @@ +/** \file misc/scoped-map.hxx + ** \brief Implementation of misc::scoped_map. + */ + +#include <misc/scoped-map.hh> + +#pragma once + +#include <sstream> +#include <stdexcept> +#include <type_traits> + +#include <ranges> +#include <misc/algorithm.hh> +#include <misc/contract.hh> +#include <misc/indent.hh> + +namespace misc +{ + // FIXME DONE: Some code was deleted here. + + template <typename Key, typename Data> + void scoped_map<Key, Data>::put(const Key& key, const Data& value) + { + scopes_.back().insert_or_assign(key, value); + } + + template <typename Key, typename Data> + Data scoped_map<Key, Data>::get(const Key& key) const + requires(std::is_pointer_v<Data>) + { + if (auto data = scopes_.back().find(key); data != scopes_.back().end()) + return data->second; + return nullptr; + } + + template <typename Key, typename Data> + Data scoped_map<Key, Data>::get(const Key& key) const + requires(!std::is_pointer_v<Data>) + { + if (auto data = scopes_.back().find(key); data != scopes_.back().end()) + return data->second; + throw std::range_error("Key is not in scope."); + } + + template <typename Key, typename Data> + std::ostream& scoped_map<Key, Data>::dump(std::ostream& ostr) const + { + ostr << "Printing\n"; + const char* sep = "-------------------------\n"; + int depth = 0; + for (auto scope : scopes_) + { + ostr << sep << "Scope " << depth++ << incendl; + for (auto kvp : scope) + { + ostr << kvp.first << " -> " << kvp.second << iendl; + } + ostr << decendl << sep; + } + ostr << "endprint\n"; + return ostr; + } + template <typename Key, typename Data> + void scoped_map<Key, Data>::scope_begin() + { + std::map<Key, Data> new_scope; + for (auto kvp : scopes_.back()) + { + new_scope.insert_or_assign(kvp.first, kvp.second); + } + scopes_.push_back(new_scope); + } + template <typename Key, typename Data> void scoped_map<Key, Data>::scope_end() + { + scopes_.pop_back(); + } + + template <typename Key, typename Data> + inline std::ostream& operator<<(std::ostream& ostr, + const scoped_map<Key, Data>& tbl) + { + return tbl.dump(ostr); + } + +} // namespace misc |
