ref: 44ab8a339c78bcc3460d44b2f435116f21faa60a
dir: /prettyprint.c/
#include <u.h> #include <libc.h> #include <bio.h> #include "dat.h" #include "fns.h" Rune *prettyprintlist(Term *, Rune *, int, int, int, int); Rune *printlist(Term *, int, int, int); int islist(Term *); Rune * prettyprint(Term *t, int quoted, int ignoreops, int numbervars) { Rune *result; Rune *args; switch(t->tag){ case CompoundTerm: args = printlist(t, quoted, ignoreops, numbervars); if(args == nil){ args = prettyprintlist(t->children, L", ", 0, quoted, ignoreops, numbervars); result = runesmprint("%S(%S)", t->text, args); free(args); }else result = runesmprint("[%S]", args); break; case AtomTerm: result = runesmprint("%S", t->text); break; case VariableTerm: result = runesmprint("%S(%ulld)", t->text, t->clausenr); 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, int quoted, int ignoreops, int numbervars) { if(t == nil){ if(end) return runesmprint("%S", sep); else return runesmprint(""); } Rune *str = prettyprint(t, quoted, ignoreops, numbervars); Rune *rest = prettyprintlist(t->next, sep, end, quoted, ignoreops, numbervars); 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; } /* printlist prints a list's elements but not the surrounding [ and ] */ Rune * printlist(Term *list, int quoted, int ignoreops, int numbervars) { if(list->tag != CompoundTerm || list->arity != 2 || runestrcmp(L".", list->text) != 0) return nil; Term *head = list->children; Term *tail = head->next; Rune *headstr = prettyprint(head, quoted, ignoreops, numbervars); Rune *tailstr = nil; Rune *result; if(tail->tag == CompoundTerm && tail->arity == 2 && runestrcmp(L".", tail->text) == 0){ tailstr = printlist(tail, quoted, ignoreops, numbervars); result = runesmprint("%S, %S", headstr, tailstr); }else if(tail->tag == AtomTerm && runestrcmp(L"[]", tail->text) == 0){ result = runesmprint("%S", headstr); }else{ tailstr = prettyprint(tail, quoted, ignoreops, numbervars); result = runesmprint("%S | %S", headstr, tailstr); } free(headstr); free(tailstr); return result; }