ref: 33ccfecf295bb8a0d44e3622e43242d30376e951
parent: b415245da5d38ce56bd3831eecc2d679db9fc231
author: Roberto E. Vargas Caballero <[email protected]>
date: Tue Aug 21 20:42:30 EDT 2012
Print the tree with pretty indent If the tree is printed using indent, then reading code will be easier, so I will catch faster the problems, and all the people will be happiest.
--- a/tree.c
+++ b/tree.c
@@ -41,6 +41,10 @@
struct node **body;
};
+
+static unsigned char indent; /* used for pretty printing the tree*/
+
+
struct node *
nodesym(struct symbol *sym)
{
@@ -120,8 +124,8 @@
return p;
}
-void
-prtree(register struct node *np)
+static void
+prtree_helper(register struct node *np)
{
static struct optab {
unsigned char nchild;
@@ -175,29 +179,34 @@
[OCOMP] = {255, "comp"},
[OSWITCH] = {2, "switch"}
};
-
assert(np && np->op < ARRAY_SIZE(optab));
bp = &optab[np->op];
- if (bp->nchild)
- printf("(%s ", bp->txt);
-
+ if (bp->nchild) {
+ register unsigned char i;
+ putchar('\n');
+ for (i = indent; i != 0; --i)
+ putchar(' ');
+ printf("(%s", bp->txt);
+ indent += 2;
+ }
switch (bp->nchild) {
case 0: {
register struct symbol *sym = ((struct node_sym *) np)->sym;
- printf(" %s", (sym->name) ? sym->name : ".");
+ putchar(' ');
+ fputs((sym->name) ? sym->name : ".", stdout);
return;
}
case 1:
- prtree(((struct node_op1 *) np)->infix);
+ prtree_helper(((struct node_op1 *) np)->infix);
break;
case 2:
- prtree(((struct node_op2 *) np)->left);
- prtree(((struct node_op2 *) np)->rigth);
+ prtree_helper(((struct node_op2 *) np)->left);
+ prtree_helper(((struct node_op2 *) np)->rigth);
break;
case 3:
- prtree(((struct node_op3 *) np)->left);
- prtree(((struct node_op3 *) np)->infix);
- prtree(((struct node_op3 *) np)->rigth);
+ prtree_helper(((struct node_op3 *) np)->left);
+ prtree_helper(((struct node_op3 *) np)->infix);
+ prtree_helper(((struct node_op3 *) np)->rigth);
break;
case 255: {
register struct node **bp, **lim;
@@ -205,9 +214,17 @@
bp = ((struct node_comp *) np)->body;
lim = bp + ((struct node_comp *) np)->nr;
while (bp < lim)
- prtree(*bp++);
+ prtree_helper(*bp++);
break;
}
}
putchar(')');
+ indent -= 2;
+}
+
+void
+prtree(register struct node *np)
+{
+ indent = 0;
+ prtree_helper(np);
}