shithub: pprolog

ref: 901224d36c3f488e4118a1fd804da2b3372d8ed6
dir: /misc.c/

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

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

Term *
copyterm(Term *orig, uvlong *clausenr)
{
	Term *new = gmalloc(sizeof(Term));
	memcpy(new, orig, sizeof(Term));
	new->next = nil;
	new->children = nil;

	if(clausenr)
		new->clausenr = *clausenr;
	else
		new->clausenr = orig->clausenr;

	Term *child;
	for(child = orig->children; child != nil; child = child->next)
		new->children = appendterm(new->children, copyterm(child, clausenr));
	return new;
}

Term *
appendterm(Term *a, Term *b)
{
	if(a == nil)
		return b;

	Term *tmp;
	for(tmp = a; tmp->next != nil; tmp = tmp->next);
	tmp->next = b;
	return a;
}

int
termslength(Term *list)
{
	int len;
	for(len = 0; list != nil; len++, list = list->next);
	return len;
}

Term *
mkterm(int tag)
{
	Term *t = gmalloc(sizeof(Term));
	t->tag = tag;
	t->next = nil;
	t->children = nil;
	t->text = nil;
	t->clausenr = 0;
	t->inparens = 0;
	return t;
}

Term *
mkatom(Rune *name)
{
	Term *t = mkterm(AtomTerm);
	t->text = name;
	return t;
}

Term *
mkvariable(Rune *name)
{
	Term *t = mkterm(VariableTerm);
	t->text = name;
	return t;
}

Term *
mkcompound(Rune *name, int arity, Term *args)
{
	Term *t = mkterm(CompoundTerm);
	t->text = name;
	t->arity = arity;
	t->children = args;
	return t;
}

Term *
mkfloat(double dval)
{
	Term *t = mkterm(FloatTerm);
	t->dval = dval;
	return t;
}

Term *
mkinteger(vlong ival)
{
	Term *t = mkterm(IntegerTerm);
	t->ival = ival;
	return t;
}

Term *
mkstring(Rune *text)
{
	Term *t = nil;
	Rune *r;

	switch(flagdoublequotes){
	case DoubleQuotesChars:
		for(r = text; *r != '\0'; r++){
			Rune *chtext = runesmprint("%C", *r);
			Term *ch = mkatom(chtext);
			t = appendterm(t, ch);
		}
		t = mklist(t);
		break;
	case DoubleQuotesCodes:
		for(r = text; *r != '\0'; r++){
			Term *code = mkinteger(*r);
			t = appendterm(t, code);
		}
		t = mklist(t);
		break;
		break;
	case DoubleQuotesAtom:
		t = mkatom(text);
	}
	return t;
}

Term *
mklist(Term *elems)
{
	if(elems == nil)
		return mkatom(L"[]");
	else{
		Term *t = copyterm(elems, nil);
		t->next = mklist(elems->next);
		return mkcompound(L".", 2, t);
	}
}

Clause *
copyclause(Clause *orig, uvlong *clausenr)
{
	Clause *new = gmalloc(sizeof(Clause));
	new->head = copyterm(orig->head, clausenr);
	if(orig->body)
		new->body = copyterm(orig->body, clausenr);
	else
		new->body = nil;
	if(clausenr)
		new->clausenr = *clausenr;
	else
		new->clausenr = orig->clausenr;
	new->next = nil;
	return new;
}