scc

simple c99 compiler
git clone git://git.simple-cc.org/scc
Log | Files | Refs | Submodules | README | LICENSE

node.c (1681B)


      1 #include <stdlib.h>
      2 #include <string.h>
      3 
      4 #include <scc/scc.h>
      5 
      6 #include "cc2.h"
      7 
      8 #define NNODES   32
      9 
     10 Node *curstmt;
     11 Symbol *curfun;
     12 
     13 static Alloc *arena;
     14 
     15 
     16 Node *
     17 node(int op)
     18 {
     19 	struct arena *ap;
     20 	Node *np;
     21 
     22 	if (!arena)
     23 		arena = alloc(sizeof(Node), NNODES);
     24 	np = memset(new(arena), 0, sizeof(*np));
     25 	np->op = op;
     26 
     27 	return np;
     28 }
     29 
     30 #ifndef NDEBUG
     31 #include <stdio.h>
     32 
     33 static void
     34 prnode(Node *np)
     35 {
     36 	if (!np)
     37 		return;
     38 	prnode(np->left);
     39 	prnode(np->right);
     40 
     41 	fprintf(stderr, "\t%c%lu", np->op, np->type.size);
     42 }
     43 
     44 void
     45 prtree(Node *np)
     46 {
     47 	prnode(np);
     48 	putc('\n', stderr);
     49 }
     50 
     51 void
     52 prforest(char *msg)
     53 {
     54 	Node *np;
     55 
     56 	if (!curfun)
     57 		return;
     58 
     59 	fprintf(stderr, "%s {\n", msg);
     60 	for (np = curfun->u.stmt; np; np = np->next)
     61 		prtree(np);
     62 	fputs("}\n", stderr);
     63 }
     64 #endif
     65 
     66 Node *
     67 addstmt(Node *np, int flag)
     68 {
     69 	if (curstmt)
     70 		np->next = curstmt->next;
     71 	np->prev = curstmt;
     72 
     73 	if (!curfun->u.stmt)
     74 		curfun->u.stmt = np;
     75 	else
     76 		curstmt->next = np;
     77 
     78 	if (flag == SETCUR)
     79 		curstmt = np;
     80 
     81 	return np;
     82 }
     83 
     84 Node *
     85 delstmt(void)
     86 {
     87 	Node *next, *prev;
     88 
     89 	next = curstmt->next;
     90 	prev = curstmt->prev;
     91 	if (next)
     92 		next->prev = prev;
     93 	if (prev)
     94 		prev->next = next;
     95 	else
     96 		curfun->u.stmt = next;
     97 	deltree(curstmt);
     98 
     99 	return curstmt = next;
    100 }
    101 
    102 Node *
    103 nextstmt(void)
    104 {
    105 	return curstmt = curstmt->next;
    106 }
    107 
    108 void
    109 delnode(Node *np)
    110 {
    111 	delete(arena, np);
    112 }
    113 
    114 void
    115 deltree(Node *np)
    116 {
    117 	if (!np)
    118 		return;
    119 	deltree(np->left);
    120 	deltree(np->right);
    121 	delnode(np);
    122 }
    123 
    124 void
    125 cleannodes(void)
    126 {
    127 	if (arena) {
    128 		dealloc(arena);
    129 		arena = NULL;
    130 	}
    131 	curstmt = NULL;
    132 }
    133 
    134 void
    135 apply(Node *(*fun)(Node *))
    136 {
    137 	if (!curfun)
    138 		return;
    139 	curstmt = curfun->u.stmt;
    140 	while (curstmt)
    141 		(*fun)(curstmt) ? nextstmt() : delstmt();
    142 }