scc

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

node.c (1693B)


      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->left)
     37 		prnode(np->left);
     38 	if (np->right)
     39 		prnode(np->right);
     40 	fprintf(stderr, "\t%c%lu", np->op, np->type.size);
     41 }
     42 
     43 void
     44 prtree(Node *np)
     45 {
     46 	prnode(np);
     47 	putc('\n', stderr);
     48 }
     49 
     50 void
     51 prforest(char *msg)
     52 {
     53 	Node *np;
     54 
     55 	if (!curfun)
     56 		return;
     57 
     58 	fprintf(stderr, "%s {\n", msg);
     59 	for (np = curfun->u.stmt; np; np = np->next)
     60 		prtree(np);
     61 	fputs("}\n", stderr);
     62 }
     63 #endif
     64 
     65 Node *
     66 addstmt(Node *np, int flag)
     67 {
     68 	if (curstmt)
     69 		np->next = curstmt->next;
     70 	np->prev = curstmt;
     71 
     72 	if (!curfun->u.stmt)
     73 		curfun->u.stmt = np;
     74 	else
     75 		curstmt->next = np;
     76 
     77 	if (flag == SETCUR)
     78 		curstmt = np;
     79 
     80 	return np;
     81 }
     82 
     83 Node *
     84 delstmt(void)
     85 {
     86 	Node *next, *prev;
     87 
     88 	next = curstmt->next;
     89 	prev = curstmt->prev;
     90 	if (next)
     91 		next->prev = prev;
     92 	if (prev)
     93 		prev->next = next;
     94 	else
     95 		curfun->u.stmt = next;
     96 	deltree(curstmt);
     97 
     98 	return curstmt = next;
     99 }
    100 
    101 Node *
    102 nextstmt(void)
    103 {
    104 	return curstmt = curstmt->next;
    105 }
    106 
    107 void
    108 delnode(Node *np)
    109 {
    110 	delete(arena, np);
    111 }
    112 
    113 void
    114 deltree(Node *np)
    115 {
    116 	if (!np)
    117 		return;
    118 	deltree(np->left);
    119 	deltree(np->right);
    120 	delnode(np);
    121 }
    122 
    123 void
    124 cleannodes(void)
    125 {
    126 	if (arena) {
    127 		dealloc(arena);
    128 		arena = NULL;
    129 	}
    130 	curstmt = NULL;
    131 }
    132 
    133 void
    134 apply(Node *(*fun)(Node *))
    135 {
    136 	if (!curfun)
    137 		return;
    138 	curstmt = curfun->u.stmt;
    139 	while (curstmt)
    140 		(*fun)(curstmt) ? nextstmt() : delstmt();
    141 }