Spicy
unit-context.h
1 // Copyright (c) 2020-now by the Zeek Project. See LICENSE for details.
2 
3 #pragma once
4 
5 #include <cassert>
6 #include <string>
7 #include <utility>
8 
9 #include <hilti/rt/exception.h>
10 #include <hilti/rt/type-info.h>
11 #include <hilti/rt/types/reference.h>
12 
13 namespace spicy::rt {
14 
19 HILTI_EXCEPTION(ContextMismatch, UsageError)
20 
21 
28 class UnitContext {
29 public:
36  template<typename T>
38  : _object(std::move(obj)), _type_info(ti) {}
45  template<typename Context>
47  if ( ti != _type_info )
48  throw ContextMismatch(hilti::rt::fmt("context mismatch between related units: expected %s, but got %s",
49  _type_info->display, ti->display));
50 
51  return hilti::rt::any_cast<hilti::rt::StrongReference<Context>>(_object);
52  }
53 
54  UnitContext() = delete;
55  UnitContext(const UnitContext&) = default;
56  UnitContext(UnitContext&&) = default;
57 
58  UnitContext& operator=(const UnitContext&) = default;
59  UnitContext& operator=(UnitContext&&) = default;
60 
61  virtual ~UnitContext(); // trigger vtable
62 private:
63  hilti::rt::any _object;
64  const hilti::rt::TypeInfo* _type_info;
65 };
66 
67 namespace detail {
68 
75 template<typename Context>
76 inline UnitContext createContext(Context ctx, const hilti::rt::TypeInfo* ti) {
77  if ( ti->tag == hilti::rt::TypeInfo::Tag::StrongReference )
78  ti = ti->strong_reference->valueType();
79 
80  return UnitContext(std::move(ctx), ti);
81 }
82 
92 template<typename Context>
93 inline void setContext(hilti::rt::StrongReference<Context>& context, const hilti::rt::TypeInfo* context_type,
94  const std::optional<UnitContext>& new_ctx, const hilti::rt::TypeInfo* ti) {
95  if ( new_ctx )
96  context = new_ctx->as<Context>(ti);
97  else
98  context = nullptr;
99 }
100 
101 } // namespace detail
102 
103 } // namespace spicy::rt
104 
105 namespace hilti::rt::detail::adl {
106 
107 inline std::string to_string(const spicy::rt::UnitContext& ctx, rt::detail::adl::tag /*unused*/) {
108  return "<unit context>";
109 }
110 
111 } // namespace hilti::rt::detail::adl
Definition: reference.h:376
const TypeInfo * valueType() const
Definition: type-info.h:206
Definition: unit-context.h:28
UnitContext(hilti::rt::StrongReference< T > obj, const hilti::rt::TypeInfo *ti)
Definition: unit-context.h:37
hilti::rt::StrongReference< Context > as(const hilti::rt::TypeInfo *ti) const
Definition: unit-context.h:46
std::string fmt(const char *fmt, const Args &... args)
Definition: fmt.h:13
std::string to_string(T &&x)
Definition: extension-points.h:26
Definition: type-info.h:1273
const char * display
Definition: type-info.h:1275
Tag tag
Tag indicating which field of below union is set.
Definition: type-info.h:1333