#include <stdlib>
#include "cfa-stack.h"

forall(otype T) struct stack_node {
	T value;
	stack_node(T) * next;
};

forall(otype T) void ?{}( stack(T) & s ) { (s.head){ 0 }; }

forall(otype T) void ?{}( stack(T) & s, stack(T) t ) {
	stack_node(T) ** crnt = &s.head;
	for ( stack_node(T) * next = t.head; next; next = next->next ) {
		stack_node(T)* new_node = (stack_node(T)*)malloc(); /***/
		(*new_node){ next->value };
		*crnt = new_node;
		crnt = &(*crnt)->next;
	}
	*crnt = 0;
}

forall(otype T) stack(T) ?=?( stack(T) & s, stack(T) t ) {
	if ( s.head == t.head ) return s;
	clear( s );
	s{ t };
	return s;
}

forall(otype T) void ^?{}( stack(T) & s) { clear( s ); }

forall(otype T) _Bool empty( const stack(T) & s ) { return s.head == 0; }

forall(otype T) void push( stack(T) & s, T value ) {
	stack_node(T)* new_node = (stack_node(T)*)malloc(); /***/
	(*new_node){ value, s.head };
	s.head = new_node;
}

forall(otype T) T pop( stack(T) & s ) {
	stack_node(T) * n = s.head;
	s.head = n->next;
	T v = n->value;
	^(*n){};
	free( n );
	return v;
}

forall(otype T) void clear( stack(T) & s ) {
	for ( stack_node(T) * next = s.head; next; ) {
		stack_node(T) * crnt = next;
		next = crnt->next;
		^(*crnt){};
		free(crnt);
	}
	s.head = 0;
}
