//
// 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 Feb 16 09:14:04 2019
// Update Count     : 500
//

#include <cxxabi.h>                         // for __cxa_demangle
#include <execinfo.h>                       // for backtrace, backtrace_symbols
#include <getopt.h>                         // for no_argument, optind, geto...
#include <signal.h>                         // for signal, SIGABRT, SIGSEGV
#include <cassert>                          // for assertf
#include <cstdio>                           // for fopen, FILE, fclose, stdin
#include <cstdlib>                          // for exit, free, abort, EXIT_F...
#include <cstring>                          // for index
#include <fstream>                          // for ofstream
#include <iostream>                         // for operator<<, basic_ostream
#include <iterator>                         // for back_inserter
#include <list>                             // for list
#include <string>                           // for char_traits, operator<<

#include "CompilationState.h"
#include "../config.h"                      // for CFA_LIBDIR
#include "CodeGen/FixMain.h"                // for FixMain
#include "CodeGen/FixNames.h"               // for fixNames
#include "CodeGen/Generate.h"               // for generate
#include "CodeTools/DeclStats.h"            // for printDeclStats
#include "CodeTools/ResolvProtoDump.h"      // for dumpAsResolvProto
#include "CodeTools/TrackLoc.h"             // for fillLocations
#include "Common/CompilerError.h"           // for CompilerError
#include "Common/Stats.h"
#include "Common/PassVisitor.h"
#include "Common/SemanticError.h"           // for SemanticError
#include "Common/UnimplementedError.h"      // for UnimplementedError
#include "Common/utility.h"                 // for deleteAll, filter, printAll
#include "Concurrency/Waitfor.h"            // for generateWaitfor
#include "ControlStruct/ExceptTranslate.h"  // for translateEHM
#include "ControlStruct/Mutate.h"           // for mutate
#include "GenPoly/Box.h"                    // for box
#include "GenPoly/InstantiateGeneric.h"     // for instantiateGeneric
#include "GenPoly/Lvalue.h"                 // for convertLvalue
#include "GenPoly/Specialize.h"             // for convertSpecializations
#include "InitTweak/FixInit.h"              // for fix
#include "InitTweak/GenInit.h"              // for genInit
#include "MakeLibCfa.h"                     // for makeLibCfa
#include "Parser/LinkageSpec.h"             // for Spec, Cforall, Intrinsic
#include "Parser/ParseNode.h"               // for DeclarationNode, buildList
#include "Parser/TypedefTable.h"            // for TypedefTable
#include "ResolvExpr/AlternativePrinter.h"  // for AlternativePrinter
#include "ResolvExpr/Resolver.h"            // for resolve
#include "SymTab/Validate.h"                // for validate
#include "SynTree/Declaration.h"            // for Declaration
#include "SynTree/Visitor.h"                // for acceptAll
#include "Tuples/Tuples.h"                  // for expandMemberTuples, expan...
#include "Virtual/ExpandCasts.h"            // for expandCasts

using namespace std;

void NewPass(const char * const name) {
	Stats::Heap::newPass(name);
	using namespace Stats::Counters;
	
	{
		static auto group = build<CounterGroup>("Pass Visitor");
		auto pass = build<CounterGroup>(name, group);
		pass_visitor_stats.depth = 0;
		pass_visitor_stats.avg = build<AverageCounter<double>>("Average Depth", pass);
		pass_visitor_stats.max = build<MaxCounter<double>>("Max Depth", pass);
	}

	{
		static auto group = build<CounterGroup>("Syntax Node");
		auto pass = build<CounterGroup>(name, group);
		BaseSyntaxNode::new_nodes = build<SimpleCounter>("Allocs", pass);
	}
}

#define PASS(name, pass)                  \
	if ( errorp ) { cerr << name << endl; } \
	NewPass(name);                          \
	Stats::Time::StartBlock(name);          \
	pass;                                   \
	Stats::Time::StopBlock();

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

std::string PreludeDirector = "";

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

