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

forall(otype T) struct stack_node {
	T value;
	stack_node(T) * next;
};
forall(otype T) void ?{}( stack_node(T) & node, T value, stack_node(T) * next ) {
    node.value = value;
    node.next = 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 ) {
		// *crnt = new( next->value, 0 );
		stack_node(T)* new_node = ((stack_node(T)*)malloc());
		(*new_node){ next->value }; /***/
		*crnt = new_node;
		stack_node(T) * acrnt = *crnt;
		crnt = &acrnt->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 ) {
	// s.head = new( value, s.head );
	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;
	delete( 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;
		delete( crnt );
	}
	s.head = 0;
}
