//
// 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.
//
// BasicInit.cc -- 
//
// Author           : Rodolfo G. Esteves
// Created On       : Mon May 18 07:44:20 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Tue May 19 16:30:43 2015
// Update Count     : 1
//

#include <list>
#include <cassert>
#include <iostream>
#include <iterator>
#include <algorithm>

#include "utility.h"

#include "SynTree/Type.h"
#include "SynTree/Statement.h"
#include "SynTree/Expression.h"
#include "SynTree/Declaration.h"
#include "SynTree/Initializer.h"

#include "BasicInit.h"
#include "NameCollector.h"
#include "NameAssociation.h"

namespace InitTweak {
	CompoundStmt* BasicInit::mutate(CompoundStmt *compoundStmt) {
		index.visit( compoundStmt );

		std::list< Statement * > &kids = compoundStmt->get_kids();
		std::list< Statement * > newKids;

		for ( std::list< Statement * >::iterator i = kids.begin(); i!= kids.end(); i++ ) {
			//BasicInit newMut(  );
			(*i)->acceptMutator( *this );
			newKids.push_back( *i );

			if ( has_bindings() ) { //       if ( get_bindings() != 0  ) {
				std::list< Statement *> newSt = get_statements();
				//newSt.push_back( *i );
				newKids.splice( newKids.end(), newSt );
				bindings = 0;
				stmts.clear();
			} // if
		} // for

		compoundStmt->get_kids() = newKids;
		return compoundStmt;
	}

	Statement * BasicInit::mutate(DeclStmt *declStmt) {
		declStmt->accept( index );

		ObjectDecl *odecl = 0;

		if ( ( odecl = dynamic_cast<ObjectDecl *>(declStmt->get_decl()) ) != 0 ) {
			Initializer *init = odecl->get_init();
			if ( init == 0 ) return declStmt;

			if ( Classify::type( odecl->get_type() ) == Classify::COMPOUND_T )
				if ( Classify::initializer(init) == Classify::SINGLE_I )
					throw( 0 ); // mismatch of type and initializer
				else {
					NameInCollection *col = Classify::declaration( odecl, &index );
					bindings = NameAssociation< Expression *, BreakInitializer >::createNameAssoc(col);
					bindings->add_value( std::string(""), BreakInitializer(init) );
					BasicInit::build_statements( bindings, odecl->get_name(), stmts );
				} // if
			else
				if ( Classify::initializer(init) == Classify::COMPOUND_I )
					throw( 0 ); // mismatch of type and initializer
				else {
					// Single inits
					SingleInit *sinit = dynamic_cast< SingleInit * > ( init );
					assert( sinit != 0);

					std::list<Expression *> args;
					args.push_back( new AddressExpr( new NameExpr( odecl->get_name() )) );    // have to get address of object
					args.push_back( sinit->get_value() );
					// replace declaration with initialization
					stmts.push_back(new ExprStmt(std::list<Label>(), new UntypedExpr(new NameExpr("?=?"), args)));
				} // if

			delete init;
			odecl->set_init( 0 );
		} else {
			// no declaration statement
		} // if

		return declStmt;
	}

	ExprStmt *assignFromDecl( DeclStmt *declStmt ) {
		ObjectDecl *decl;
		if ( (decl = dynamic_cast<ObjectDecl *>( declStmt->get_decl() )) != 0 ) {
			SingleInit *init;
			if ( (init = dynamic_cast<SingleInit *>(decl->get_init())) != 0 ) {
			} // if
		} // if

		return 0;
	}

	bool isDeclStmtP(Statement *stmt) {
		return ( dynamic_cast< DeclStmt *>(stmt) != 0 );
	}

	BasicInit::Classify::TypeKind BasicInit::Classify::type( Type *toClassify ) {
		if ( toClassify == 0 ) return NULL_T;

		if ( dynamic_cast< StructInstType * >(toClassify) ||
			 dynamic_cast< UnionInstType * >(toClassify) ||
			 dynamic_cast< ArrayType * >(toClassify)         )
			return COMPOUND_T;
		else
			return SINGLE_T;
	}

	BasicInit::Classify::InitKind BasicInit::Classify::initializer( Initializer *init) {
		if ( init == 0 ) return NULL_I;
		if ( dynamic_cast< ListInit * >(init) )
			return COMPOUND_I;
		if ( dynamic_cast< SingleInit * >(init) )
			return SINGLE_I;

		return NULL_I; // shouldn't be here anyways
	}

