view actions.c @ 43:c7dca4a1dc37

added test programs; added another example program
author meillo@marmaro.de
date Sat, 01 Mar 2008 21:13:12 +0100
parents 1ad3d7305e5d
children 0b82169d4129
line wrap: on
line source

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "baum.h"
#include "actions.h"

unsigned char action_print(struct Node* node);
unsigned char action_sum(struct Node* node);
unsigned char action_number(struct Node* node);
unsigned char action_input(struct Node* node);
unsigned char action_times(struct Node* node);



unsigned char action(struct Node* node) {
	if (node == NULL) {
		if (option_verbose) {
			fprintf(stderr, "warning: action of non existing node\n");
		}
		return 0;
	}

	if (strcmp(node->name, "print") == 0) {
		return action_print(node);

	} else if (strcmp(node->name, "sum") == 0) {
		return action_sum(node);

	} else if (strcmp(node->name, "number") == 0) {
		return action_number(node);

	} else if (strcmp(node->name, "input") == 0) {
		return action_input(node);

	} else if (strcmp(node->name, "times") == 0) {
		return action_times(node);

	} else {
		fprintf(stderr, "unknown kind of node\n");
		exit(4);
	}
}



unsigned char action_print(struct Node* node) {
	unsigned char result;
	result = action(node->down);
	if (node->value == 'c') {
		printf("%c", result);
	} else {
		printf("%d", result);
	}
	return result;
}


unsigned 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;
}


unsigned char action_number(struct Node* node) {
	if (node->down != NULL) {
		action(node->down);
	}
	return node->value;
}


unsigned char action_input(struct Node* node) {
	/* reads a number which is treated as ASCII value */
	int input;
	printf("input: ");
	scanf("%d", &input);
	input = input % 256;
	insertLast(node, newNode("number", (char) input));

	return 0;
}


unsigned char action_times(struct Node* node) {
	struct Node* tp;
	struct Node* last;
	unsigned char i;
	tp = node->down;
	for (i = 0; i < node->value; i++) {
		/* FIXME deep copy */
		last = insertLast(node, newNode(tp->name, tp->value));
		if (tp->down != NULL) {
			last->down = newNode(tp->down->name, tp->down->value);
		}

	}
	return 0;
}