PageRenderTime 55ms CodeModel.GetById 45ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/vm/tagged.hpp

http://github.com/abeaumont/factor
C++ Header | 85 lines | 68 code | 17 blank | 0 comment | 6 complexity | 362366ab1d089477e23dfb541a4d9880 MD5 | raw file
 1namespace factor
 2{
 3
 4template<typename Type> cell tag(Type *value)
 5{
 6	return RETAG(value,Type::type_number);
 7}
 8
 9inline static cell tag_dynamic(object *value)
10{
11	return RETAG(value,value->type());
12}
13
14template<typename Type>
15struct tagged
16{
17	cell value_;
18
19	cell type() const
20	{
21		return TAG(value_);
22	}
23
24	bool type_p(cell type_) const
25	{
26		return type() == type_;
27	}
28
29	bool type_p() const
30	{
31		if(Type::type_number == TYPE_COUNT)
32			return true;
33		else
34			return type_p(Type::type_number);
35	}
36
37	cell value() const
38	{
39#ifdef FACTOR_DEBUG
40		FACTOR_ASSERT(type_p());
41#endif
42		return value_;
43	}
44
45	Type *untagged() const
46	{
47#ifdef FACTOR_DEBUG
48		FACTOR_ASSERT(type_p());
49#endif
50		return (Type *)(UNTAG(value_));
51	}
52
53	Type *untag_check(factor_vm *parent) const
54	{
55		if(!type_p())
56			parent->type_error(Type::type_number,value_);
57		return untagged();
58	}
59
60	explicit tagged(cell tagged) : value_(tagged) {}
61	explicit tagged(Type *untagged) : value_(factor::tag(untagged)) {}
62
63	Type *operator->() const { return untagged(); }
64	cell *operator&() const { return &value_; }
65
66	const tagged<Type> &operator=(const Type *x) { value_ = tag(x); return *this; }
67	const tagged<Type> &operator=(const cell &x) { value_ = x; return *this; }
68
69	bool operator==(const tagged<Type> &x) { return value_ == x.value_; }
70	bool operator!=(const tagged<Type> &x) { return value_ != x.value_; }
71
72	template<typename NewType> tagged<NewType> as() { return tagged<NewType>(value_); }
73};
74
75template<typename Type> Type *factor_vm::untag_check(cell value)
76{
77	return tagged<Type>(value).untag_check(this);
78}
79
80template<typename Type> Type *untag(cell value)
81{
82	return tagged<Type>(value).untagged();
83}
84
85}