view baum.c @ 1:3da0ff17c8e7

added features (print, sum, number); split in header file
author meillo@marmaro.de
date Thu, 07 Feb 2008 14:31:02 +0100
parents 2f71d692d4f9
children 557fa4df2bcd
line wrap: on
line source

/*
 * baum - an esoteric programming language
 *
 * (c) markus schnalke <meillo@marmaro.de>
 * and julian forster
 *
 */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "baum.h"

char action(struct Node* node);

struct Node* root;


void logit(char* text) {
	fprintf(stderr, "[%s]\n", text);
}


/* new */
struct Node* newNode(char* name) {
	struct Node* node;
	node = (struct Node*) malloc(sizeof(struct Node));
	node->name = name;
	node->value = 0;
	node->right = 0;
	node->down = 0;
	return node;
}


/* delete */
void delete(struct Node* node) {
	if (node->down != NULL) {
		delete(node->down);
	}
	if (node->right != NULL) {
		delete(node->right);
	}
	free(node); node=0;
}


/* print */
void printNode(struct Node* node) {
	printf("Node: %20s (%c)\n", node->name, node->value);
}

void printTree(struct Node* root) {
	printNode(root);
	printf("  down: ");
	if (root->down != NULL) {
		printTree(root->down);
	} else {
		printf("NULL\n");
	}
	printf("  right: ");
	if (root->right != NULL) {
		printTree(root->right);
	} else {
		printf("NULL\n");
	}
}


char action_print(struct Node* node) {
	printf("%c\n", action(node->down));
	return 0;
}

char action_sum(struct Node* node) {
	struct Node* tp;
	tp = node->down;
	while (tp != NULL) {
		node->value += action(tp);
		tp = tp->right;
	}
	return node->value;
}

char action_number(struct Node* node) {
	return node->value;
}

char action(struct Node* node) {
	if (strcmp(node->name, "print") == 0) {
		logit("print-node");
		return action_print(node);
	} else if (strcmp(node->name, "sum") == 0) {
		logit("sum-node");
		return action_sum(node);
	} else if (strcmp(node->name, "number") == 0) {
		logit("number-node");
		return action_number(node);
	} else {
		fprintf(stderr, "unknown kind of node");
		exit(1);
	}
}



/* traverse */
void traverse(struct Node* root) {
	/* each node controlls the nodes below itself */
	action(root);
}

/* init */
void init() {
	root = newNode("print");
	root->down = newNode("number");
	root->down = newNode("sum");
	root->down->down = newNode("number");
	root->down->down->value = 70;  /* 'F' */
	root->down->down->right = newNode("number");
	root->down->down->right->value = 50;  /* '2' */
	/* result should be 'x' */
}


/* main */
int main(int argc, char* argv[]) {
	init();
	printTree(root);

	action(root);

	delete(root);
	
	return(0);
}