Spicy
unit-context.h
1 // Copyright (c) 2020-2021 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, UserException)
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  return UnitContext(std::move(ctx), ti);
78 }
79 
89 template<typename Context>
90 inline void setContext(hilti::rt::StrongReference<Context>& context, const std::optional<UnitContext>& new_ctx,
91  const hilti::rt::TypeInfo* ti) {
92  if ( new_ctx )
93  context = new_ctx->as<Context>(ti);
94  else
95  context = nullptr;
96 }
97 
98 } // namespace detail
99 
100 } // namespace spicy::rt
const char * display
Definition: type-info.h:1148
Definition: optional.h:79
hilti::rt::StrongReference< Context > as(const hilti::rt::TypeInfo *ti) const
Definition: unit-context.h:46
Definition: reference.h:328
Definition: unit-context.h:28
UnitContext(hilti::rt::StrongReference< T > obj, const hilti::rt::TypeInfo *ti)
Definition: unit-context.h:37
Definition: type-info.h:1146
std::string fmt(const char *fmt, const Args &... args)
Definition: fmt.h:13