Spicy
spicy
runtime
include
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, UsageError)
20
21
28
class
UnitContext
{
29
public
:
36
template
<
typename
T>
37
UnitContext
(
hilti::rt::StrongReference<T>
obj,
const
hilti::rt::TypeInfo
* ti)
38
: _object(
std
::move(obj)), _type_info(ti) {}
45
template
<
typename
Context>
46
hilti::rt::StrongReference<Context>
as
(
const
hilti::rt::TypeInfo
* ti)
const
{
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
101
102
namespace
hilti::rt::detail::adl
{
103
104
inline
std::string to_string(
const
spicy::rt::UnitContext
& ctx, rt::detail::adl::tag
/*unused*/
) {
105
return
"<unit context>"
;
106
}
107
108
}
// namespace hilti::rt::detail::adl
hilti::rt::TypeInfo::display
const char * display
Definition:
type-info.h:1145
std
Definition:
optional.h:79
spicy::rt::UnitContext::as
hilti::rt::StrongReference< Context > as(const hilti::rt::TypeInfo *ti) const
Definition:
unit-context.h:46
hilti::rt::StrongReference
Definition:
reference.h:345
spicy::rt::UnitContext
Definition:
unit-context.h:28
spicy::rt
hilti::rt::detail::adl
Definition:
deferred-expression.h:41
spicy::rt::UnitContext::UnitContext
UnitContext(hilti::rt::StrongReference< T > obj, const hilti::rt::TypeInfo *ti)
Definition:
unit-context.h:37
hilti::rt::TypeInfo
Definition:
type-info.h:1143
hilti::rt::fmt
std::string fmt(const char *fmt, const Args &... args)
Definition:
fmt.h:13
Generated by
1.8.13