	NameInCollection * BasicInit::Classify::declaration( ObjectDecl *objdecl, SymTab::Indexer *index ) {
		assert ( index != 0 );

		ReferenceToType *reftype;
		if ( (reftype = dynamic_cast< StructInstType * >( objdecl->get_type() )) != 0 ) {
			StructDecl *strDecl = index->lookupStruct( reftype->get_name() );
			if ( strDecl != 0 ) {
				NameCollectionBuilder bld;
				NameCollector nc( bld );
				strDecl->accept( nc );
				NameInCollection *col = nc.get_builder().get_collection();
				nc.get_builder().set_collection( 0 );

				return col;
			} else
				throw( SemanticError( std::string("No structure of name: ") + reftype->get_name() ) );
		} else {
			throw(SemanticError( reftype->get_name() + std::string("is not a reference to type") ));
			return 0;
		} // if
	}

	std::list< Statement * >
	BasicInit::Classify::matchInit( NameInCollection *col, ObjectDecl *toInitialize, Initializer *init ) {
		assert ( col != 0 );

		std::list< Statement * > arranged(0); //( col->size() ); 
		std::fill( arranged.begin(), arranged.end(), (Statement *)0 );
		int current = 0;

		if ( init == 0 )
			// no initializer... shouldn't even bother... fix this. 
			return arranged;

		ListInit *li = dynamic_cast< ListInit * >( init );

		if ( li != 0 ) {
			for ( std::list<Initializer *>::iterator i = li->begin_initializers();
				  i != li->end_initializers();
				  i++) {
				std::list<Expression *> d_orig = (*i)->get_designators();

				NameInCollection *corrsp; // corresponding element to this initializer
				if ( ! d_orig.empty() ) {
					// 1) has designators
					std::list<NameExpr *> des;
					std::transform( d_orig.begin(), d_orig.end(),
									std::back_inserter( des ), cast_ptr<Expression, NameExpr > );

					for ( std::list<NameExpr *>::iterator j = des.begin(); j != des.end(); j++ ) {
						// check for existence of the element

						if ( (corrsp = (*col)[ (*j)->get_name() ]) != 0 ) {
							// current++;
							SingleInit *sinit;
							if ( (sinit = dynamic_cast< SingleInit * >( *i )) != 0 )
								arranged.push_back( constructAssgn( corrsp->get_name(), toInitialize, sinit ) );
							else
								; // recursive call to matchInit
						} else
							// error, member doesn't exist
							return arranged; // throw( 0 ); // XXX
					}
				} else {
					// 2) doesn't have designators
					if ( (corrsp = (*col)[ current++ ]) != 0 ) {
						SingleInit *sinit;
						if ( (sinit = dynamic_cast< SingleInit * >( *i )) != 0 )
							arranged.push_back( constructAssgn( corrsp->get_name(), toInitialize, sinit ) );
						else
							; // recursive call to matchInit
					} else {
						// Shouldn't be here... probably too many elements in initializer?
					} // if
				} // if
			} // for
		} // if

		return arranged;
	}

	Statement *BasicInit::Classify::constructAssgn( std::string membName, ObjectDecl *toInit, SingleInit *sinit ) {
		std::list< Expression * > args;
		args.push_back(new AddressExpr( new UntypedMemberExpr( membName, new NameExpr(toInit->get_name()) )));
		args.push_back( sinit->get_value() );
		Statement *ret = new ExprStmt(std::list<Label>(), new UntypedExpr(new NameExpr("?=?"), args));
		return ret;
	}

	void BasicInit::build_statements( NameAssociation< Expression *, BreakInitializer > *assoc,  std::string aggName, std::list< Statement *> &stmts ) {
		assert( assoc != 0 );
		static std::list< std::string > prefix;

		NameInCollection *col = assoc->get_collection();
		if ( col->isComposite() ) {
			VariousNames *vc = dynamic_cast< VariousNames * >( col ); 
			for ( VariousNames::key_iterator it = vc->keys_begin(); it != vc->keys_end(); it++ ) {
				prefix.push_back( *it );
				if ( (*assoc)[ *it ] != 0 )
					build_statements( (*assoc)[ *it ], aggName, stmts );

				prefix.pop_back();
			}
		} else {
			SingleNameAssoc< Expression *, BreakInitializer > *sa = \
				dynamic_cast< SingleNameAssoc< Expression *, BreakInitializer > * >( assoc );
			assert( sa != 0 );

			Expression * rh = sa->get_data();

			if (rh != 0) {
				// construct assignment statement list
				Expression *lh = new NameExpr ( aggName );
				for ( std::list< std::string >::iterator i = prefix.begin(); i != prefix.end(); i++ )
					lh = new UntypedMemberExpr( *i, lh );

				std::list< Expression * > args;
				args.push_back( new AddressExpr(lh) ); 	args.push_back( rh );

				stmts.push_back( new ExprStmt(std::list<Label>(), new UntypedExpr(new NameExpr("?=?"), args)) );
			} // if
		} // if

		return;
	}
} // namespace InitTweak

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