Παράσταση του συντακτικού δένδρου

Παράδειγμα ορισμού (tree.h)

/*
 * Tree type and building function declarations
 *
 * D. Spinellis, November 1999
 *
 * $Id: tree.h 1.1 1999/11/09 23:32:12 dds Exp $
 *
 */

enum e_nodetype {
        ent_binop,                              /* Binary operator expr */
        ent_unop,                               /* Unary operator expr */
        ent_digit                               /* Digit expr */
};

struct s_tree {
        enum e_nodetype nt;                     /* Expression type */
        union {
                struct s_binop {
                        struct s_tree *left, *right;
                        char op;
                } binop;                        /* Binary operator expr */
                struct s_unary {
                        struct s_tree *expr;
                        char op;
                } unop;                         /* Unary operator expr */
                int digit;                      /* Digit expression */
        } u;
};


struct s_tree * mk_binop(struct s_tree *left, char op, struct s_tree *right);
struct s_tree * mk_unop(char op, struct s_tree *expr);
struct s_tree * mk_digit(char c);

Παράδειγμα συναρτήσεων δημιουργία και εκτύπωσης (tree.c)

/*
 * Tree building functions
 *
 * D. Spinellis, November 1999
 *
 * $Id: tree.c 1.2 1999/11/10 09:15:35 dds Exp $
 *
 */

#include <stdlib.h>
#include "tree.h"

struct s_tree *
mk_binop(struct s_tree *left, char op, struct s_tree *right)
{
        struct s_tree *t = malloc(sizeof(struct s_tree));

        t->nt = ent_binop;
        t->u.binop.left = left;
        t->u.binop.op = op;
        t->u.binop.right = right;
        return (t);
}

struct s_tree *
mk_unop(char op, struct s_tree *expr)
{
        struct s_tree *t = malloc(sizeof(struct s_tree));

        t->nt = ent_unop;
        t->u.unop.op = op;
        t->u.unop.expr = expr;
        return (t);
}

struct s_tree *
mk_digit(char c)
{
        struct s_tree *t = malloc(sizeof(struct s_tree));

        t->nt = ent_digit;
        t->u.digit = c -'0';
        return (t);
}

/*
 * Indent output by the indent ammount given
 */
static void
indent(int level)
{
        int i;

        for (i = 0; i < level; i++)
                printf("    ");
}

/*
 * Dump an expression tree to the standard output
 */
void
dumptree(struct s_tree *t)
{
        static int il = 0;              /* Indent level */

        il++;
        switch (t->nt) {
        case ent_binop:
                dumptree(t->u.binop.left);
                indent(il); printf("%c\n", t->u.binop.op);
                dumptree(t->u.binop.right);
                break;
        case ent_unop:
                indent(il); printf("%c\n", t->u.unop.op);
                dumptree(t->u.unop.expr);
                break;
        case ent_digit:
                indent(il); printf("%d\n", t->u.digit);
                break;
        }
        il--;
}