scc

simple C compiler
git clone git://git.2f30.org/scc
Log | Files | Refs | README | LICENSE

node.c (1740B)


      1 static char sccsid[] = "@(#) ./cc2/node.c";
      2 #include <stdlib.h>
      3 #include <string.h>
      4 
      5 #include "../inc/scc.h"
      6 
      7 #include "cc2.h"
      8 
      9 #define NNODES   32
     10 
     11 Node *curstmt;
     12 Symbol *curfun;
     13 
     14 static Alloc *arena;
     15 
     16 
     17 Node *
     18 node(int op)
     19 {
     20 	struct arena *ap;
     21 	Node *np;
     22 
     23 	if (!arena)
     24 		arena = alloc(sizeof(Node), NNODES);
     25 	np = memset(new(arena), 0, sizeof(*np));
     26 	np->op = op;
     27 
     28 	return np;
     29 }
     30 
     31 #ifndef NDEBUG
     32 #include <stdio.h>
     33 
     34 static void
     35 prnode(Node *np)
     36 {
     37 	if (np->left)
     38 		prnode(np->left);
     39 	if (np->right)
     40 		prnode(np->right);
     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 }