scc

Simple C99 Compiler
Log | Files | Refs | README | LICENSE

node.c (1710B)


      1 /* See LICENSE file for copyright and license details. */
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 #include "../inc/cc.h"
      6 
      7 #include "arch.h"
      8 #include "cc2.h"
      9 
     10 #define NNODES   32
     11 
     12 Node *curstmt;
     13 Symbol *curfun;
     14 
     15 struct arena {
     16 	Node *mem;
     17 	struct arena *next;
     18 };
     19 
     20 static struct arena *arena;
     21 static Node *freep;
     22 
     23 Node *
     24 newnode(int op)
     25 {
     26 	struct arena *ap;
     27 	Node *np;
     28 
     29 	if (!freep) {
     30 		ap = xmalloc(sizeof(*ap));
     31 		ap->mem = xcalloc(NNODES, sizeof(Node));
     32 		ap->next = arena;
     33 		arena = ap;
     34 		for (np = ap->mem; np < &ap->mem[NNODES-1]; ++np)
     35 			np->left = np+1;
     36 		np->left = NULL;
     37 		freep = np;
     38 	}
     39 
     40 	np = freep;
     41 	freep = np->left;
     42 
     43 	memset(np, 0, sizeof(*np));
     44 	np->op = op;
     45 
     46 	return np;
     47 }
     48 
     49 Node *
     50 addstmt(Node *np, int flag)
     51 {
     52 	if (curstmt)
     53 		np->next = curstmt->next;
     54 	np->prev = curstmt;
     55 
     56 	if (!curfun->u.stmt)
     57 		curfun->u.stmt = np;
     58 	else
     59 		curstmt->next = np;
     60 
     61 	if (flag == SETCUR)
     62 		curstmt = np;
     63 
     64 	return np;
     65 }
     66 
     67 Node *
     68 delstmt(void)
     69 {
     70 	Node *next, *prev;
     71 
     72 	next = curstmt->next;
     73 	prev = curstmt->prev;
     74 	if (next)
     75 		next->prev = prev;
     76 	if (prev)
     77 		prev->next = next;
     78 	else
     79 		curfun->u.stmt = next;
     80 	deltree(curstmt);
     81 
     82 	return curstmt = next;
     83 }
     84 
     85 Node *
     86 nextstmt(void)
     87 {
     88 	return curstmt = curstmt->next;
     89 }
     90 
     91 void
     92 delnode(Node *np)
     93 {
     94 	np->left = freep;
     95 	freep = np;
     96 }
     97 
     98 void
     99 deltree(Node *np)
    100 {
    101 	if (!np)
    102 		return;
    103 	deltree(np->left);
    104 	deltree(np->right);
    105 	delnode(np);
    106 }
    107 
    108 void
    109 cleannodes(void)
    110 {
    111 	struct arena *ap, *next;
    112 
    113 	for (ap = arena; ap; ap = next) {
    114 		next = ap->next;
    115 		free(ap->mem);
    116 		free(ap);
    117 	}
    118 	arena = NULL;
    119 	freep = NULL;
    120 	curstmt = NULL;
    121 }
    122 
    123 void
    124 apply(Node *(*fun)(Node *))
    125 {
    126 	if (!curfun)
    127 		return;
    128 	curstmt = curfun->u.stmt;
    129 	while (curstmt)
    130 		(*fun)(curstmt) ? nextstmt() : delstmt();
    131 }