aboutsummaryrefslogtreecommitdiff
path: root/c/pl.cpp
blob: a1849dbf208ca2f2d8407e3951a4f56253c95f61 (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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <windows.h>
#include <SWI-Prolog.h>

#include "pl.h"

/* Frame: Wrapper for opening and closing Prolog foreign frames. */

Frame::Frame()
{
	m_f = PL_open_foreign_frame();
}

Frame::~Frame()
{
	PL_close_foreign_frame(m_f);
}

void Frame::Close()
{
	PL_close_foreign_frame(m_f);
}

/* Close foreign frame and invalidate associated data. */
void Frame::Discard()
{
	PL_discard_foreign_frame(m_f);
}

void Frame::Rewind()
{
	PL_rewind_foreign_frame(m_f);
}

/* Mark: Wrapper for marking and releasing strings on the Prolog stack. */

Mark::Mark()
{
	PL_mark_string_buffers(&m_m);
}

Mark::~Mark()
{
	PL_release_string_buffers_from_mark(m_m);
}

/* Query: Wrapper for opening, solving and cutting Prolog query. */

Query::Query(const module_t ctx, const predicate_t p, const term_t t0)
{
	m_q = PL_open_query(ctx, PL_Q_CATCH_EXCEPTION, p, t0);
}

Query::~Query()
{
	PL_cut_query(m_q);
}

int Query::Cut()
{
	if (PL_cut_query(m_q)) return 1;
	if (const term_t t = PL_exception(m_q)) throw t;
	return 0;
}

/* Cut query and invalidate associated data. */
int Query::Close()
{
	if (PL_close_query(m_q)) return 1;
	if (const term_t t = PL_exception(m_q)) throw t;
	return 0;
}

int Query::NextSolution()
{
	if (PL_next_solution(m_q)) return 1;
	if (const term_t t = PL_exception(m_q)) throw t;
	return 0;
}

/* Convert Prolog term to normal or wide characters. */
template <>
int PlString<char>(const term_t t, std::string* const pStr, const int iFlags)
{
	char* sz;
	int r = PL_get_chars(t, &sz, iFlags);
	if (r) *pStr = sz;
	return r;
}

template <>
int PlString<wchar_t>(const term_t t, std::wstring* const pWstr, const int iFlags)
{
	char* sz;
	int r = PL_get_chars(t, &sz, iFlags);
	if (r) *pWstr = BstrFromSz<wchar_t>(sz);
	return r;
}