--- ray/src/common/calprnt.c 2003/02/25 02:47:21 2.3 +++ ray/src/common/calprnt.c 2024/02/24 19:00:23 2.9 @@ -1,5 +1,5 @@ #ifndef lint -static const char RCSid[] = "$Id: calprnt.c,v 2.3 2003/02/25 02:47:21 greg Exp $"; +static const char RCSid[] = "$Id: calprnt.c,v 2.9 2024/02/24 19:00:23 greg Exp $"; #endif /* * calprint.c - routines for printing calcomp expressions. @@ -8,19 +8,43 @@ static const char RCSid[] = "$Id: calprnt.c,v 2.3 2003 #include "copyright.h" #include +#include +#include "rterror.h" #include "calcomp.h" +/* is child operation lower precedence than parent? */ +static int +lower_precedent_op(int typ, EPNODE *ek) +{ + if (ek == NULL) + return(0); + switch (typ) { + case '+': + return(0); + case '-': + return(ek->type == '+'); + case '*': + return(strchr("+-", ek->type) != NULL); + case '/': + return(strchr("+-*", ek->type) != NULL); + case '^': + return(strchr("+-*/^", ek->type) != NULL); + } + return(0); /* child not binary op */ +} + void -eprint(ep, fp) /* print a parse tree */ -register EPNODE *ep; -FILE *fp; +eprint( /* print a parse tree */ + EPNODE *ep, + FILE *fp +) { static EPNODE *curdef = NULL; - register EPNODE *ep1; + EPNODE *ep1 = NULL; - switch (ep->type) { + switch (ep==NULL ? -1 : ep->type) { case VAR: fputs(ep->v.ln->name, fp); @@ -55,11 +79,6 @@ FILE *fp; fprintf(fp, "%.9g", ep->v.num); break; - case UMINUS: - fputc('-', fp); - eprint(ep->v.kid, fp); - break; - case CHAN: fprintf(fp, "$%d", ep->v.chan); break; @@ -75,19 +94,42 @@ FILE *fp; eprint(ep->v.kid->sibling, fp); curdef = ep1; break; - + + case UMINUS: + fputc('-', fp); + if (ep->v.kid != NULL && strchr("+-*/^", ep->v.kid->type)) { + fputc('(', fp); + eprint(ep->v.kid, fp); + fputc(')', fp); + } else + eprint(ep->v.kid, fp); + break; + case '+': - case '-': case '*': + case '-': case '/': case '^': - fputc('(', fp); - eprint(ep->v.kid, fp); - fputc(' ', fp); - fputc(ep->type, fp); - fputc(' ', fp); - eprint(ep->v.kid->sibling, fp); - fputc(')', fp); + if (lower_precedent_op(ep->type, ep->v.kid)) { + fputc('(', fp); + eprint(ep->v.kid, fp); + fputc(')', fp); + } else + eprint(ep->v.kid, fp); + for (ep1 = ep->v.kid->sibling; ep1 != NULL; ep1 = ep1->sibling) { + if (ep->type != '^') { + fputc(' ', fp); + fputc(ep->type, fp); + fputc(' ', fp); + } else + fputc(ep->type, fp); + if (lower_precedent_op(ep->type, ep1)) { + fputc('(', fp); + eprint(ep1, fp); + fputc(')', fp); + } else + eprint(ep1, fp); + } break; default: @@ -95,16 +137,16 @@ FILE *fp; quit(1); } - } void -dprint(name, fp) /* print a definition (all if no name) */ -char *name; -FILE *fp; +dprint( /* print a definition (all if no name) */ + char *name, + FILE *fp +) { - register EPNODE *ep; + EPNODE *ep; if (name == NULL) for (ep = dfirst(); ep != NULL; ep = dnext()) {