//
// Cforall Version 1.0.0 Copyright (C) 2015 University of Waterloo
//
// The contents of this file are covered under the licence agreement in the
// file "LICENCE" distributed with Cforall.
//
// main.cc --
//
// Author           : Richard C. Bilson
// Created On       : Fri May 15 23:12:02 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Sat Aug 20 12:52:22 2016
// Update Count     : 403
//

#include <iostream>
#include <fstream>
#include <signal.h>										// signal
#include <getopt.h>										// getopt
#include <execinfo.h>									// backtrace, backtrace_symbols_fd
#include <cxxabi.h>										// __cxa_demangle

using namespace std;

#include "Parser/lex.h"
#include "Parser/parser.h"
#include "Parser/TypedefTable.h"
#include "GenPoly/Lvalue.h"
#include "GenPoly/Specialize.h"
#include "GenPoly/Box.h"
#include "GenPoly/CopyParams.h"
#include "GenPoly/InstantiateGeneric.h"
#include "CodeGen/Generate.h"
#include "CodeGen/FixNames.h"
#include "ControlStruct/Mutate.h"
#include "SymTab/Validate.h"
#include "ResolvExpr/AlternativePrinter.h"
#include "ResolvExpr/Resolver.h"
#include "MakeLibCfa.h"
#include "InitTweak/GenInit.h"
#include "InitTweak/FixInit.h"
#include "Common/UnimplementedError.h"
#include "../config.h"

using namespace std;

#define OPTPRINT(x) if ( errorp ) cerr << x << endl;


LinkageSpec::Spec linkage = LinkageSpec::Cforall;
TypedefTable typedefTable;
DeclarationNode * parseTree = nullptr;					// program parse tree

extern int yydebug;										// set for -g flag (Grammar)
bool
	astp = false,
	bresolvep = false,
	bboxp = false,
	ctorinitp = false,
	exprp = false,
	expraltp = false,
	libcfap = false,
	nopreludep = false,
	noprotop = false,
	parsep = false,
	resolvep = false,									// used in AlternativeFinder
	symtabp = false,
	treep = false,
	validp = false,
	errorp = false,
	codegenp = false;

static void parse_cmdline( int argc, char *argv[], const char *& filename );
static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit = false );
static void dump( list< Declaration * > & translationUnit, ostream & out = cout );

void sigSegvBusHandler( int sig_num ) {
	enum { Frames = 50 };
	void * array[Frames];
	int size = backtrace( array, Frames );

	cerr << "*CFA runtime error* program cfa-cpp terminated with "
		 <<	(sig_num == SIGSEGV ? "segment fault" : "bus error")
		 << " backtrace:" << endl;

	char ** messages = backtrace_symbols( array, size );

	// skip first stack frame (points here)
	for ( int i = 2; i < size - 2 && messages != nullptr; i += 1 ) {
		char * mangled_name = nullptr, * offset_begin = nullptr, * offset_end = nullptr;
		for ( char *p = messages[i]; *p; ++p ) {        // find parantheses and +offset
			if (*p == '(') {
				mangled_name = p;
			} else if (*p == '+') {
				offset_begin = p;
			} else if (*p == ')') {
				offset_end = p;
				break;
			} // if
		} // for

		// if line contains symbol, attempt to demangle
		if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
			*mangled_name++ = '\0';
			*offset_begin++ = '\0';
			*offset_end++ = '\0';

			int status;
			char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
			if ( status == 0 ) {						// demangling successful ?
				cerr << "(" << i - 2 << ") " << messages[i] << " : "
					 << real_name << "+" << offset_begin << offset_end << endl;

			} else {									// otherwise, output mangled name
				cerr << "(" << i - 2 << ") " << messages[i] << " : "
					 << mangled_name << "+" << offset_begin << offset_end << endl;
			} // if
			free( real_name );
		} else {										// otherwise, print the whole line
			cerr << "(" << i - 2 << ") " << messages[i] << endl;
		} // if
	} // for
	free( messages );
	exit( EXIT_FAILURE );
} // sigSegvBusHandler

