//
// 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.
//
// Validate.cc --
//
// Author           : Richard C. Bilson
// Created On       : Sun May 17 21:50:04 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Thu Mar 30 16:50:13 2017
// Update Count     : 357
//

// The "validate" phase of translation is used to take a syntax tree and convert it into a standard form that aims to be
// as regular in structure as possible.  Some assumptions can be made regarding the state of the tree after this pass is
// complete, including:
//
// - No nested structure or union definitions; any in the input are "hoisted" to the level of the containing struct or
//   union.
//
// - All enumeration constants have type EnumInstType.
//
// - The type "void" never occurs in lists of function parameter or return types.  A function
//   taking no arguments has no argument types.
//
// - No context instances exist; they are all replaced by the set of declarations signified by the context, instantiated
//   by the particular set of type arguments.
//
// - Every declaration is assigned a unique id.
//
// - No typedef declarations or instances exist; the actual type is substituted for each instance.
//
// - Each type, struct, and union definition is followed by an appropriate assignment operator.
//
// - Each use of a struct or union is connected to a complete definition of that struct or union, even if that
//   definition occurs later in the input.

#include <list>
#include <iterator>
#include "Common/ScopedMap.h"
#include "Common/utility.h"
#include "Common/UniqueName.h"
#include "Concurrency/Keywords.h"
#include "Validate.h"
#include "SynTree/Visitor.h"
#include "SynTree/Mutator.h"
#include "SynTree/Type.h"
#include "SynTree/Expression.h"
#include "SynTree/Statement.h"
#include "SynTree/TypeSubstitution.h"
#include "Indexer.h"
#include "FixFunction.h"
// #include "ImplementationType.h"
#include "GenPoly/DeclMutator.h"
#include "AddVisit.h"
#include "MakeLibCfa.h"
#include "TypeEquality.h"
#include "Autogen.h"
#include "ResolvExpr/typeops.h"
#include <algorithm>
#include "InitTweak/InitTweak.h"
#include "CodeGen/CodeGenerator.h"

#define debugPrint( x ) if ( doDebug ) { std::cout << x; }

