//
// 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.
//
// AddVisit.h --
//
// Author           : Richard C. Bilson
// Created On       : Sun May 17 16:14:32 2015
// Last Modified By : Peter A. Buhr
// Last Modified On : Thu Feb  2 16:36:02 2017
// Update Count     : 14
//

#include "SynTree/Statement.h"

namespace SymTab {
	void addDecls( std::list< Declaration* > &declsToAdd, std::list< Statement* > &statements, std::list< Statement* >::iterator i );

	template< typename Visitor >
	inline void addVisitStatementList( std::list< Statement* > &stmts, Visitor &visitor ) {
		for ( std::list< Statement* >::iterator stmt = stmts.begin(); ; ++stmt ) {
			// add any new declarations after the previous statement
			for ( std::list< Declaration* >::iterator decl = visitor.declsToAddAfter.begin(); decl != visitor.declsToAddAfter.end(); ++decl ) {
				DeclStmt *declStmt = new DeclStmt( noLabels, *decl );
				stmts.insert( stmt, declStmt );
			}
			visitor.declsToAddAfter.clear();

			if ( stmt == stmts.end() ) break;

			// run mutator on statement
			maybeAccept( *stmt, visitor );

			// add any new declarations before the statement
			for ( std::list< Declaration* >::iterator decl = visitor.declsToAdd.begin(); decl != visitor.declsToAdd.end(); ++decl ) {
				DeclStmt *declStmt = new DeclStmt( noLabels, *decl );
				stmts.insert( stmt, declStmt );
			}
			visitor.declsToAdd.clear();
		}
	}

	template< typename Visitor >
	inline void addVisit(CompoundStmt *compoundStmt, Visitor &visitor) {
		addVisitStatementList( compoundStmt->get_kids(), visitor );
	}

	template< typename Visitor >
	inline void addVisit(SwitchStmt *switchStmt, Visitor &visitor) {
		addVisitStatementList( switchStmt->get_statements(), visitor );
		maybeAccept( switchStmt->get_condition(), visitor );
	}

	template< typename Visitor >
	void acceptAndAdd( std::list< Declaration * > &translationUnit, Visitor &visitor ) {
		for ( std::list< Declaration* >::iterator decl = translationUnit.begin(); ; ++decl ) {
			// splice in new declarations after previous decl
			translationUnit.splice( decl, visitor.declsToAddAfter );

			if ( decl == translationUnit.end() ) break;

			// run mutator on declaration
			maybeAccept( *decl, visitor );

			// splice in new declarations before current decl
			translationUnit.splice( decl, visitor.declsToAdd );
		}
	}

} // namespace SymTab

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