summaryrefslogtreecommitdiff
path: root/tiger-compiler/lib/misc/scoped-map.hxx
blob: 14258b98d64af800a8e131f7b1b89e7794c4710f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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