namespace SymTab {
	class HoistStruct final : public Visitor {
		template< typename Visitor >
		friend void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor );
	    template< typename Visitor >
	    friend void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor );
	  public:
		/// Flattens nested struct types
		static void hoistStruct( std::list< Declaration * > &translationUnit );

		std::list< Declaration * > &get_declsToAdd() { return declsToAdd; }

		virtual void visit( EnumInstType *enumInstType );
		virtual void visit( StructInstType *structInstType );
		virtual void visit( UnionInstType *unionInstType );
		virtual void visit( StructDecl *aggregateDecl );
		virtual void visit( UnionDecl *aggregateDecl );

		virtual void visit( CompoundStmt *compoundStmt );
		virtual void visit( SwitchStmt *switchStmt );
	  private:
		HoistStruct();

		template< typename AggDecl > void handleAggregate( AggDecl *aggregateDecl );

		std::list< Declaration * > declsToAdd, declsToAddAfter;
		bool inStruct;
	};

	/// Fix return types so that every function returns exactly one value
	class ReturnTypeFixer final : public Visitor {
	  public:
		typedef Visitor Parent;
		using Parent::visit;

		static void fix( std::list< Declaration * > &translationUnit );

		virtual void visit( FunctionDecl * functionDecl );
		virtual void visit( FunctionType * ftype );
	};

	/// Replaces enum types by int, and function or array types in function parameter and return lists by appropriate pointers.
	class EnumAndPointerDecayPass final : public Visitor {
		typedef Visitor Parent;
		virtual void visit( EnumDecl *aggregateDecl );
		virtual void visit( FunctionType *func );
	};

	/// Associates forward declarations of aggregates with their definitions
	class LinkReferenceToTypes final : public Indexer {
		typedef Indexer Parent;
	  public:
		LinkReferenceToTypes( bool doDebug, const Indexer *indexer );
	  private:
  		using Parent::visit;
		void visit( EnumInstType *enumInst ) final;
		void visit( StructInstType *structInst ) final;
		void visit( UnionInstType *unionInst ) final;
		void visit( TraitInstType *contextInst ) final;
		void visit( EnumDecl *enumDecl ) final;
		void visit( StructDecl *structDecl ) final;
		void visit( UnionDecl *unionDecl ) final;
		void visit( TypeInstType *typeInst ) final;

		const Indexer *indexer;

		typedef std::map< std::string, std::list< EnumInstType * > > ForwardEnumsType;
		typedef std::map< std::string, std::list< StructInstType * > > ForwardStructsType;
		typedef std::map< std::string, std::list< UnionInstType * > > ForwardUnionsType;
		ForwardEnumsType forwardEnums;
		ForwardStructsType forwardStructs;
		ForwardUnionsType forwardUnions;
	};

	/// Replaces array and function types in forall lists by appropriate pointer type
	class Pass3 final : public Indexer {
		typedef Indexer Parent;
	  public:
	  	using Parent::visit;
		Pass3( const Indexer *indexer );
	  private:
		virtual void visit( ObjectDecl *object ) override;
		virtual void visit( FunctionDecl *func ) override;

		const Indexer *indexer;
	};

	class ReturnChecker : public Visitor {
	  public:
		/// Checks that return statements return nothing if their return type is void
		/// and return something if the return type is non-void.
		static void checkFunctionReturns( std::list< Declaration * > & translationUnit );
	  private:
		virtual void visit( FunctionDecl * functionDecl );
		virtual void visit( ReturnStmt * returnStmt );

		std::list< DeclarationWithType * > returnVals;
	};

	class EliminateTypedef : public Mutator {
	  public:
		EliminateTypedef() : scopeLevel( 0 ) {}
		/// Replaces typedefs by forward declarations
		static void eliminateTypedef( std::list< Declaration * > &translationUnit );
	  private:
		virtual Declaration *mutate( TypedefDecl *typeDecl );
		virtual TypeDecl *mutate( TypeDecl *typeDecl );
		virtual DeclarationWithType *mutate( FunctionDecl *funcDecl );
		virtual DeclarationWithType *mutate( ObjectDecl *objDecl );
		virtual CompoundStmt *mutate( CompoundStmt *compoundStmt );
		virtual Type *mutate( TypeInstType *aggregateUseType );
		virtual Expression *mutate( CastExpr *castExpr );

		virtual Declaration *mutate( StructDecl * structDecl );
		virtual Declaration *mutate( UnionDecl * unionDecl );
		virtual Declaration *mutate( EnumDecl * enumDecl );
		virtual Declaration *mutate( TraitDecl * contextDecl );

		template<typename AggDecl>
		AggDecl *handleAggregate( AggDecl * aggDecl );

		template<typename AggDecl>
		void addImplicitTypedef( AggDecl * aggDecl );

		typedef std::unique_ptr<TypedefDecl> TypedefDeclPtr;
		typedef ScopedMap< std::string, std::pair< TypedefDeclPtr, int > > TypedefMap;
		typedef std::map< std::string, TypeDecl * > TypeDeclMap;
		TypedefMap typedefNames;
		TypeDeclMap typedeclNames;
		int scopeLevel;
	};

	class VerifyCtorDtorAssign : public Visitor {
	public:
		/// ensure that constructors, destructors, and assignment have at least one
		/// parameter, the first of which must be a pointer, and that ctor/dtors have no
		/// return values.
		static void verify( std::list< Declaration * > &translationUnit );

		virtual void visit( FunctionDecl *funcDecl );
	};

	class ArrayLength : public Visitor {
	public:
		/// for array types without an explicit length, compute the length and store it so that it
		/// is known to the rest of the phases. For example,
		///   int x[] = { 1, 2, 3 };
		///   int y[][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
		/// here x and y are known at compile-time to have length 3, so change this into
		///   int x[3] = { 1, 2, 3 };
		///   int y[3][2] = { { 1, 2, 3 }, { 1, 2, 3 } };
		static void computeLength( std::list< Declaration * > & translationUnit );

		virtual void visit( ObjectDecl * objDecl );
	};

	class CompoundLiteral final : public GenPoly::DeclMutator {
		Type::StorageClasses storageClasses;

		using GenPoly::DeclMutator::mutate;
		DeclarationWithType * mutate( ObjectDecl *objectDecl ) final;
		Expression *mutate( CompoundLiteralExpr *compLitExpr ) final;
	};

	void validate( std::list< Declaration * > &translationUnit, bool doDebug ) {
		EnumAndPointerDecayPass epc;
		LinkReferenceToTypes lrt( doDebug, 0 );
		Pass3 pass3( 0 );
		CompoundLiteral compoundliteral;

		HoistStruct::hoistStruct( translationUnit );
		EliminateTypedef::eliminateTypedef( translationUnit );
		ReturnTypeFixer::fix( translationUnit ); // must happen before autogen
		acceptAll( translationUnit, lrt ); // must happen before autogen, because sized flag needs to propagate to generated functions
		acceptAll( translationUnit, epc ); // must happen before VerifyCtorDtorAssign, because void return objects should not exist
		VerifyCtorDtorAssign::verify( translationUnit );  // must happen before autogen, because autogen examines existing ctor/dtors
		Concurrency::applyKeywords( translationUnit );
		autogenerateRoutines( translationUnit ); // moved up, used to be below compoundLiteral - currently needs EnumAndPointerDecayPass
		Concurrency::implementMutexFuncs( translationUnit );
		Concurrency::implementThreadStarter( translationUnit );
		ReturnChecker::checkFunctionReturns( translationUnit );
		compoundliteral.mutateDeclarationList( translationUnit );
		acceptAll( translationUnit, pass3 );
		ArrayLength::computeLength( translationUnit );
	}

	void validateType( Type *type, const Indexer *indexer ) {
		EnumAndPointerDecayPass epc;
		LinkReferenceToTypes lrt( false, indexer );
		Pass3 pass3( indexer );
		type->accept( epc );
		type->accept( lrt );
		type->accept( pass3 );
	}

	void HoistStruct::hoistStruct( std::list< Declaration * > &translationUnit ) {
		HoistStruct hoister;
		acceptAndAdd( translationUnit, hoister );
	}

	HoistStruct::HoistStruct() : inStruct( false ) {
	}

	void filter( std::list< Declaration * > &declList, bool (*pred)( Declaration * ), bool doDelete ) {
		std::list< Declaration * >::iterator i = declList.begin();
		while ( i != declList.end() ) {
			std::list< Declaration * >::iterator next = i;
			++next;
			if ( pred( *i ) ) {
				if ( doDelete ) {
					delete *i;
				} // if
				declList.erase( i );
			} // if
			i = next;
		} // while
	}

	bool isStructOrUnion( Declaration *decl ) {
		return dynamic_cast< StructDecl * >( decl ) || dynamic_cast< UnionDecl * >( decl );
	}

	template< typename AggDecl >
	void HoistStruct::handleAggregate( AggDecl *aggregateDecl ) {
		if ( inStruct ) {
			// Add elements in stack order corresponding to nesting structure.
			declsToAdd.push_front( aggregateDecl );
			Visitor::visit( aggregateDecl );
		} else {
			inStruct = true;
			Visitor::visit( aggregateDecl );
			inStruct = false;
		} // if
		// Always remove the hoisted aggregate from the inner structure.
		filter( aggregateDecl->get_members(), isStructOrUnion, false );
	}

	void HoistStruct::visit( EnumInstType *structInstType ) {
		if ( structInstType->get_baseEnum() ) {
			declsToAdd.push_front( structInstType->get_baseEnum() );
		}
	}

	void HoistStruct::visit( StructInstType *structInstType ) {
		if ( structInstType->get_baseStruct() ) {
			declsToAdd.push_front( structInstType->get_baseStruct() );
		}
	}

	void HoistStruct::visit( UnionInstType *structInstType ) {
		if ( structInstType->get_baseUnion() ) {
			declsToAdd.push_front( structInstType->get_baseUnion() );
		}
	}

	void HoistStruct::visit( StructDecl *aggregateDecl ) {
		handleAggregate( aggregateDecl );
	}

	void HoistStruct::visit( UnionDecl *aggregateDecl ) {
		handleAggregate( aggregateDecl );
	}

	void HoistStruct::visit( CompoundStmt *compoundStmt ) {
		addVisit( compoundStmt, *this );
	}

	void HoistStruct::visit( SwitchStmt *switchStmt ) {
		addVisit( switchStmt, *this );
	}

	void EnumAndPointerDecayPass::visit( EnumDecl *enumDecl ) {
		// Set the type of each member of the enumeration to be EnumConstant
		for ( std::list< Declaration * >::iterator i = enumDecl->get_members().begin(); i != enumDecl->get_members().end(); ++i ) {
			ObjectDecl * obj = dynamic_cast< ObjectDecl * >( *i );
			assert( obj );
			obj->set_type( new EnumInstType( Type::Qualifiers( Type::Const ), enumDecl->get_name() ) );
		} // for
		Parent::visit( enumDecl );
	}

	namespace {
		template< typename DWTList >
		void fixFunctionList( DWTList & dwts, FunctionType * func ) {
			// the only case in which "void" is valid is where it is the only one in the list; then it should be removed
			// entirely other fix ups are handled by the FixFunction class
			typedef typename DWTList::iterator DWTIterator;
			DWTIterator begin( dwts.begin() ), end( dwts.end() );
			if ( begin == end ) return;
			FixFunction fixer;
			DWTIterator i = begin;
			*i = (*i)->acceptMutator( fixer );
			if ( fixer.get_isVoid() ) {
				DWTIterator j = i;
				++i;
				delete *j;
				dwts.erase( j );
				if ( i != end ) {
					throw SemanticError( "invalid type void in function type ", func );
				} // if
			} else {
				++i;
				for ( ; i != end; ++i ) {
					FixFunction fixer;
					*i = (*i )->acceptMutator( fixer );
					if ( fixer.get_isVoid() ) {
						throw SemanticError( "invalid type void in function type ", func );
					} // if
				} // for
			} // if
		}
	}

	void EnumAndPointerDecayPass::visit( FunctionType *func ) {
		// Fix up parameters and return types
		fixFunctionList( func->get_parameters(), func );
		fixFunctionList( func->get_returnVals(), func );
		Visitor::visit( func );
	}

	LinkReferenceToTypes::LinkReferenceToTypes( bool doDebug, const Indexer *other_indexer ) : Indexer( doDebug ) {
		if ( other_indexer ) {
			indexer = other_indexer;
		} else {
			indexer = this;
		} // if
	}

	void LinkReferenceToTypes::visit( EnumInstType *enumInst ) {
		Parent::visit( enumInst );
		EnumDecl *st = indexer->lookupEnum( enumInst->get_name() );
		// it's not a semantic error if the enum is not found, just an implicit forward declaration
		if ( st ) {
			//assert( ! enumInst->get_baseEnum() || enumInst->get_baseEnum()->get_members().empty() || ! st->get_members().empty() );
			enumInst->set_baseEnum( st );
		} // if
		if ( ! st || st->get_members().empty() ) {
			// use of forward declaration
			forwardEnums[ enumInst->get_name() ].push_back( enumInst );
		} // if
	}

	void LinkReferenceToTypes::visit( StructInstType *structInst ) {
		Parent::visit( structInst );
		StructDecl *st = indexer->lookupStruct( structInst->get_name() );
		// it's not a semantic error if the struct is not found, just an implicit forward declaration
		if ( st ) {
			//assert( ! structInst->get_baseStruct() || structInst->get_baseStruct()->get_members().empty() || ! st->get_members().empty() );
			structInst->set_baseStruct( st );
		} // if
		if ( ! st || st->get_members().empty() ) {
			// use of forward declaration
			forwardStructs[ structInst->get_name() ].push_back( structInst );
		} // if
	}

	void LinkReferenceToTypes::visit( UnionInstType *unionInst ) {
		Parent::visit( unionInst );
		UnionDecl *un = indexer->lookupUnion( unionInst->get_name() );
		// it's not a semantic error if the union is not found, just an implicit forward declaration
		if ( un ) {
			unionInst->set_baseUnion( un );
		} // if
		if ( ! un || un->get_members().empty() ) {
			// use of forward declaration
			forwardUnions[ unionInst->get_name() ].push_back( unionInst );
		} // if
	}

	void LinkReferenceToTypes::visit( TraitInstType *traitInst ) {
		Parent::visit( traitInst );
		if ( traitInst->get_name() == "sized" ) {
			// "sized" is a special trait with no members - just flick the sized status on for the type variable
			if ( traitInst->get_parameters().size() != 1 ) {
				throw SemanticError( "incorrect number of trait parameters: ", traitInst );
			}
			TypeExpr * param = safe_dynamic_cast< TypeExpr * > ( traitInst->get_parameters().front() );
			TypeInstType * inst = safe_dynamic_cast< TypeInstType * > ( param->get_type() );
			TypeDecl * decl = inst->get_baseType();
			decl->set_sized( true );
			// since "sized" is special, the next few steps don't apply
			return;
		}
		TraitDecl *traitDecl = indexer->lookupTrait( traitInst->get_name() );
		if ( ! traitDecl ) {
			throw SemanticError( "use of undeclared trait " + traitInst->get_name() );
		} // if
		if ( traitDecl->get_parameters().size() != traitInst->get_parameters().size() ) {
			throw SemanticError( "incorrect number of trait parameters: ", traitInst );
		} // if

		for ( TypeDecl * td : traitDecl->get_parameters() ) {
			for ( DeclarationWithType * assert : td->get_assertions() ) {
				traitInst->get_members().push_back( assert->clone() );
			} // for
		} // for

		// need to clone members of the trait for ownership purposes
		std::list< Declaration * > members;
		std::transform( traitDecl->get_members().begin(), traitDecl->get_members().end(), back_inserter( members ), [](Declaration * dwt) { return dwt->clone(); } );

		applySubstitution( traitDecl->get_parameters().begin(), traitDecl->get_parameters().end(), traitInst->get_parameters().begin(), members.begin(), members.end(), back_inserter( traitInst->get_members() ) );

		// need to carry over the 'sized' status of each decl in the instance
		for ( auto p : group_iterate( traitDecl->get_parameters(), traitInst->get_parameters() ) ) {
			TypeExpr * expr = safe_dynamic_cast< TypeExpr * >( std::get<1>(p) );
			if ( TypeInstType * inst = dynamic_cast< TypeInstType * >( expr->get_type() ) ) {
				TypeDecl * formalDecl = std::get<0>(p);
				TypeDecl * instDecl = inst->get_baseType();
				if ( formalDecl->get_sized() ) instDecl->set_sized( true );
			}
		}
	}

	void LinkReferenceToTypes::visit( EnumDecl *enumDecl ) {
		// visit enum members first so that the types of self-referencing members are updated properly
		Parent::visit( enumDecl );
		if ( ! enumDecl->get_members().empty() ) {
			ForwardEnumsType::iterator fwds = forwardEnums.find( enumDecl->get_name() );
			if ( fwds != forwardEnums.end() ) {
				for ( std::list< EnumInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
					(*inst )->set_baseEnum( enumDecl );
				} // for
				forwardEnums.erase( fwds );
			} // if
		} // if
	}

	void LinkReferenceToTypes::visit( StructDecl *structDecl ) {
		// visit struct members first so that the types of self-referencing members are updated properly
		Parent::visit( structDecl );
		if ( ! structDecl->get_members().empty() ) {
			ForwardStructsType::iterator fwds = forwardStructs.find( structDecl->get_name() );
			if ( fwds != forwardStructs.end() ) {
				for ( std::list< StructInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
					(*inst )->set_baseStruct( structDecl );
				} // for
				forwardStructs.erase( fwds );
			} // if
		} // if
	}

	void LinkReferenceToTypes::visit( UnionDecl *unionDecl ) {
		Parent::visit( unionDecl );
		if ( ! unionDecl->get_members().empty() ) {
			ForwardUnionsType::iterator fwds = forwardUnions.find( unionDecl->get_name() );
			if ( fwds != forwardUnions.end() ) {
				for ( std::list< UnionInstType * >::iterator inst = fwds->second.begin(); inst != fwds->second.end(); ++inst ) {
					(*inst )->set_baseUnion( unionDecl );
				} // for
				forwardUnions.erase( fwds );
			} // if
		} // if
	}

	void LinkReferenceToTypes::visit( TypeInstType *typeInst ) {
		if ( NamedTypeDecl *namedTypeDecl = lookupType( typeInst->get_name() ) ) {
			if ( TypeDecl *typeDecl = dynamic_cast< TypeDecl * >( namedTypeDecl ) ) {
				typeInst->set_isFtype( typeDecl->get_kind() == TypeDecl::Ftype );
			} // if
		} // if
	}

	Pass3::Pass3( const Indexer *other_indexer ) :  Indexer( false ) {
		if ( other_indexer ) {
			indexer = other_indexer;
		} else {
			indexer = this;
		} // if
	}

	/// Fix up assertions - flattens assertion lists, removing all trait instances
	void forallFixer( Type * func ) {
		for ( TypeDecl * type : func->get_forall() ) {
			std::list< DeclarationWithType * > toBeDone, nextRound;
			toBeDone.splice( toBeDone.end(), type->get_assertions() );
			while ( ! toBeDone.empty() ) {
				for ( DeclarationWithType * assertion : toBeDone ) {
					if ( TraitInstType *traitInst = dynamic_cast< TraitInstType * >( assertion->get_type() ) ) {
						// expand trait instance into all of its members
						for ( Declaration * member : traitInst->get_members() ) {
							DeclarationWithType *dwt = safe_dynamic_cast< DeclarationWithType * >( member );
							nextRound.push_back( dwt->clone() );
						}
						delete traitInst;
					} else {
						// pass assertion through
						FixFunction fixer;
						assertion = assertion->acceptMutator( fixer );
						if ( fixer.get_isVoid() ) {
							throw SemanticError( "invalid type void in assertion of function ", func );
						}
						type->get_assertions().push_back( assertion );
					} // if
				} // for
				toBeDone.clear();
				toBeDone.splice( toBeDone.end(), nextRound );
			} // while
		} // for
	}

	void Pass3::visit( ObjectDecl *object ) {
		forallFixer( object->get_type() );
		if ( PointerType *pointer = dynamic_cast< PointerType * >( object->get_type() ) ) {
			forallFixer( pointer->get_base() );
		} // if
		Parent::visit( object );
		object->fixUniqueId();
	}

	void Pass3::visit( FunctionDecl *func ) {
		forallFixer( func->get_type() );
		Parent::visit( func );
		func->fixUniqueId();
	}

	void ReturnChecker::checkFunctionReturns( std::list< Declaration * > & translationUnit ) {
		ReturnChecker checker;
		acceptAll( translationUnit, checker );
	}

	void ReturnChecker::visit( FunctionDecl * functionDecl ) {
		std::list< DeclarationWithType * > oldReturnVals = returnVals;
		returnVals = functionDecl->get_functionType()->get_returnVals();
		Visitor::visit( functionDecl );
		returnVals = oldReturnVals;
	}

	void ReturnChecker::visit( ReturnStmt * returnStmt ) {
		// Previously this also checked for the existence of an expr paired with no return values on
		// the  function return type. This is incorrect, since you can have an expression attached to
		// a return statement in a void-returning function in C. The expression is treated as if it
		// were cast to void.
		if ( returnStmt->get_expr() == NULL && returnVals.size() != 0 ) {
			throw SemanticError( "Non-void function returns no values: " , returnStmt );
		}
	}


	bool isTypedef( Declaration *decl ) {
		return dynamic_cast< TypedefDecl * >( decl );
	}

	void EliminateTypedef::eliminateTypedef( std::list< Declaration * > &translationUnit ) {
		EliminateTypedef eliminator;
		mutateAll( translationUnit, eliminator );
		if ( eliminator.typedefNames.count( "size_t" ) ) {
			// grab and remember declaration of size_t
			SizeType = eliminator.typedefNames["size_t"].first->get_base()->clone();
		} else {
			// xxx - missing global typedef for size_t - default to long unsigned int, even though that may be wrong
			// eventually should have a warning for this case.
			SizeType = new BasicType( Type::Qualifiers(), BasicType::LongUnsignedInt );
		}
		filter( translationUnit, isTypedef, true );

	}

	Type *EliminateTypedef::mutate( TypeInstType * typeInst ) {
		// instances of typedef types will come here. If it is an instance
		// of a typdef type, link the instance to its actual type.
		TypedefMap::const_iterator def = typedefNames.find( typeInst->get_name() );
		if ( def != typedefNames.end() ) {
			Type *ret = def->second.first->get_base()->clone();
			ret->get_qualifiers() |= typeInst->get_qualifiers();
			// place instance parameters on the typedef'd type
			if ( ! typeInst->get_parameters().empty() ) {
				ReferenceToType *rtt = dynamic_cast<ReferenceToType*>(ret);
				if ( ! rtt ) {
					throw SemanticError("cannot apply type parameters to base type of " + typeInst->get_name());
				}
				rtt->get_parameters().clear();
				cloneAll( typeInst->get_parameters(), rtt->get_parameters() );
				mutateAll( rtt->get_parameters(), *this );  // recursively fix typedefs on parameters
			} // if
			delete typeInst;
			return ret;
		} else {
			TypeDeclMap::const_iterator base = typedeclNames.find( typeInst->get_name() );
			assertf( base != typedeclNames.end(), "Can't find typedecl name %s", typeInst->get_name().c_str() );
			typeInst->set_baseType( base->second );
		} // if
		return typeInst;
	}

	Declaration *EliminateTypedef::mutate( TypedefDecl * tyDecl ) {
		Declaration *ret = Mutator::mutate( tyDecl );

		if ( typedefNames.count( tyDecl->get_name() ) == 1 && typedefNames[ tyDecl->get_name() ].second == scopeLevel ) {
			// typedef to the same name from the same scope
			// must be from the same type

			Type * t1 = tyDecl->get_base();
			Type * t2 = typedefNames[ tyDecl->get_name() ].first->get_base();
			if ( ! ResolvExpr::typesCompatible( t1, t2, Indexer() ) ) {
				throw SemanticError( "cannot redefine typedef: " + tyDecl->get_name() );
			}
		} else {
			typedefNames[ tyDecl->get_name() ] = std::make_pair( TypedefDeclPtr( tyDecl ), scopeLevel );
		} // if

		// When a typedef is a forward declaration:
		//    typedef struct screen SCREEN;
		// the declaration portion must be retained:
		//    struct screen;
		// because the expansion of the typedef is:
		//    void rtn( SCREEN *p ) => void rtn( struct screen *p )
		// hence the type-name "screen" must be defined.
		// Note, qualifiers on the typedef are superfluous for the forward declaration.

		Type *designatorType = tyDecl->get_base()->stripDeclarator();
		if ( StructInstType *aggDecl = dynamic_cast< StructInstType * >( designatorType ) ) {
			return new StructDecl( aggDecl->get_name() );
		} else if ( UnionInstType *aggDecl = dynamic_cast< UnionInstType * >( designatorType ) ) {
			return new UnionDecl( aggDecl->get_name() );
		} else if ( EnumInstType *enumDecl = dynamic_cast< EnumInstType * >( designatorType ) ) {
			return new EnumDecl( enumDecl->get_name() );
		} else {
			return ret->clone();
		} // if
	}

	TypeDecl *EliminateTypedef::mutate( TypeDecl * typeDecl ) {
		TypedefMap::iterator i = typedefNames.find( typeDecl->get_name() );
		if ( i != typedefNames.end() ) {
			typedefNames.erase( i ) ;
		} // if

		typedeclNames[ typeDecl->get_name() ] = typeDecl;
		return Mutator::mutate( typeDecl );
	}

	DeclarationWithType *EliminateTypedef::mutate( FunctionDecl * funcDecl ) {
		typedefNames.beginScope();
		DeclarationWithType *ret = Mutator::mutate( funcDecl );
		typedefNames.endScope();
		return ret;
	}

	DeclarationWithType *EliminateTypedef::mutate( ObjectDecl * objDecl ) {
		typedefNames.beginScope();
		DeclarationWithType *ret = Mutator::mutate( objDecl );
		typedefNames.endScope();

		if ( FunctionType *funtype = dynamic_cast<FunctionType *>( ret->get_type() ) ) { // function type?
			// replace the current object declaration with a function declaration
			FunctionDecl * newDecl = new FunctionDecl( ret->get_name(), ret->get_storageClasses(), ret->get_linkage(), funtype, 0, objDecl->get_attributes(), ret->get_funcSpec() );
			objDecl->get_attributes().clear();
			objDecl->set_type( nullptr );
			delete objDecl;
			return newDecl;
		} // if
		return ret;
	}

	Expression *EliminateTypedef::mutate( CastExpr * castExpr ) {
		typedefNames.beginScope();
		Expression *ret = Mutator::mutate( castExpr );
		typedefNames.endScope();
		return ret;
	}

	CompoundStmt *EliminateTypedef::mutate( CompoundStmt * compoundStmt ) {
		typedefNames.beginScope();
		scopeLevel += 1;
		CompoundStmt *ret = Mutator::mutate( compoundStmt );
		scopeLevel -= 1;
		std::list< Statement * >::iterator i = compoundStmt->get_kids().begin();
		while ( i != compoundStmt->get_kids().end() ) {
			std::list< Statement * >::iterator next = i+1;
			if ( DeclStmt *declStmt = dynamic_cast< DeclStmt * >( *i ) ) {
				if ( dynamic_cast< TypedefDecl * >( declStmt->get_decl() ) ) {
					delete *i;
					compoundStmt->get_kids().erase( i );
				} // if
			} // if
			i = next;
		} // while
		typedefNames.endScope();
		return ret;
	}

	// there may be typedefs nested within aggregates. in order for everything to work properly, these should be removed
	// as well
	template<typename AggDecl>
	AggDecl *EliminateTypedef::handleAggregate( AggDecl * aggDecl ) {
		std::list<Declaration *>::iterator it = aggDecl->get_members().begin();
		for ( ; it != aggDecl->get_members().end(); ) {
			std::list< Declaration * >::iterator next = it+1;
			if ( dynamic_cast< TypedefDecl * >( *it ) ) {
				delete *it;
				aggDecl->get_members().erase( it );
			} // if
			it = next;
		}
		return aggDecl;
	}

	template<typename AggDecl>
	void EliminateTypedef::addImplicitTypedef( AggDecl * aggDecl ) {
		if ( typedefNames.count( aggDecl->get_name() ) == 0 ) {
			Type *type = nullptr;
			if ( StructDecl * newDeclStructDecl = dynamic_cast< StructDecl * >( aggDecl ) ) {
				type = new StructInstType( Type::Qualifiers(), newDeclStructDecl->get_name() );
			} else if ( UnionDecl * newDeclUnionDecl = dynamic_cast< UnionDecl * >( aggDecl ) ) {
				type = new UnionInstType( Type::Qualifiers(), newDeclUnionDecl->get_name() );
			} else if ( EnumDecl * newDeclEnumDecl = dynamic_cast< EnumDecl * >( aggDecl )  ) {
				type = new EnumInstType( Type::Qualifiers(), newDeclEnumDecl->get_name() );
			} // if
			TypedefDeclPtr tyDecl( new TypedefDecl( aggDecl->get_name(), Type::StorageClasses(), type ) );
			typedefNames[ aggDecl->get_name() ] = std::make_pair( std::move( tyDecl ), scopeLevel );
		} // if
	}

	Declaration *EliminateTypedef::mutate( StructDecl * structDecl ) {
		addImplicitTypedef( structDecl );
		Mutator::mutate( structDecl );
		return handleAggregate( structDecl );
	}

	Declaration *EliminateTypedef::mutate( UnionDecl * unionDecl ) {
		addImplicitTypedef( unionDecl );
		Mutator::mutate( unionDecl );
		return handleAggregate( unionDecl );
	}

	Declaration *EliminateTypedef::mutate( EnumDecl * enumDecl ) {
		addImplicitTypedef( enumDecl );
		Mutator::mutate( enumDecl );
		return handleAggregate( enumDecl );
	}

	Declaration *EliminateTypedef::mutate( TraitDecl * contextDecl ) {
		Mutator::mutate( contextDecl );
		return handleAggregate( contextDecl );
	}

	void VerifyCtorDtorAssign::verify( std::list< Declaration * > & translationUnit ) {
		VerifyCtorDtorAssign verifier;
		acceptAll( translationUnit, verifier );
	}

	void VerifyCtorDtorAssign::visit( FunctionDecl * funcDecl ) {
		FunctionType * funcType = funcDecl->get_functionType();
		std::list< DeclarationWithType * > &returnVals = funcType->get_returnVals();
		std::list< DeclarationWithType * > &params = funcType->get_parameters();

		if ( InitTweak::isCtorDtorAssign( funcDecl->get_name() ) ) {
			if ( params.size() == 0 ) {
				throw SemanticError( "Constructors, destructors, and assignment functions require at least one parameter ", funcDecl );
			}
			PointerType * ptrType = dynamic_cast< PointerType * >( params.front()->get_type() );
			if ( ! ptrType || ptrType->is_array() ) {
				throw SemanticError( "First parameter of a constructor, destructor, or assignment function must be a pointer ", funcDecl );
			}
			if ( InitTweak::isCtorDtor( funcDecl->get_name() ) && returnVals.size() != 0 ) {
				throw SemanticError( "Constructors and destructors cannot have explicit return values ", funcDecl );
			}
		}

		Visitor::visit( funcDecl );
	}

	DeclarationWithType * CompoundLiteral::mutate( ObjectDecl *objectDecl ) {
		storageClasses = objectDecl->get_storageClasses();
		DeclarationWithType * temp = Mutator::mutate( objectDecl );
		return temp;
	}

	Expression *CompoundLiteral::mutate( CompoundLiteralExpr *compLitExpr ) {
		// transform [storage_class] ... (struct S){ 3, ... };
		// into [storage_class] struct S temp =  { 3, ... };
		static UniqueName indexName( "_compLit" );

		ObjectDecl *tempvar = new ObjectDecl( indexName.newName(), storageClasses, LinkageSpec::C, 0, compLitExpr->get_result(), compLitExpr->get_initializer() );
		compLitExpr->set_result( 0 );
		compLitExpr->set_initializer( 0 );
		delete compLitExpr;
		DeclarationWithType * newtempvar = mutate( tempvar );
		addDeclaration( newtempvar );					// add modified temporary to current block
		return new VariableExpr( newtempvar );
	}

	void ReturnTypeFixer::fix( std::list< Declaration * > &translationUnit ) {
		ReturnTypeFixer fixer;
		acceptAll( translationUnit, fixer );
	}

	void ReturnTypeFixer::visit( FunctionDecl * functionDecl ) {
		Parent::visit( functionDecl );
		FunctionType * ftype = functionDecl->get_functionType();
		std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
		assertf( retVals.size() == 0 || retVals.size() == 1, "Function %s has too many return values: %d", functionDecl->get_name().c_str(), retVals.size() );
		if ( retVals.size() == 1 ) {
			// ensure all function return values have a name - use the name of the function to disambiguate (this also provides a nice bit of help for debugging).
			// ensure other return values have a name.
			DeclarationWithType * ret = retVals.front();
			if ( ret->get_name() == "" ) {
				ret->set_name( toString( "_retval_", CodeGen::genName( functionDecl ) ) );
			}
		}
	}

	void ReturnTypeFixer::visit( FunctionType * ftype ) {
		// xxx - need to handle named return values - this information needs to be saved somehow
		// so that resolution has access to the names.
		// Note that this pass needs to happen early so that other passes which look for tuple types
		// find them in all of the right places, including function return types.
		std::list< DeclarationWithType * > & retVals = ftype->get_returnVals();
		if ( retVals.size() > 1 ) {
			// generate a single return parameter which is the tuple of all of the return values
			TupleType * tupleType = safe_dynamic_cast< TupleType * >( ResolvExpr::extractResultType( ftype ) );
			// ensure return value is not destructed by explicitly creating an empty ListInit node wherein maybeConstruct is false.
			ObjectDecl * newRet = new ObjectDecl( "", Type::StorageClasses(), LinkageSpec::Cforall, 0, tupleType, new ListInit( std::list<Initializer*>(), noDesignators, false ) );
			deleteAll( retVals );
			retVals.clear();
			retVals.push_back( newRet );
		}
	}

	void ArrayLength::computeLength( std::list< Declaration * > & translationUnit ) {
		ArrayLength len;
		acceptAll( translationUnit, len );
	}

	void ArrayLength::visit( ObjectDecl * objDecl ) {
		if ( ArrayType * at = dynamic_cast< ArrayType * >( objDecl->get_type() ) ) {
			if ( at->get_dimension() != nullptr ) return;
			if ( ListInit * init = dynamic_cast< ListInit * >( objDecl->get_init() ) ) {
				at->set_dimension( new ConstantExpr( Constant::from_ulong( init->get_initializers().size() ) ) );
			}
		}
	}
} // namespace SymTab

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