summaryrefslogtreecommitdiff
path: root/starts/meaning-vm/concept.cpp
blob: 993ac6222480c47b6a0981ca77cd4d2148fc59a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "concept.hpp"

ref concept::id()
{
	return this;
}

bool concept::linked(ref const & type) const
{
	return links.count(type.ptr) > 0;
}

bool concept::linked(ref const & type, ref const & target) const
{
	for (ref const & t : getAll(type)) {
		if (t == target) {
			return true;
		}
	}
	return false;
}

ref concept::get(ref const & type, bool quick) const
{
	// this is called by name(), so it passes quick=true
	auto result = links.equal_range(type.ptr);
	if (result.first == result.second) {
		if (quick) {
			throw std::out_of_range("no such concept link to get");
		} else {
			throw std::out_of_range("no such concept link to get: " + (std::string)type.name());
		}
	}
	return result.first->second;
}

concept::array concept::getAll(ref const & type) const
{
	array ret;
	for (
		auto range = links.equal_range(type.ptr);
		range.first != range.second;
		++ range.first
	) { 
		ret.emplace_back(range.first->second);
	}
	return ret;
}

void concept::link(ref const & type, ref const & target)
{
	links.insert({type.ptr, target.ptr});
}

void concept::unlink(ref const & type, ref const & target)
{
	auto ls = links.equal_range(type.ptr);
	for (auto l = ls.first; l != ls.second; ++ l) {
		if (l->second == target.ptr) {
			links.erase(l);
			return;
		}
	}
	throw std::out_of_range("no such concept link to erase");
}

void concept::unlink(ref const & type)
{
	auto ls = links.equal_range(type.ptr);
	if (ls.first == ls.second) {
		throw std::out_of_range("no such concept link to erase");
	}
	auto mid = ls.first;
	++ mid;
	if (mid != ls.second) {
		throw std::out_of_range("more than one link of type to erase");
	}
	links.erase(ls.first);
}