shithub: pprolog

ref: 9799fbd9e8c7fd186365c628bf2024d458dafc75
dir: /prettyprint.c/

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

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

Rune *prettyprintlist(Term *, Rune *, int);

Rune *
prettyprint(Term *t)
{
	Rune *result;
	Rune *args;

	switch(t->tag){
	case CompoundTerm:
		args = prettyprintlist(t->children, L", ", 0);
		result = runesmprint("%S(%S)", t->text, args);
		free(args);
		break;
	case AtomTerm:
	case VariableTerm:
		result = runesmprint("%S", t->text);
		break;
	case NumberTerm:
		if(t->numbertype == NumberInt)
			result = runesmprint("%lld", t->ival);
		else
			result = runesmprint("%f", t->dval);
		break;
	default:
		result = runesmprint("cant print term with tag %d", t->tag);
		break;
	}

	return result;
}

Rune *
prettyprintlist(Term *t, Rune *sep, int end)
{
	if(t == nil){
		if(end)
			return runesmprint("%S", sep);
		else
			return runesmprint("");
	}

	Rune *str = prettyprint(t);
	Rune *rest = prettyprintlist(t->next, sep, end);
	Rune *result;

	if(t->next != nil)
		result = runesmprint("%S%S%S", str, sep, rest);
	else
		result = runesmprint("%S%S", str, end ? rest : L"");

	free(str);
	free(rest);
	return result;
}