static void backtrace( int start ) {					// skip first N stack frames
	enum { Frames = 50 };
	void * array[Frames];
	int size = ::backtrace( array, Frames );
	char ** messages = ::backtrace_symbols( array, size ); // does not demangle names

	*index( messages[0], '(' ) = '\0';					// find executable name
	cerr << "Stack back trace for: " << messages[0] << endl;

	// skip last 2 stack frames after main
	for ( int i = start; 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
		int frameNo = i - start;
		if ( mangled_name && offset_begin && offset_end && mangled_name < offset_begin ) {
			*mangled_name++ = '\0';						// delimit strings
			*offset_begin++ = '\0';
			*offset_end++ = '\0';

			int status;
			char * real_name = __cxxabiv1::__cxa_demangle( mangled_name, 0, 0, &status );
			// bug in __cxa_demangle for single-character lower-case non-mangled names
			if ( status == 0 ) {						// demangling successful ?
				cerr << "(" << frameNo << ") " << messages[i] << " : "
					 << real_name << "+" << offset_begin << offset_end << endl;
			} else {									// otherwise, output mangled name
				cerr << "(" << frameNo << ") " << messages[i] << " : "
					 << mangled_name << "(/*unknown*/)+" << offset_begin << offset_end << endl;
			} // if

			free( real_name );
		} else {										// otherwise, print the whole line
			cerr << "(" << frameNo << ") " << messages[i] << endl;
		} // if
	} // for

	free( messages );
} // backtrace

void sigSegvBusHandler( int sig_num ) {
	cerr << "*CFA runtime error* program cfa-cpp terminated with "
		 <<	(sig_num == SIGSEGV ? "segment fault" : "bus error")
		 << "." << endl;
	backtrace( 2 );										// skip first 2 stack frames
	//_exit( EXIT_FAILURE );
	abort();
} // sigSegvBusHandler

