summaryrefslogtreecommitdiff
path: root/uswipl.c
blob: 1c925150469a0db6990f675aecba647f6f9a7b83 (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
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <SWI-Prolog.h>

int main(int argc, char **argv)
{
	char        *input;
	size_t       input_size;
	ssize_t      input_len;
	char        *output;
	term_t       term;
	predicate_t  pred;
	qid_t        query;

	if (!PL_initialise(argc, argv))
		return EXIT_FAILURE;

	input = NULL;
	while (errno = 0, (input_len = getline(&input, &input_size, stdin)) != -1) {
		switch (input[0]) {
			case '!':
				if ((term = PL_new_term_ref()) == (term_t)0)
					return EXIT_FAILURE;

				if (PL_put_term_from_chars(term, REP_UTF8 | CVT_EXCEPTION, -1, &input[1]) == FALSE)
					return EXIT_FAILURE;

				if (PL_assert(term, NULL, PL_ASSERTZ) == FALSE)
					return EXIT_FAILURE;

				break;

			case '?':
				input[input_len - 1] = '\0';
				if ((pred = PL_predicate(&input[1], 1, NULL)) == (predicate_t)0)
					return EXIT_FAILURE;

				if ((term = PL_new_term_ref()) == (term_t)0)
					return EXIT_FAILURE;

				query = PL_open_query(NULL, PL_Q_NODEBUG, pred, term);
				while (PL_next_solution(query) == TRUE) {
					if (PL_get_chars(term, &output, CVT_ALL | CVT_VARIABLE | CVT_EXCEPTION | BUF_MALLOC | REP_UTF8) == FALSE)
						return EXIT_FAILURE;
					puts(output);
					PL_free(output);
				}
				PL_close_query(query);

				break;

			default:
				fputs("Unexpected input\n", stderr);
				return EXIT_FAILURE;
		}
	}

	free(input);

	if (errno) {
		perror("Failed to read line from standard input");
		return EXIT_FAILURE;
	}

	return EXIT_SUCCESS;
}