/*
    c99tree - input layer, c parser wrapper
    Copyright (C) 2010  Tibor Palinkas

    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 2 of the License, 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.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "tree.h"
#include "tree_load.h"
#include "scope.h"
#include "c99tree.h"

node_t *AST = NULL;   /* Abstract Syntax Tree: the grammar */
node_t *TOKT = NULL;  /* Token Tree: list of tokens */
static int close_yyin = 0;

node_t *tree_load_c(const char *filename)
{
	node_t *gram_root, *tok_root;

	if (filename != NULL) {
		yyin = fopen(filename, "r");
		if (yyin == NULL) {
			fprintf(stderr, "c99tree error: can't open %s\n", filename);
			return NULL;
		}
		close_yyin = 1;
	}
	else
		filename = "<stdin>"; /* if no file name from the command line, use stdin */


	scope_enter();
	loc_file_open(NULL, NULL); /* file name: NULL means wait until the first preproc tag */

	gram_root = Nalloc(T_GRAMMAR_TREE, NULL, NULL);
	gram_root->loc.soffs = -1;
	gram_root->loc.eoffs = -1;
	gram_root->loc.twin_parent = NULL;
	gram_root->loc.twin_parent_uid = -1;

	tok_root = Nalloc(T_TOKEN_TREE, NULL, NULL);
	tok_root->loc.soffs = -1;
	tok_root->loc.eoffs = -1;
	tok_root->loc.twin_parent = NULL;
	tok_root->loc.twin_parent_uid = -1;

	yyparse();
	scope_leave();

	tok_root->children = TOKT;
	gram_root->children = AST;
	gram_root->next = tok_root;
	
	return gram_root;
}

void tree_load_cleanup_c()
{
	if (close_yyin)
		fclose(yyin);
	yylex_destroy();
}