void sigAbortHandler( __attribute__((unused)) int sig_num ) {
	backtrace( 6 );										// skip first 6 stack frames
	signal( SIGABRT, SIG_DFL);							// reset default signal handler
		raise( SIGABRT );									// reraise SIGABRT
} // sigAbortHandler


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 );
	signal( SIGABRT, sigAbortHandler );

	// std::cout << "main" << std::endl;
	// for ( int i = 0; i < argc; i += 1 ) {
	// 	std::cout << '\t' << argv[i] << std::endl;
	// } // for

	parse_cmdline( argc, argv, filename );				// process command-line arguments
	CodeGen::FixMain::setReplaceMain( !nomainp );

	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.cfa";
			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

		Stats::Time::StartGlobal();
		NewPass("Parse");
		Stats::Time::StartBlock("Parse");

		// 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.

			assertf( !PreludeDirector.empty(), "Can't find prelude without option --prelude-dir must be used." );

			// Read to gcc builtins, if not generating the cfa library
			FILE * gcc_builtins = fopen( (PreludeDirector + "/gcc-builtins.cf").c_str(), "r" );
			assertf( gcc_builtins, "cannot open gcc-builtins.cf\n" );
			parse( gcc_builtins, LinkageSpec::Compiler );

			// read the extra prelude in, if not generating the cfa library
			FILE * extras = fopen( (PreludeDirector + "/extras.cf").c_str(), "r" );
			assertf( extras, "cannot open extras.cf\n" );
			parse( extras, LinkageSpec::BuiltinC );

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

				// Read to cfa builtins, if not generating the cfa library
				FILE * builtins = fopen( (PreludeDirector + "/builtins.cf").c_str(), "r" );
				assertf( builtins, "cannot open builtins.cf\n" );
				parse( builtins, LinkageSpec::BuiltinCFA );
			} // 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

		// Temporary: fill locations after parsing so that every node has a location, for early error messages.
		// Eventually we should pass the locations from the parser to every node, but this quick and dirty solution
		// works okay for now.
		CodeTools::fillLocations( translationUnit );
		Stats::Time::StopBlock();

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

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

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

		PASS( "Fix Labels", ControlStruct::fixLabels( translationUnit ) );
		PASS( "Fix Names", CodeGen::fixNames( translationUnit ) );
		PASS( "Gen Init", InitTweak::genInit( translationUnit ) );
		PASS( "Expand Member Tuples" , Tuples::expandMemberTuples( translationUnit ) );
		if ( libcfap ) {
			// generate the bodies of cfa library functions
			LibCfa::makeLibCfa( translationUnit );
		} // if

		if ( declstatsp ) {
			CodeTools::printDeclStats( translationUnit );
			deleteAll( translationUnit );
			return 0;
		}

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

		CodeTools::fillLocations( translationUnit );

		if ( resolvprotop ) {
			CodeTools::dumpAsResolvProto( translationUnit );
			return 0;
		}

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

		// fix ObjectDecl - replaces ConstructorInit nodes
		PASS( "Fix Init", InitTweak::fix( translationUnit, buildingLibrary() ) );
		if ( ctorinitp ) {
			dump ( translationUnit );
			return 0;
		} // if

		PASS( "Expand Unique Expr", Tuples::expandUniqueExpr( translationUnit ) ); // xxx - is this the right place for this? want to expand ASAP so tha, sequent passes don't need to worry about double-visiting a unique expr - needs to go after InitTweak::fix so that copy constructed return declarations are reused

		PASS( "Translate EHM" , ControlStruct::translateEHM( translationUnit ) );

		PASS( "Gen Waitfor" , Concurrency::generateWaitFor( translationUnit ) );

		PASS( "Convert Specializations",  GenPoly::convertSpecializations( translationUnit ) ); // needs to happen before tuple types are expanded

		PASS( "Expand Tuples", Tuples::expandTuples( translationUnit ) ); // xxx - is this the right place for this?

		if ( tuplep ) {
			dump( translationUnit );
			return 0;
		}

		PASS( "Virtual Expand Casts", Virtual::expandCasts( translationUnit ) ); // Must come after translateEHM

		PASS( "Instantiate Generics", GenPoly::instantiateGeneric( translationUnit ) );
		if ( genericsp ) {
			dump( translationUnit );
			return 0;
		}
		PASS( "Convert L-Value", GenPoly::convertLvalue( translationUnit ) );


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

		if ( bcodegenp ) {
			dump( translationUnit );
			return 0;
		}

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

		CodeTools::fillLocations( translationUnit );
		PASS( "Code Gen", CodeGen::generate( translationUnit, *output, ! noprotop, prettycodegenp, true, linemarks ) );

		CodeGen::FixMain::fix( *output, (PreludeDirector + "/bootloader.c").c_str() );
		if ( output != &cout ) {
			delete output;
		} // if
	} catch ( SemanticErrorException &e ) {
		if ( errorp ) {
			cerr << "---AST at error:---" << endl;
			dump( translationUnit, cerr );
			cerr << endl << "---End of AST, begin error message:---\n" << endl;
		} // if
		e.print();
		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 [REDACTED])" << endl;
		if ( output != &cout ) {
			delete output;
		} // if
		return 1;
	} catch(...) {
		std::exception_ptr eptr = std::current_exception();
		try {
			if (eptr) {
				std::rethrow_exception(eptr);
			}
			else {
				std::cerr << "Exception Uncaught and Unkown" << std::endl;
			}
		} catch(const std::exception& e) {
			std::cerr << "Uncaught Exception \"" << e.what() << "\"\n";
		}
		return 1;
	}// try

	deleteAll( translationUnit );
	Stats::print();

	return 0;
} // main

