/************************************************************************
 * grammer - src/memory.c
 * Copyright (C) 2002 Marcello Barnaba <vjt@openssl.it>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 1, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * memory funcs . . .
 */

#include "struct.h"
#include "io.h"
#include "memory.h"

void *xmalloc(size_t sz)
{
    void *ret;

    if((ret = malloc(sz)) == NULL)
    {
	outofmemory(errno);
	/* NOTREACHED */
	return NULL;
    }

    memset(ret, 0x0, sz);
    return ret;
}

void *xrealloc(void *p, size_t sz)
{
    void *ret;
    if((ret = realloc(p, sz)) == NULL)
    {
	outofmemory(errno);
	/* NOTREACHED */
	return NULL;
    }
    return ret;
}

void outofmemory(int e)
{
    outf("PANIC: out of memory (%s)\n",
	    strerror(e));
    exit(-1);
    /* NOTREACHED */
    return;
}

void free_list(List *l)
{
    register List *ltrv;
    void *p;

    for(ltrv = l; ltrv; ltrv = (List *)p)
    {
	p = (void *) ltrv->next;
	xfree(ltrv->item);
	xfree(ltrv);
    }
}

void free_grammar(Grammar *g)
{
    register Prod *ptrv;
    void *p;

    /* free the terminals */
    free_list(g->X);
    /* free the nonterminals */
    free_list(g->V);

    for(ptrv = g->P; ptrv; ptrv = (Prod *)p)
    {
	p = (void *) ptrv->next;
	free_list(ptrv->sx);
	free_list(ptrv->dx);
    }
}
