A Hugo incarnation of the blog.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

type.hpp 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #pragma once
  2. #include <memory>
  3. #include <map>
  4. #include <string>
  5. #include <vector>
  6. #include <set>
  7. struct type_mgr;
  8. struct type {
  9. virtual ~type() = default;
  10. virtual void print(const type_mgr& mgr, std::ostream& to) const = 0;
  11. };
  12. using type_ptr = std::shared_ptr<type>;
  13. struct type_scheme {
  14. std::vector<std::string> forall;
  15. type_ptr monotype;
  16. type_scheme(type_ptr type) : forall(), monotype(std::move(type)) {}
  17. void print(const type_mgr& mgr, std::ostream& to) const;
  18. type_ptr instantiate(type_mgr& mgr) const;
  19. };
  20. using type_scheme_ptr = std::shared_ptr<type_scheme>;
  21. struct type_var : public type {
  22. std::string name;
  23. type_var(std::string n)
  24. : name(std::move(n)) {}
  25. void print(const type_mgr& mgr, std::ostream& to) const;
  26. };
  27. struct type_base : public type {
  28. std::string name;
  29. int32_t arity;
  30. type_base(std::string n, int32_t a = 0)
  31. : name(std::move(n)), arity(a) {}
  32. void print(const type_mgr& mgr, std::ostream& to) const;
  33. };
  34. struct type_data : public type_base {
  35. struct constructor {
  36. int tag;
  37. };
  38. std::map<std::string, constructor> constructors;
  39. type_data(std::string n, int32_t a = 0)
  40. : type_base(std::move(n), a) {}
  41. };
  42. struct type_arr : public type {
  43. type_ptr left;
  44. type_ptr right;
  45. type_arr(type_ptr l, type_ptr r)
  46. : left(std::move(l)), right(std::move(r)) {}
  47. void print(const type_mgr& mgr, std::ostream& to) const;
  48. };
  49. struct type_app : public type {
  50. type_ptr constructor;
  51. std::vector<type_ptr> arguments;
  52. type_app(type_ptr c)
  53. : constructor(std::move(c)) {}
  54. void print(const type_mgr& mgr, std::ostream& to) const;
  55. };
  56. struct type_mgr {
  57. int last_id = 0;
  58. std::map<std::string, type_ptr> types;
  59. std::string new_type_name();
  60. type_ptr new_type();
  61. type_ptr new_arrow_type();
  62. void unify(type_ptr l, type_ptr r);
  63. type_ptr substitute(
  64. const std::map<std::string, type_ptr>& subst,
  65. const type_ptr& t) const;
  66. type_ptr resolve(type_ptr t, type_var*& var) const;
  67. void bind(const std::string& s, type_ptr t);
  68. void find_free(const type_ptr& t, std::set<std::string>& into) const;
  69. };