view src/operations.c @ 25:2b19746a4e97

Added stack_destroy, separated programs, added swap operation stack_destroy unallocates all space that is currently being used by a given stack. I now have the rpn program and my memory test programs in separate files. The swap operation is exactly what one would expect.
author Jonathan Pevarnek <pevarnj@gmail.com>
date Wed, 16 Mar 2011 17:29:25 -0400
parents 45a80ea314ae
children c1ad124f2aaf
line wrap: on
line source

#include <operations.h>
#include <std.h>
#include <stack.h>
#include <math.h>

const char operationNames[MAXOP][10] = {".", "+", "-", "*", "/", "**", "dup", "drop", "log", "exp", "swap"};
void (*operation[MAXOP])(Stack*) = {op_print, op_add, op_sub, op_mult,
	op_div, op_pow, op_dup, op_drop, op_log, op_exp, op_swap};

void op_math1(Stack *stack, eltType (*mathop)(eltType))
{
	eltCon con = pop(stack);
	if(con.error) sPrint("ERROR, no values on stack\n");
	else push(stack, mathop(con.val));
}

void op_math2(Stack *stack, eltType (*mathop)(eltType, eltType))
{
	eltCon con2 = pop(stack);
	eltCon con1 = pop(stack);
	if(con1.error || con2.error) sPrint("ERROR, stack not large enough\n");
	else push(stack, mathop(con1.val, con2.val));
}

void op_print(Stack *stack)
{
	eltCon con = pop(stack);
	if(con.error) sPrint("ERROR, no values on stack\n");
	else {
		eltType val = con.val;
		char output[30];
		sPrint(append(ftoa(val, output, 10), "\n"));
	}
}

void op_add(Stack *stack)
{
	op_math2(stack, math_add);
}

void op_sub(Stack *stack)
{
	op_math2(stack, math_sub);
}

void op_mult(Stack *stack)
{
	op_math2(stack, math_mult);
}

void op_div(Stack *stack)
{
	op_math2(stack, math_div);
}

void op_pow(Stack *stack)
{
	op_math2(stack, math_pow);
}

void op_dup(Stack *stack)
{
	eltCon con = pop(stack);
	if(con.error) sPrint("ERROR, no values on stack\n");
	else {
		push(stack, con.val);
		push(stack, con.val);
	}
}

void op_drop(Stack *stack)
{
	pop(stack);
}

void op_log(Stack *stack)
{
	op_math1(stack, math_log);
}

void op_exp(Stack *stack)
{
	op_math1(stack, math_exp);
}

void op_swap(Stack *stack)
{
	eltCon con2 = pop(stack);
	eltCon con1 = pop(stack);
	if(con1.error || con2.error) sPrint("ERROR, stack not large enough\n");
	push(stack, con2.val);
	push(stack, con1.val);
}