#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 ) {
		*crnt = ((stack_node(T)*)malloc()){ next->value }; /***/
		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 = ((stack_node(T)*)malloc()){ value, s->head }; /***/
}

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

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