int main( int argc, char * argv[] ) {
	FILE * input;										// use FILE rather than istream because yyin is FILE
	ostream *output = & cout;
	const char *filename = nullptr;
	list< Declaration * > translationUnit;

	signal( SIGSEGV, sigSegvBusHandler );
	signal( SIGBUS, sigSegvBusHandler );

	parse_cmdline( argc, argv, filename );				// process command-line arguments

	try {
		// choose to read the program from a file or stdin
		if ( optind < argc ) {							// any commands after the flags ? => input file name
			input = fopen( argv[ optind ], "r" );
			assertf( input, "cannot open %s\n", argv[ optind ] );
			// if running cfa-cpp directly, might forget to pass -F option (and really shouldn't have to)
			if ( filename == nullptr ) filename = argv[ optind ];
			// prelude filename comes in differently
			if ( libcfap ) filename = "prelude.cf";
			optind += 1;
		} else {										// no input file name
			input = stdin;
			// if running cfa-cpp directly, might forget to pass -F option. Since this takes from stdin, pass
			// a fake name along
			if ( filename == nullptr ) filename = "stdin";
		} // if

		if ( optind < argc ) {							// any commands after the flags and input file ? => output file name
			output = new ofstream( argv[ optind ] );
		} // if

		// read in the builtins, extras, and the prelude
		if ( ! nopreludep ) {							// include gcc builtins
			// -l is for initial build ONLY and builtins.cf is not in the lib directory so access it here.
			FILE * builtins = fopen( libcfap | treep ? "builtins.cf" : CFA_LIBDIR "/builtins.cf", "r" );
			assertf( builtins, "cannot open builtins.cf\n" );
			parse( builtins, LinkageSpec::Compiler );

			// read the extra prelude in, if not generating the cfa library
			FILE * extras = fopen( libcfap | treep ? "extras.cf" : CFA_LIBDIR "/extras.cf", "r" );
			assertf( extras, "cannot open extras.cf\n" );
			parse( extras, LinkageSpec::C );

			if ( ! libcfap ) {
				// read the prelude in, if not generating the cfa library
				FILE * prelude = fopen( treep ? "prelude.cf" : CFA_LIBDIR "/prelude.cf", "r" );
				assertf( prelude, "cannot open prelude.cf\n" );
				parse( prelude, LinkageSpec::Intrinsic );
			} // if
		} // if

		parse( input, libcfap ? LinkageSpec::Intrinsic : LinkageSpec::Cforall, yydebug );

		if ( parsep ) {
			parseTree->printList( cout );
			delete parseTree;
			return 0;
		} // if

		buildList( parseTree, translationUnit );
		delete parseTree;
		parseTree = nullptr;

		if ( astp ) {
			dump( translationUnit );
			return 0;
		} // if

		// add the assignment statement after the initialization of a type parameter
		OPTPRINT( "validate" )
		SymTab::validate( translationUnit, symtabp );
		if ( symtabp ) {
			deleteAll( translationUnit );
			return 0;
		} // if

		if ( expraltp ) {
			ResolvExpr::AlternativePrinter printer( cout );
			acceptAll( translationUnit, printer );
			return 0;
		} // if

		if ( validp ) {
			dump( translationUnit );
			return 0;
		} // if

		OPTPRINT( "mutate" )
		ControlStruct::mutate( translationUnit );
		OPTPRINT( "fixNames" )
		CodeGen::fixNames( translationUnit );
		OPTPRINT( "tweakInit" )
		InitTweak::genInit( translationUnit );

		if ( libcfap ) {
			// generate the bodies of cfa library functions
			LibCfa::makeLibCfa( translationUnit );
		} // if

		if ( bresolvep ) {
			dump( translationUnit );
			return 0;
		} // if

		OPTPRINT( "resolve" )
		ResolvExpr::resolve( translationUnit );
		if ( exprp ) {
			dump( translationUnit );
			return 0;
		} // if

		// fix ObjectDecl - replaces ConstructorInit nodes
		OPTPRINT( "fixInit" )
		InitTweak::fix( translationUnit, filename, libcfap || treep );
		if ( ctorinitp ) {
			dump ( translationUnit );
			return 0;
		} // if

		OPTPRINT("instantiateGenerics")
		GenPoly::instantiateGeneric( translationUnit );
		OPTPRINT( "copyParams" );
		GenPoly::copyParams( translationUnit );
		OPTPRINT( "convertSpecializations" )
		GenPoly::convertSpecializations( translationUnit );
		OPTPRINT( "convertLvalue" )
		GenPoly::convertLvalue( translationUnit );

		if ( bboxp ) {
			dump( translationUnit );
			return 0;
		} // if
		OPTPRINT( "box" )
		GenPoly::box( translationUnit );

		// print tree right before code generation
		if ( codegenp ) {
			dump( translationUnit );
			return 0;
		} // if

		CodeGen::generate( translationUnit, *output, ! noprotop );

		if ( output != &cout ) {
			delete output;
		} // if
	} catch ( SemanticError &e ) {
		if ( errorp ) {
			cerr << "---AST at error:---" << endl;
			dump( translationUnit, cerr );
			cerr << endl << "---End of AST, begin error message:---\n" << endl;
		} // if
		e.print( cerr );
		if ( output != &cout ) {
			delete output;
		} // if
		return 1;
	} catch ( UnimplementedError &e ) {
		cout << "Sorry, " << e.get_what() << " is not currently implemented" << endl;
		if ( output != &cout ) {
			delete output;
		} // if
		return 1;
	} catch ( CompilerError &e ) {
		cerr << "Compiler Error: " << e.get_what() << endl;
		cerr << "(please report bugs to " << endl;
		if ( output != &cout ) {
			delete output;
		} // if
		return 1;
	} // try

	deleteAll( translationUnit );
	return 0;
} // main

