aboutsummaryrefslogtreecommitdiff
path: root/c/pl.c
blob: acb6ba3e5685d82b2eca9703a2746b3269063663 (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdarg.h>
#include <string.h>
#include <SWI-Prolog.h>
#include "defs.h"

static int Plpv(term_t, char *, va_list);
static int Plgv(term_t, char *, va_list);

/* Call Prolog predicate once. */
int
Pl(char *szMod, char *szPred, char *szFmt, ...)
{
	int iArity;
	term_t t;
	va_list vl, vl2;

	iArity = strlen(szFmt);
	t = PL_new_term_refs(iArity);

	va_start(vl, szFmt);
	va_copy(vl2, vl);

	if (!Plpv(t, szFmt, vl)) goto f;
	if (!PL_call_predicate(NULL, PL_Q_NORMAL,
		PL_predicate(szPred, iArity, szMod), t))
		goto f;
	if (!Plgv(t, szFmt, vl2)) goto f;

	va_end(vl);
	va_end(vl2);
	return 1;
f:	va_end(vl);
	va_end(vl2);
	return 0;
}

/* Put known values in term. */
int
Plp(term_t t, char *szFmt, ...)
{
	int r;
	va_list vl;
	va_start(vl, szFmt);
	r = Plpv(t, szFmt, vl);
	va_end(vl);
	return r;
}
int
Plpv(term_t t, char *szFmt, va_list vl)
{
	int i;
	for (i = 0; szFmt[i]; i++) {
		switch (szFmt[i]) {
		case 'I':
		    {
			int x;
			x = va_arg(vl, int);
			if (!PL_put_integer(t+i, x)) return 0;
			break;
		    }
		case 'S':
		    {
			atom_t a;
			char *x;
			x = va_arg(vl, char *);
			a = PL_new_atom(x);
			if (!PL_put_atom(t+i, a)) return 0;
			break;
		    }
		case 'i':
			va_arg(vl, int *);
			break;
		case 's':
			va_arg(vl, char **);
			break;
		}
	}
	return 1;
}

/* Get unknown values from term. */
int
Plg(term_t t, char *szFmt, ...)
{
	int r;
	va_list vl;
	va_start(vl, szFmt);
	r = Plgv(t, szFmt, vl);
	va_end(vl);
	return r;
}
int
Plgv(term_t t, char *szFmt, va_list vl)
{
	int i;
	for (i = 0; szFmt[i]; i++) {
		switch (szFmt[i]) {
		case 'i':
		    {
			int *lp;
			lp = va_arg(vl, int *);
			if (!PL_get_integer(t+i, lp)) return 0;
			break;
		    }
		case 's':
		    {
			char **lp;
			lp = va_arg(vl, char **);
			if (!PL_get_atom_chars(t+i, lp)) return 0;
			break;
		    }
		case 'I':
			va_arg(vl, int);
			break;
		case 'S':
			va_arg(vl, char *);
			break;
		}
	}
	return 1;
}