void parse_cmdline( int argc, char * argv[], const char *& filename ) {
	enum { Ast, Bbox, Bresolver, CtorInitFix, DeclStats, Expr, ExprAlt, Grammar, LibCFA, Linemarks, Nolinemarks, Nopreamble, Parse, PreludeDir, Prototypes, Resolver, ResolvProto, Stats, Symbol, Tree, TupleExpansion, 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 },
		{ "decl-stats", no_argument, 0, DeclStats },
		{ "expr", no_argument, 0, Expr },
		{ "expralt", no_argument, 0, ExprAlt },
		{ "grammar", no_argument, 0, Grammar },
		{ "libcfa", no_argument, 0, LibCFA },
		{ "line-marks", no_argument, 0, Linemarks },
		{ "no-line-marks", no_argument, 0, Nolinemarks },
		{ "no-preamble", no_argument, 0, Nopreamble },
		{ "parse", no_argument, 0, Parse },
		{ "prelude-dir", required_argument, 0, PreludeDir },
		{ "no-prototypes", no_argument, 0, Prototypes },
		{ "resolver", no_argument, 0, Resolver },
		{ "resolv-proto", no_argument, 0, ResolvProto },
		{ "stats", required_argument, 0, Stats },
		{ "symbol", no_argument, 0, Symbol },
		{ "tree", no_argument, 0, Tree },
		{ "tuple-expansion", no_argument, 0, TupleExpansion },
		{ "validate", no_argument, 0, Validate },
		{ 0, 0, 0, 0 }
	}; // long_opts
	int long_index;

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

	bool Wsuppress = false, Werror = false;
	int c;
	while ( (c = getopt_long( argc, argv, "abBcCdefgGlLmnNpqrRstTvwW:yzZD: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 box steps
			bboxp = true;
			break;
			case CtorInitFix:
			case 'c':										// print after constructors and destructors are replaced
			ctorinitp = true;
			break;
			case 'C':										// print before code generation
			bcodegenp = true;
			break;
			case DeclStats:
			case 'd':
				declstatsp = 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 'G':										// dump AST after instantiate generics
			genericsp = true;
			break;
			case LibCFA:
			case 'l':										// generate libcfa.c
			libcfap = true;
			break;
			case Linemarks:
			case 'L':										// print lines marks
			linemarks = true;
			break;
			case Nopreamble:
			case 'n':										// do not read preamble
			nopreludep = true;
			break;
			case Nolinemarks:
			case 'N':										// suppress line marks
			linemarks = false;
			break;
			case Prototypes:
			case 'p':										// generate prototypes for preamble functions
			noprotop = true;
			break;
			case PreludeDir:
				PreludeDirector = optarg;
			break;
			case 'm':										// don't replace the main
				nomainp = true;
			break;
			case Parse:
			case 'q':										// dump parse tree
			parsep = true;
			break;
			case Resolver:
			case 'r':										// print resolver steps
			resolvep = true;
			break;
			case 'R':										// dump resolv-proto instance
			resolvprotop = true;
			break;
			case Stats:
				Stats::parse_params(optarg);
			break;
			case Symbol:
			case 's':										// print symbol table events
			symtabp = true;
			break;
			case Tree:
			case 't':										// build in tree
			treep = true;
			break;
			case TupleExpansion:
			case 'T':										// print after tuple expansion
			tuplep = true;
			break;
			case 'v':										// dump AST after decl validation pass
			validp = true;
			break;
			case 'w':
			Wsuppress = true;
			break;
			case 'W':
			if ( strcmp( optarg, "all" ) == 0 ) {
				SemanticWarning_EnableAll();
			} else if ( strcmp( optarg, "error" ) == 0 ) {
				Werror = true;
			} else {
				char * warning = optarg;
				Severity s;
				if ( strncmp( optarg, "no-", 3 ) == 0 ) {
					warning += 3;
					s = Severity::Suppress;
				} else {
					s = Severity::Warn;
				} // if
				SemanticWarning_Set( warning, s );
			} // if
			break;
			case 'y':										// dump AST on error
			errorp = true;
			break;
			case 'z':										// dump as codegen rather than AST
			codegenp = true;
			break;
			case 'Z':									// prettyprint during codegen (i.e. print unmangled names, etc.)
			prettycodegenp = true;
			break;
			case 'D':										// ignore -Dxxx
			break;
			case 'F':										// source file-name without suffix
			filename = optarg;
			break;
			case '?':
			if ( optopt ) {								// short option ?
				assertf( false, "Unknown option: -%c\n", (char)optopt );
			} else {
				assertf( false, "Unknown option: %s\n", argv[optind - 1] );
			} // if
			#if defined(__GNUC__) && __GNUC__ >= 7
				__attribute__((fallthrough));
			#endif
			default:
			abort();
		} // switch
	} // while

	if ( Werror ) {
		SemanticWarning_WarningAsError();
	} // if
	if ( Wsuppress ) {
		SemanticWarning_SuppressAll();
	} // if
	// for ( const auto w : WarningFormats ) {
	// 	cout << w.name << ' ' << (int)w.severity << endl;
	// } // for
} // 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;
	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

	// depending on commandline options, either generate code or dump the AST
	if ( codegenp ) {
		CodeGen::generate( decls, out, ! noprotop, prettycodegenp );
	} else {
		printAll( decls, out );
	}
	deleteAll( translationUnit );
} // dump

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