void parse_cmdline( int argc, char * argv[], const char *& filename ) {
	enum { Ast, Bbox, Bresolver, CtorInitFix, Expr, ExprAlt, Grammar, LibCFA, Nopreamble, Parse, Prototypes, Resolver, Symbol, Tree, Validate, };

	static struct option long_opts[] = {
		{ "ast", no_argument, 0, Ast },
		{ "before-box", no_argument, 0, Bbox },
		{ "before-resolver", no_argument, 0, Bresolver },
		{ "ctorinitfix", no_argument, 0, CtorInitFix },
		{ "expr", no_argument, 0, Expr },
		{ "expralt", no_argument, 0, ExprAlt },
		{ "grammar", no_argument, 0, Grammar },
		{ "libcfa", no_argument, 0, LibCFA },
		{ "no-preamble", no_argument, 0, Nopreamble },
		{ "parse", no_argument, 0, Parse },
		{ "no-prototypes", no_argument, 0, Prototypes },
		{ "resolver", no_argument, 0, Resolver },
		{ "symbol", no_argument, 0, Symbol },
		{ "tree", no_argument, 0, Tree },
		{ "validate", no_argument, 0, Validate },
		{ 0, 0, 0, 0 }
	}; // long_opts
	int long_index;

	opterr = 0;											// (global) prevent getopt from printing error messages

	int c;
	while ( (c = getopt_long( argc, argv, "abBcefglnpqrstvyzD:F:", long_opts, &long_index )) != -1 ) {
		switch ( c ) {
		  case Ast:
		  case 'a':										// dump AST
			astp = true;
			break;
		  case Bresolver:
		  case 'b':										// print before resolver steps
			bresolvep = true;
			break;
		  case 'B':										// print before resolver steps
			bboxp = true;
			break;
		  case CtorInitFix:
		  case 'c':
			ctorinitp = true;
			break;
		  case Expr:
		  case 'e':										// dump AST after expression analysis
			exprp = true;
			break;
		  case ExprAlt:
		  case 'f':										// print alternatives for expressions
			expraltp = true;
			break;
		  case Grammar:
		  case 'g':										// bison debugging info (grammar rules)
			yydebug = true;
			break;
		  case LibCFA:
		  case 'l':										// generate libcfa.c
			libcfap = true;
			break;
		  case Nopreamble:
		  case 'n':										// do not read preamble
			nopreludep = true;
			break;
		  case Prototypes:
		  case 'p':										// generate prototypes for preamble functions
			noprotop = true;
			break;
		  case Parse:
		  case 'q':										// dump parse tree
			parsep = true;
			break;
		  case Resolver:
		  case 'r':										// print resolver steps
			resolvep = true;
			break;
		  case Symbol:
		  case 's':										// print symbol table events
			symtabp = true;
			break;
		  case Tree:
		  case 't':										// build in tree
			treep = true;
			break;
		  case 'v':										// dump AST after decl validation pass
			validp = true;
			break;
		  case 'y':
			errorp = true;
			break;
		  case 'z':
			codegenp = true;
			break;
		  case 'D':										// ignore -Dxxx
			break;
		  case 'F':										// source file-name without suffix
			filename = optarg;
			break;
		  case '?':
			assertf( false, "Unknown option: '%c'\n", (char)optopt );
		  default:
			abort();
		} // switch
	} // while
} // parse_cmdline

static void parse( FILE * input, LinkageSpec::Spec linkage, bool shouldExit ) {
	extern int yyparse( void );
	extern FILE * yyin;
	extern int yylineno;

	::linkage = linkage;								// set globals
	yyin = input;
	yylineno = 1;
	typedefTable.enterScope();
	int parseStatus = yyparse();

	fclose( input );
	if ( shouldExit || parseStatus != 0 ) {
		exit( parseStatus );
	} // if
} // parse

static bool notPrelude( Declaration * decl ) {
	return ! LinkageSpec::isBuiltin( decl->get_linkage() );
} // notPrelude

static void dump( list< Declaration * > & translationUnit, ostream & out ) {
	list< Declaration * > decls;

	if ( noprotop ) {
		filter( translationUnit.begin(), translationUnit.end(), back_inserter( decls ), notPrelude );
	} else {
		decls = translationUnit;
	} // if

	printAll( decls, out );
	deleteAll( translationUnit );
} // dump

// Local Variables: //
// tab-width: 4 //
// mode: c++ //
// compile-command: "make install" //
// End:  //
