shithub: pprolog

ref: baea4aa939861fd4efbc71b96f93ba890f01ac40
dir: /builtins.c/

View raw version
#include <u.h>
#include <libc.h>

#include "dat.h"
#include "fns.h"

int builtinfail(Term *, Term *, Goal **, Choicepoint **, Binding **);
int builtincall(Term *, Term *, Goal **, Choicepoint **, Binding **);
int builtincut(Term *, Term *, Goal **, Choicepoint **, Binding **);

Builtin
findbuiltin(Term *goal)
{
	int arity;
	Rune *name;

	switch(goal->tag){
	case AtomTerm:
		arity = 0;
		name = goal->text;
		break;
	case CompoundTerm:
		arity = goal->arity;
		name = goal->text;
		break;
	default:
		return nil;
	}

	if(!runestrcmp(name, L"fail") && arity == 0)
		return builtinfail;
	if(!runestrcmp(name, L"call") && arity == 1)
		return builtincall;
	if(!runestrcmp(name, L"!") && arity == 0)
		return builtincut;

	return nil;
}

int
builtinfail(Term *database, Term *goal, Goal **goals, Choicepoint **choicestack, Binding **bindings)
{
	USED(database);
	USED(goal);
	USED(goals);
	USED(choicestack);
	USED(bindings);
	return 0;
}

int
builtincall(Term *database, Term *goal, Goal **goals, Choicepoint **choicestack, Binding **bindings)
{
	USED(database);
	USED(choicestack);
	USED(bindings);

	Goal *g = malloc(sizeof(Goal));
	g->goal = goal->children;
	g->next = *goals;
	*goals = g;

	return 1;
}

int
builtincut(Term *database, Term *goal, Goal **goals, Choicepoint **choicestack, Binding **bindings)
{
	USED(database);
	USED(goals);
	USED(bindings);

	Choicepoint *cp = *choicestack;

	/* Cut all choicepoints with an id larger or equal to the goal clause number, since they must have been introduced
	   after this goal's parent.
	*/
	while(cp != nil && cp->id >= goal->clausenr)
		cp = cp->next;
	*choicestack = cp;
	return 1;
}