Index: src/AST/Pass.hpp
===================================================================
--- src/AST/Pass.hpp	(revision 7f3f63cc9c42e8363dc7b2b0cf4b7e8d803c04e2)
+++ src/AST/Pass.hpp	(revision 04124c4c8fc28d94cb6020ef4a76198aa0f12299)
@@ -1,4 +1,19 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2019 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// Pass.hpp --
+//
+// Author           : Thierry Delisle
+// Created On       : Thu May 09 15::37::05 2019
+// Last Modified By :
+// Last Modified On :
+// Update Count     :
+//
+
 #pragma once
-// IWYU pragma: private, include "Common/PassVisitor.h"
+// IWYU pragma: private, include "AST/Pass.hpp"
 
 #include <functional>
@@ -6,9 +21,13 @@
 #include <stack>
 
-#include "Fwd.hpp"
-#include "Node.hpp"
+#include "AST/Fwd.hpp"
+#include "AST/Node.hpp"
+#include "AST/Decl.hpp"
+#include "AST/Visitor.hpp"
+
+#include "SymTab/Indexer.h"
 
 // Private prelude header, needed for some of the magic tricks this class pulls off
-#include "Pass.proto.hpp"
+#include "AST/Pass.proto.hpp"
 
 namespace ast {
@@ -20,8 +39,12 @@
 //
 // Several additional features are available through inheritance
-// | WithTypeSubstitution - provides polymorphic TypeSubstitution * env for the current expression
+// | WithTypeSubstitution - provides polymorphic const TypeSubstitution * env for the
+//                          current expression
 // | WithStmtsToAdd       - provides the ability to insert statements before or after the current
 //                          statement by adding new statements into stmtsToAddBefore or
 //                          stmtsToAddAfter respectively.
+// | WithDeclsToAdd       - provides the ability to insert declarations before or after the current
+//                          declarations by adding new DeclStmt into declsToAddBefore or
+//                          declsToAddAfter respectively.
 // | WithShortCircuiting  - provides the ability to skip visiting child nodes; set visit_children
 //                          to false in pre{visit,visit} to skip visiting children
@@ -30,15 +53,19 @@
 //                          automatically be restored to its previous value after the corresponding
 //                          postvisit/postmutate teminates.
+// | WithVisitorRef       - provides an pointer to the templated visitor wrapper
+// | WithIndexer          - provides indexer functionality (i.e. up-to-date symbol table)
 //-------------------------------------------------------------------------------------------------
 template< typename pass_t >
 class Pass final : public ast::Visitor {
 public:
+	/// Forward any arguments to the pass constructor
+	/// Propagate 'this' if necessary
 	template< typename... Args >
 	Pass( Args &&... args)
-		: m_pass( std::forward<Args>( args )... )
+		: pass( std::forward<Args>( args )... )
 	{
 		// After the pass is constructed, check if it wants the have a pointer to the wrapping visitor
 		typedef Pass<pass_t> this_t;
-		this_t * const * visitor = __pass::visitor(m_pass, 0);
+		this_t * const * visitor = __pass::visitor(pass, 0);
 		if(visitor) {
 			*const_cast<this_t **>( visitor ) = this;
@@ -48,6 +75,8 @@
 	virtual ~Pass() = default;
 
-	pass_t m_pass;
-
+	/// Storage for the actual pass
+	pass_t pass;
+
+	/// Visit function declarations
 	virtual DeclWithType *     visit( const ObjectDecl           * ) override final;
 	virtual DeclWithType *     visit( const FunctionDecl         * ) override final;
@@ -145,128 +174,112 @@
 	virtual TypeSubstitution * visit( const TypeSubstitution     * ) override final;
 
+	friend void acceptAll( std::list< ptr<Decl> > & decls, Pass<pass_t>& visitor );
 private:
 
-	bool __visit_children() { __pass::bool_ref * ptr = __pass::visit_children(m_pass, 0); return ptr ? *ptr : true; }
+	bool __visit_children() { __pass::bool_ref * ptr = __pass::visit_children(pass, 0); return ptr ? *ptr : true; }
 
 private:
+	/// Logic to call the accept and mutate the parent if needed, delegates call to accept
 	template<typename parent_t, typename child_t>
 	void maybe_accept(parent_t * & , typename parent_t::child_t *);
 
-	ast::Statement  * call_accept( const ast::Statement  * );
-	ast::Expression * call_accept( const ast::Expression * );
+	Stmt * call_accept( const Stmt * );
+	Expr * call_accept( const Expr * );
 
 	template< template <class> class container_t >
-	container_t< ast::ptr<ast::Statement> > call_accept( const container_t< ast::ptr<ast::Statement> > & );
+	container_t< ptr<Stmt> > call_accept( const container_t< ptr<Stmt> > & );
 
 	template< template <class> class container_t, typename node_t >
-	container_t< ast::ptr<node_t> > call_accept( const container_t< ast::ptr<node_t> > & container );
+	container_t< ptr<node_t> > call_accept( const container_t< ptr<node_t> > & container );
 
 private:
-	struct indexer_guard {
+	/// Internal RAII guard for indexer features
+	struct guard_indexer {
+		guard_indexer( Pass<pass_t> & pass ): pass( pass ) { __pass::indexer::enter(pass, 0); }
+		~guard_indexer()                                   { __pass::indexer::leave(pass, 0); }
 		Pass<pass_t> & pass;
-
-		indexer_guard( Pass<pass_t> & pass ) : pass( pass ) { __pass::indexer::enter(pass, 0); }
-		~indexer_guard()                                    { __pass::indexer::leave(pass, 0); }
 	};
 
-	indexer_guard make_indexer_guard() { return { *this }; }
-
-private:
-	struct scope_guard {
+	/// Internal RAII guard for scope features
+	struct guard_scope {
+		guard_scope( Pass<pass_t> & pass ): pass( pass ) { __pass::scope::enter(pass, 0); }
+		~guard_scope()                                   { __pass::scope::leave(pass, 0); }
 		Pass<pass_t> & pass;
-
-		scope_guard( Pass<pass_t> & pass ) : pass( pass ) { __pass::scope::enter(pass, 0); }
-		~scope_guard()                                    { __pass::scope::leave(pass, 0); }
 	};
-
-	scope_guard make_scope_guard() { return { *this }; }
-};
-
-//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-// Guard value : RAII type to restore a value when the Pass finishes visiting this node
-template<typename pass_t, typename T>
-void GuardValue( pass_t * pass, T& val ) {
-	pass->at_cleanup( [ val ]( void * newVal ) {
-		* static_cast< T * >( newVal ) = val;
-	}, static_cast< void * >( & val ) );
-}
-
-//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+};
+
+template<typename pass_t>
+void acceptAll( std::list< ptr<Decl> >, Pass<pass_t>& visitor );
+
+//-------------------------------------------------------------------------------------------------
 // PASS ACCESSORIES
-//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-
-// Keep track of the type substitution
-struct WithConstTypeSubstitution {
-	const ast::TypeSubstitution * env = nullptr;
-};
+//-------------------------------------------------------------------------------------------------
 
 template<typename T>
 using std_list = std::list<T>;
 
-// Used if visitor requires added statements before or after the current node.
-// The Pass template handles what *before* and *after* means automatically
+/// Keep track of the polymorphic const TypeSubstitution * env for the current expression
+struct WithConstTypeSubstitution {
+	const TypeSubstitution * env = nullptr;
+};
+
+/// Used if visitor requires added statements before or after the current node.
+/// The Pass template handles what *before* and *after* means automatically
 template< template<class> class container_t = std_list >
 struct WithStmtsToAdd {
-	container_t< ast::ptr< ast::Statement > > stmtsToAddBefore;
-	container_t< ast::ptr< ast::Statement > > stmtsToAddAfter;
-};
-
-// Used if visitor requires added declarations before or after the current node.
-// The Pass template handles what *before* and *after* means automatically
+	container_t< ptr<Stmt> > stmtsToAddBefore;
+	container_t< ptr<Stmt> > stmtsToAddAfter;
+};
+
+/// Used if visitor requires added declarations before or after the current node.
+/// The Pass template handles what *before* and *after* means automatically
 template< template<class> class container_t = std_list >
 struct WithDeclsToAdd {
-	~WithDeclsToAdd() {
-		assert( declsToAddBefore.empty() );
-	}
-
-	container_t< ast::ptr< ast::Declaration > > declsToAddBefore;
-	container_t< ast::ptr< ast::Declaration > > declsToAddAfter;
-};
-
-// Use if visitation should stop at certain levels
-// set visit_children false of all child nodes should be ignored
+	container_t< ptr<Decl> > declsToAddBefore;
+	container_t< ptr<Decl> > declsToAddAfter;
+};
+
+/// Use if visitation should stop at certain levels
+/// set visit_children false of all child nodes should be ignored
 struct WithShortCircuiting {
 	__pass::bool_ref visit_children;
 };
 
-// class WithGuards {
-// protected:
-// 	WithGuards() = default;
-// 	~WithGuards() = default;
-
-// public:
-// 	at_cleanup_t at_cleanup;
-
-// 	template< typename T >
-// 	void GuardValue( T& val ) {
-// 		at_cleanup( [ val ]( void * newVal ) {
-// 			* static_cast< T * >( newVal ) = val;
-// 		}, static_cast< void * >( & val ) );
-// 	}
-
-// 	template< typename T >
-// 	void GuardScope( T& val ) {
-// 		val.beginScope();
-// 		at_cleanup( []( void * val ) {
-// 			static_cast< T * >( val )->endScope();
-// 		}, static_cast< void * >( & val ) );
-// 	}
-
-// 	template< typename Func >
-// 	void GuardAction( Func func ) {
-// 		at_cleanup( [func](__attribute__((unused)) void *) { func(); }, nullptr );
-// 	}
-// };
-
-// template<typename pass_type>
-// class WithVisitorRef {
-// protected:
-// 	WithVisitorRef() {}
-// 	~WithVisitorRef() {}
-
-// public:
-// 	PassVisitor<pass_type> * const visitor = nullptr;
-// };
-
+/// Used to restore values/functions/etc. when the Pass finishes visiting this node
+class WithGuards {
+	__pass::at_cleanup_t at_cleanup;
+
+public:
+	/// When this node is finished being visited, restore the value of a variable
+	template< typename T >
+	void GuardValue( T& val ) {
+		at_cleanup( [ val ]( void * newVal ) {
+			* static_cast< T * >( newVal ) = val;
+		}, static_cast< void * >( & val ) );
+	}
+
+	/// On the object, all beginScope now and endScope when the current node is finished being visited
+	template< typename T >
+	void GuardScope( T& val ) {
+		val.beginScope();
+		at_cleanup( []( void * val ) {
+			static_cast< T * >( val )->endScope();
+		}, static_cast< void * >( & val ) );
+	}
+
+	/// When this node is finished being visited, call a function
+	template< typename Func >
+	void GuardAction( Func func ) {
+		at_cleanup( [func](void *) { func(); }, nullptr );
+	}
+};
+
+/// Used to get a pointer to the pass with its wrapped type
+template<typename pass_t>
+struct WithVisitorRef {
+	Pass<pass_t> * const visitor = nullptr;
+};
+
+/// Use when the templated visitor should update the indexer
 struct WithIndexer {
 	SymTab::Indexer indexer;
Index: src/AST/Pass.impl.hpp
===================================================================
--- src/AST/Pass.impl.hpp	(revision 7f3f63cc9c42e8363dc7b2b0cf4b7e8d803c04e2)
+++ src/AST/Pass.impl.hpp	(revision 04124c4c8fc28d94cb6020ef4a76198aa0f12299)
@@ -1,12 +1,28 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2019 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// Pass.impl.hpp --
+//
+// Author           : Thierry Delisle
+// Created On       : Thu May 09 15::37::05 2019
+// Last Modified By :
+// Last Modified On :
+// Update Count     :
+//
+
 #pragma once
-// IWYU pragma: private, include "Pass.hpp"
+// IWYU pragma: private, include "AST/Pass.hpp"
 
 #define VISIT_START( node ) \
+	using namespace ast; \
 	/* back-up the visit children */ \
-	__attribute__((unused)) ast::__pass::visit_children_guard guard1( ast::__pass::visit_children(m_pass, 0) ); \
+	__attribute__((unused)) ast::__pass::visit_children_guard guard1( ast::__pass::visit_children(pass, 0) ); \
 	/* setup the scope for passes that want to run code at exit */ \
-	__attribute__((unused)) ast::__pass::guard_value          guard2( ast::__pass::at_cleanup    (m_pass, 0) ); \
+	__attribute__((unused)) ast::__pass::guard_value          guard2( ast::__pass::at_cleanup    (pass, 0) ); \
 	/* call the implementation of the previsit of this pass */ \
-	__pass::previsit( m_pass, node, 0 );
+	__pass::previsit( pass, node, 0 );
 
 #define VISIT( code ) \
@@ -98,9 +114,9 @@
 
 	template< typename pass_t >
-	ast::Expression * Pass< pass_t >::call_accept( const ast::Expression * expr ) {
+	ast::Expr * Pass< pass_t >::call_accept( const ast::Expr * expr ) {
 		__pedantic_pass_assert( __visit_children() );
 		__pedantic_pass_assert( expr );
 
-		const ast::TypeSubstitution ** env_ptr = __pass::env( m_pass, 0);
+		const ast::TypeSubstitution ** env_ptr = __pass::env( pass, 0);
 		if ( env_ptr && expr->env ) {
 			*env_ptr = expr->env;
@@ -111,64 +127,7 @@
 
 	template< typename pass_t >
-	ast::Statement * Pass< pass_t >::call_accept( const ast::Statement * stmt ) {
+	Stmt * Pass< pass_t >::call_accept( const Stmt * stmt ) {
 		__pedantic_pass_assert( __visit_children() );
 		__pedantic_pass_assert( stmt );
-
-		// add a few useful symbols to the scope
-		using __pass::empty;
-		using decls_t = typename std::remove_pointer< decltype(__decls_before()) >::type;
-		using stmts_t = typename std::remove_pointer< decltype(__stmts_before()) >::type;
-
-		// get the stmts/decls that will need to be spliced in
-		auto stmts_before = __pass::stmtsToAddBefore( m_pass, 0);
-		auto stmts_after  = __pass::stmtsToAddAfter ( m_pass, 0);
-		auto decls_before = __pass::declsToAddBefore( m_pass, 0);
-		auto decls_after  = __pass::declsToAddAfter ( m_pass, 0);
-
-		// These may be modified by subnode but most be restored once we exit this statemnet.
-		ValueGuardPtr< const ast::TypeSubstitution * > __old_env         ( __pass::env( m_pass, 0);  );
-		ValueGuardPtr< typename std::remove_pointer< decltype(stmts_before) > __old_decls_before( stmts_before );
-		ValueGuardPtr< typename std::remove_pointer< decltype(stmts_after ) > __old_decls_after ( stmts_after  );
-		ValueGuardPtr< typename std::remove_pointer< decltype(decls_before) > __old_stmts_before( decls_before );
-		ValueGuardPtr< typename std::remove_pointer< decltype(decls_after ) > __old_stmts_after ( decls_after  );
-
-		// Now is the time to actually visit the node
-		ast::Statement * nstmt = stmt->accept( *this );
-
-		// If the pass doesn't want to add anything then we are done
-		if( empty(stmts_before) && empty(stmts_after) && empty(decls_before) && empty(decls_after) ) {
-			return nstmt;
-		}
-
-		// Make sure that it is either adding statements or declartions but not both
-		// this is because otherwise the order would be awkward to predict
-		assert(( empty( stmts_before ) && empty( stmts_after ))
-		    || ( empty( decls_before ) && empty( decls_after )) );
-
-		// Create a new Compound Statement to hold the new decls/stmts
-		ast::CompoundStmt * compound = new ast::CompoundStmt( parent->*child.location );
-
-		// Take all the declarations that go before
-		__pass::take_all( std::back_inserter( compound->kids ), decls_before );
-		__pass::take_all( std::back_inserter( compound->kids ), stmts_before );
-
-		// Insert the original declaration
-		compound->kids.push_back( nstmt );
-
-		// Insert all the declarations that go before
-		__pass::take_all( std::back_inserter( compound->kids ), decls_after );
-		__pass::take_all( std::back_inserter( compound->kids ), stmts_after );
-
-		return compound;
-	}
-
-	template< typename pass_t >
-	template< template <class> class container_t >
-	container_t< ast::ptr<ast::Statement> > Pass< pass_t >::call_accept( const container_t< ast::ptr<ast::Statement> > & statements ) {
-		__pedantic_pass_assert( __visit_children() );
-		if( statements.empty() ) return {};
-
-		// We are going to aggregate errors for all these statements
-		SemanticErrorException errors;
 
 		// add a few useful symbols to the scope
@@ -182,4 +141,5 @@
 
 		// These may be modified by subnode but most be restored once we exit this statemnet.
+		ValueGuardPtr< const ast::TypeSubstitution * > __old_env         ( __pass::env( pass, 0);  );
 		ValueGuardPtr< typename std::remove_pointer< decltype(stmts_before) > __old_decls_before( stmts_before );
 		ValueGuardPtr< typename std::remove_pointer< decltype(stmts_after ) > __old_decls_after ( stmts_after  );
@@ -187,4 +147,58 @@
 		ValueGuardPtr< typename std::remove_pointer< decltype(decls_after ) > __old_stmts_after ( decls_after  );
 
+		// Now is the time to actually visit the node
+		ast::Statement * nstmt = stmt->accept( *this );
+
+		// If the pass doesn't want to add anything then we are done
+		if( empty(stmts_before) && empty(stmts_after) && empty(decls_before) && empty(decls_after) ) {
+			return nstmt;
+		}
+
+		// Make sure that it is either adding statements or declartions but not both
+		// this is because otherwise the order would be awkward to predict
+		assert(( empty( stmts_before ) && empty( stmts_after ))
+		    || ( empty( decls_before ) && empty( decls_after )) );
+
+		// Create a new Compound Statement to hold the new decls/stmts
+		ast::CompoundStmt * compound = new ast::CompoundStmt( parent->*child.location );
+
+		// Take all the declarations that go before
+		__pass::take_all( std::back_inserter( compound->kids ), decls_before );
+		__pass::take_all( std::back_inserter( compound->kids ), stmts_before );
+
+		// Insert the original declaration
+		compound->kids.push_back( nstmt );
+
+		// Insert all the declarations that go before
+		__pass::take_all( std::back_inserter( compound->kids ), decls_after );
+		__pass::take_all( std::back_inserter( compound->kids ), stmts_after );
+
+		return compound;
+	}
+
+	template< typename pass_t >
+	template< template <class> class container_t >
+	container_t< ptr<Stmt> > Pass< pass_t >::call_accept( const container_t< ptr<Stmt> > & statements ) {
+		__pedantic_pass_assert( __visit_children() );
+		if( statements.empty() ) return {};
+
+		// We are going to aggregate errors for all these statements
+		SemanticErrorException errors;
+
+		// add a few useful symbols to the scope
+		using __pass::empty;
+
+		// get the stmts/decls that will need to be spliced in
+		auto stmts_before = __pass::stmtsToAddBefore( pass, 0);
+		auto stmts_after  = __pass::stmtsToAddAfter ( pass, 0);
+		auto decls_before = __pass::declsToAddBefore( pass, 0);
+		auto decls_after  = __pass::declsToAddAfter ( pass, 0);
+
+		// These may be modified by subnode but most be restored once we exit this statemnet.
+		ValueGuardPtr< typename std::remove_pointer< decltype(stmts_before) > __old_decls_before( stmts_before );
+		ValueGuardPtr< typename std::remove_pointer< decltype(stmts_after ) > __old_decls_after ( stmts_after  );
+		ValueGuardPtr< typename std::remove_pointer< decltype(decls_before) > __old_stmts_before( decls_before );
+		ValueGuardPtr< typename std::remove_pointer< decltype(decls_after ) > __old_stmts_after ( decls_after  );
+
 		// update pass statitistics
 		pass_visitor_stats.depth++;
@@ -193,6 +207,6 @@
 
 		bool mutated = false;
-		container_t<ast::ptr< ast::Statement >> new_kids;
-		for( const ast::Statement * stmt : statements ) {
+		container_t< ptr<Stmt> > new_kids;
+		for( const Stmt * stmt : statements ) {
 			try {
 				__pedantic_pass_assert( stmt );
@@ -269,4 +283,44 @@
 //------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
+template< typename pass_t >
+inline void ast::acceptAll( std::list< ast::ptr<ast::Decl> > & decls, ast::Pass< pass_t > & visitor ) {
+	// We are going to aggregate errors for all these statements
+	SemanticErrorException errors;
+
+	// add a few useful symbols to the scope
+	using __pass::empty;
+
+	// get the stmts/decls that will need to be spliced in
+	auto decls_before = __pass::declsToAddBefore( pass, 0);
+	auto decls_after  = __pass::declsToAddAfter ( pass, 0);
+
+	// update pass statitistics
+	pass_visitor_stats.depth++;
+	pass_visitor_stats.max->push(pass_visitor_stats.depth);
+	pass_visitor_stats.avg->push(pass_visitor_stats.depth);
+
+	for ( std::list< ast::ptr<ast::Decl> >::iterator i = decls.begin(); ; ++i ) {
+		// splice in new declarations after previous decl
+		if ( !empty( decls_after ) ) { decls.splice( i, *decls_after ); }
+
+		if ( i == decls.end() ) break;
+
+		try {
+			// run visitor on declaration
+			ast::ptr<ast::Decl> & node = *i;
+			assert( node );
+			node = node->accept( visitor );
+		}
+		catch( SemanticErrorException &e ) {
+			errors.append( e );
+		}
+
+		// splice in new declarations before current decl
+		if ( !empty( decls_before ) ) { decls.splice( i, *decls_before ); }
+	}
+	pass_visitor_stats.depth--;
+	if ( !errors.isEmpty() ) { throw errors; }
+}
+
 // A NOTE ON THE ORDER OF TRAVERSAL
 //
@@ -289,20 +343,20 @@
 // ObjectDecl
 template< typename pass_t >
-ast::DeclarationWithType * Pass< pass_t >::mutate( ast::ObjectDecl * node ) {
+ast::DeclWithType * ast::Pass< pass_t >::visit( const ast::ObjectDecl * node ) {
 	VISIT_START( node );
 
 	VISIT(
 		{
-			auto guard = make_indexer_guard();
-			maybe_accept( node, ast::ObjectDecl::type );
-		}
-		maybe_accept( node, ast::ObjectDecl::init          );
-		maybe_accept( node, ast::ObjectDecl::bitfieldWidth );
-		maybe_accept( node, ast::ObjectDecl::attributes    );
+			indexer_guard guard { *this };
+			maybe_accept( node, ObjectDecl::type );
+		}
+		maybe_accept( node, ObjectDecl::init          );
+		maybe_accept( node, ObjectDecl::bitfieldWidth );
+		maybe_accept( node, ObjectDecl::attributes    );
 	)
 
-	__pass::indexer::AddId( m_pass, 0, node );
-
-	VISIT_END( DeclarationWithType, node );
+	__pass::indexer::AddId( pass, 0, node );
+
+	VISIT_END( DeclWithType, node );
 }
 
@@ -310,5 +364,5 @@
 // Attribute
 template< typename pass_type >
-ast::Attribute * ast::Pass< pass_type >::visit( ast::ptr<ast::Attribute> & node  )  {
+ast::Attribute * ast::Pass< pass_type >::visit( const ast::Attribute * node  )  {
 	VISIT_START(node);
 
@@ -323,5 +377,5 @@
 // TypeSubstitution
 template< typename pass_type >
-TypeSubstitution * PassVisitor< pass_type >::mutate( TypeSubstitution * node ) {
+TypeSubstitution * PassVisitor< pass_type >::mutate( const TypeSubstitution * node ) {
 	MUTATE_START( node );
 
Index: src/AST/Pass.proto.hpp
===================================================================
--- src/AST/Pass.proto.hpp	(revision 7f3f63cc9c42e8363dc7b2b0cf4b7e8d803c04e2)
+++ src/AST/Pass.proto.hpp	(revision 04124c4c8fc28d94cb6020ef4a76198aa0f12299)
@@ -1,274 +1,290 @@
+//
+// Cforall Version 1.0.0 Copyright (C) 2019 University of Waterloo
+//
+// The contents of this file are covered under the licence agreement in the
+// file "LICENCE" distributed with Cforall.
+//
+// Pass.impl.hpp --
+//
+// Author           : Thierry Delisle
+// Created On       : Thu May 09 15::37::05 2019
+// Last Modified By :
+// Last Modified On :
+// Update Count     :
+//
+
 #pragma once
 // IWYU pragma: private, include "Pass.hpp"
 
 namespace ast {
-	template<typename pass_type>
-	class Pass;
-
-	namespace __pass {
-		typedef std::function<void( void * )> cleanup_func_t;
-		typedef std::function<void( cleanup_func_t, void * )> at_cleanup_t;
-
-
-		// boolean reference that may be null
-		// either refers to a boolean value or is null and returns true
-		class bool_ref {
-		public:
-			bool_ref() = default;
-			~bool_ref() = default;
-
-			operator bool() { return m_ref ? *m_ref : true; }
-			bool operator=( bool val ) { assert(m_ref); return *m_ref = val; }
-
-		private:
-
-			friend class visit_children_guard;
-
-			bool * set( bool * val ) {
-				bool * prev = m_ref;
-				m_ref = val;
-				return prev;
+template<typename pass_type>
+class Pass;
+
+namespace __pass {
+	typedef std::function<void( void * )> cleanup_func_t;
+	typedef std::function<void( cleanup_func_t, void * )> at_cleanup_t;
+
+
+	// boolean reference that may be null
+	// either refers to a boolean value or is null and returns true
+	class bool_ref {
+	public:
+		bool_ref() = default;
+		~bool_ref() = default;
+
+		operator bool() { return m_ref ? *m_ref : true; }
+		bool operator=( bool val ) { assert(m_ref); return *m_ref = val; }
+
+	private:
+
+		friend class visit_children_guard;
+
+		bool * set( bool * val ) {
+			bool * prev = m_ref;
+			m_ref = val;
+			return prev;
+		}
+
+		bool * m_ref = nullptr;
+	};
+
+	// Implementation of the guard value
+	// Created inside the visit scope
+	class guard_value {
+	public:
+		/// Push onto the cleanup
+		guard_value( at_cleanup_t * at_cleanup ) {
+			if( at_cleanup ) {
+				*at_cleanup = [this]( cleanup_func_t && func, void* val ) {
+					push( std::move( func ), val );
+				};
 			}
-
-			bool * m_ref = nullptr;
+		}
+
+		~guard_value() {
+			while( !cleanups.empty() ) {
+				auto& cleanup = cleanups.top();
+				cleanup.func( cleanup.val );
+				cleanups.pop();
+			}
+		}
+
+		void push( cleanup_func_t && func, void* val ) {
+			cleanups.emplace( std::move(func), val );
+		}
+
+	private:
+		struct cleanup_t {
+			cleanup_func_t func;
+			void * val;
+
+			cleanup_t( cleanup_func_t&& func, void * val ) : func(func), val(val) {}
 		};
 
-		// Implementation of the guard value
-		// Created inside the visit scope
-		class guard_value {
-		public:
-			guard_value( at_cleanup_t * at_cleanup ) {
-				if( at_cleanup ) {
-					*at_cleanup = [this]( cleanup_func_t && func, void* val ) {
-						push( std::move( func ), val );
-					};
-				}
+		std::stack< cleanup_t > cleanups;
+	};
+
+	// Guard structure implementation for whether or not children should be visited
+	class visit_children_guard {
+	public:
+
+		visit_children_guard( bool_ref * ref )
+			: m_val ( true )
+			, m_prev( ref ? ref->set( &m_val ) : nullptr )
+			, m_ref ( ref )
+		{}
+
+		~visit_children_guard() {
+			if( m_ref ) {
+				m_ref->set( m_prev );
 			}
-
-			~guard_value() {
-				while( !cleanups.empty() ) {
-					auto& cleanup = cleanups.top();
-					cleanup.func( cleanup.val );
-					cleanups.pop();
-				}
-			}
-
-			void push( cleanup_func_t && func, void* val ) {
-				cleanups.emplace( std::move(func), val );
-			}
-
-		private:
-			struct cleanup_t {
-				cleanup_func_t func;
-				void * val;
-
-				cleanup_t( cleanup_func_t&& func, void * val ) : func(func), val(val) {}
-			};
-
-			std::stack< cleanup_t > cleanups;
-		};
-
-		// Guard structure implementation for whether or not children should be visited
-		class visit_children_guard {
-		public:
-
-			visit_children_guard( bool_ref * ref )
-				: m_val ( true )
-				, m_prev( ref ? ref->set( &m_val ) : nullptr )
-				, m_ref ( ref )
-			{}
-
-			~visit_children_guard() {
-				if( m_ref ) {
-					m_ref->set( m_prev );
-				}
-			}
-
-			operator bool() { return m_val; }
-
-		private:
-			bool       m_val;
-			bool     * m_prev;
-			bool_ref * m_ref;
-		};
-
-		//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-		// Deep magic (a.k.a template meta programming) to make the templated visitor work
-		// Basically the goal is to make 2 previsit
-		// 1 - Use when a pass implements a valid previsit. This uses overloading which means the any overload of
-		//     'pass.previsit( node )' that compiles will be used for that node for that type
-		//     This requires that this option only compile for passes that actually define an appropriate visit.
-		//     SFINAE will make sure the compilation errors in this function don't halt the build.
-		//     See http://en.cppreference.com/w/cpp/language/sfinae for details on SFINAE
-		// 2 - Since the first implementation might not be specilizable, the second implementation exists and does nothing.
-		//     This is needed only to eliminate the need for passes to specify any kind of handlers.
-		//     The second implementation only works because it has a lower priority. This is due to the bogus last parameter.
-		//     The second implementation takes a long while the first takes an int. Since the caller always passes an literal 0
-		//     the first implementation takes priority in regards to overloading.
-		//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-		// PreVisit : may mutate the pointer passed in if the node is mutated in the previsit call
-		template<typename pass_t, typename node_t>
-		static inline auto previsit( pass_t & pass, const node_t * & node, int ) -> decltype( pass.previsit( node ), void() ) {
-			node = pass.previsit( node );
-			assert(node);
-		}
-
-		template<typename pass_t, typename node_t>
-		static inline auto previsit( pass_t &, const node_t *, long ) {}
-
-		// PostVisit : never mutates the passed pointer but may return a different node
-		template<typename pass_t, typename node_t>
-		static inline auto postvisit( pass_t & pass, const node_t * node, int ) -> decltype( pass.postvisit( node ), (const node_t *)nullptr ) {
-			return pass.postvisit( node );
-		}
-
-		template<typename pass_t, typename node_t>
-		static inline const node_t * postvisit( pass_t &, const node_t * node, long ) { return node; }
-
-		//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-		// Deep magic (a.k.a template meta programming) continued
-		// To make the templated visitor be more expressive, we allow 'accessories' : classes/structs the implementation can inherit
-		// from in order to get extra functionallity for example
-		// class ErrorChecker : WithShortCircuiting { ... };
-		// Pass<ErrorChecker> checker;
-		// this would define a pass that uses the templated visitor with the additionnal feature that it has short circuiting
-		// Note that in all cases the accessories are not required but guarantee the requirements of the feature is matched
-		//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-		// For several accessories, the feature is enabled by detecting that a specific field is present
-		// Use a macro the encapsulate the logic of detecting a particular field
-		// The type is not strictly enforced but does match the accessory
-		#define FIELD_PTR( name, default_type ) \
-		template< typename pass_t > \
-		static inline auto name( pass_t & pass, int ) -> decltype( &pass.name ) { return &pass.name; } \
+		}
+
+		operator bool() { return m_val; }
+
+	private:
+		bool       m_val;
+		bool     * m_prev;
+		bool_ref * m_ref;
+	};
+
+	//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+	// Deep magic (a.k.a template meta programming) to make the templated visitor work
+	// Basically the goal is to make 2 previsit
+	// 1 - Use when a pass implements a valid previsit. This uses overloading which means the any overload of
+	//     'pass.previsit( node )' that compiles will be used for that node for that type
+	//     This requires that this option only compile for passes that actually define an appropriate visit.
+	//     SFINAE will make sure the compilation errors in this function don't halt the build.
+	//     See http://en.cppreference.com/w/cpp/language/sfinae for details on SFINAE
+	// 2 - Since the first implementation might not be specilizable, the second implementation exists and does nothing.
+	//     This is needed only to eliminate the need for passes to specify any kind of handlers.
+	//     The second implementation only works because it has a lower priority. This is due to the bogus last parameter.
+	//     The second implementation takes a long while the first takes an int. Since the caller always passes an literal 0
+	//     the first implementation takes priority in regards to overloading.
+	//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+	// PreVisit : may mutate the pointer passed in if the node is mutated in the previsit call
+	template<typename pass_t, typename node_t>
+	static inline auto previsit( pass_t & pass, const node_t * & node, int ) -> decltype( pass.previsit( node ), void() ) {
+		node = pass.previsit( node );
+		assert(node);
+	}
+
+	template<typename pass_t, typename node_t>
+	static inline auto previsit( pass_t &, const node_t *, long ) {}
+
+	// PostVisit : never mutates the passed pointer but may return a different node
+	template<typename pass_t, typename node_t>
+	static inline auto postvisit( pass_t & pass, const node_t * node, int ) -> decltype( pass.postvisit( node ), (const node_t *)nullptr ) {
+		return pass.postvisit( node );
+	}
+
+	template<typename pass_t, typename node_t>
+	static inline const node_t * postvisit( pass_t &, const node_t * node, long ) { return node; }
+
+	//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+	// Deep magic (a.k.a template meta programming) continued
+	// To make the templated visitor be more expressive, we allow 'accessories' : classes/structs the implementation can inherit
+	// from in order to get extra functionallity for example
+	// class ErrorChecker : WithShortCircuiting { ... };
+	// Pass<ErrorChecker> checker;
+	// this would define a pass that uses the templated visitor with the additionnal feature that it has short circuiting
+	// Note that in all cases the accessories are not required but guarantee the requirements of the feature is matched
+	//-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
+	// For several accessories, the feature is enabled by detecting that a specific field is present
+	// Use a macro the encapsulate the logic of detecting a particular field
+	// The type is not strictly enforced but does match the accessory
+	#define FIELD_PTR( name, default_type ) \
+	template< typename pass_t > \
+	static inline auto name( pass_t & pass, int ) -> decltype( &pass.name ) { return &pass.name; } \
+	\
+	template< typename pass_t > \
+	static inline default_type * name( pass_t &, long ) { return nullptr; }
+
+	// List of fields and their expected types
+	FIELD_PTR( env, const ast::TypeSubstitution )
+	FIELD_PTR( stmtsToAddBefore, std::list< ast::ptr< ast::Stmt > > )
+	FIELD_PTR( stmtsToAddAfter , std::list< ast::ptr< ast::Stmt > > )
+	FIELD_PTR( declsToAddBefore, std::list< ast::ptr< ast::Decl > > )
+	FIELD_PTR( declsToAddAfter , std::list< ast::ptr< ast::Decl > > )
+	FIELD_PTR( visit_children, __pass::bool_ref )
+	FIELD_PTR( at_cleanup, __pass::at_cleanup_t )
+	FIELD_PTR( visitor, ast::Pass<pass_t> * const )
+
+	// Remove the macro to make sure we don't clash
+	#undef FIELD_PTR
+
+	// Another feature of the templated visitor is that it calls beginScope()/endScope() for compound statement.
+	// All passes which have such functions are assumed desire this behaviour
+	// detect it using the same strategy
+	namespace scope {
+		template<typename pass_t>
+		static inline auto enter( pass_t & pass, int ) -> decltype( pass.beginScope(), void() ) {
+			pass.beginScope();
+		}
+
+		template<typename pass_t>
+		static inline void enter( pass_t &, long ) {}
+
+		template<typename pass_t>
+		static inline auto leave( pass_t & pass, int ) -> decltype( pass.endScope(), void() ) {
+			pass.endScope();
+		}
+
+		template<typename pass_t>
+		static inline void leave( pass_t &, long ) {}
+	};
+
+	// Finally certain pass desire an up to date indexer automatically
+	// detect the presence of a member name indexer and call all the members appropriately
+	namespace indexer {
+		// Some simple scoping rules
+		template<typename pass_t>
+		static inline auto enter( pass_t & pass, int ) -> decltype( pass.indexer.enterScope(), void() ) {
+			pass.indexer.enterScope();
+		}
+
+		template<typename pass_t>
+		static inline auto enter( pass_t &, long ) {}
+
+		template<typename pass_t>
+		static inline auto leave( pass_t & pass, int ) -> decltype( pass.indexer.leaveScope(), void() ) {
+			pass.indexer.leaveScope();
+		}
+
+		template<typename pass_t>
+		static inline auto leave( pass_t &, long ) {}
+
+		// The indexer has 2 kind of functions mostly, 1 argument and 2 arguments
+		// Create macro to condense these common patterns
+		#define INDEXER_FUNC1( func, type ) \
+		template<typename pass_t> \
+		static inline auto func( pass_t & pass, int, type arg ) -> decltype( pass.indexer.func( arg ), void() ) {\
+			pass.indexer.func( arg ); \
+		} \
 		\
-		template< typename pass_t > \
-		static inline default_type * name( pass_t &, long ) { return nullptr; }
-
-		// List of fields and their expected types
-		FIELD_PTR( env, const ast::TypeSubstitution )
-		FIELD_PTR( stmtsToAddBefore, std::list< ast::ptr< ast::Stmt > > )
-		FIELD_PTR( stmtsToAddAfter , std::list< ast::ptr< ast::Stmt > > )
-		FIELD_PTR( declsToAddBefore, std::list< ast::ptr< ast::Decl > > )
-		FIELD_PTR( declsToAddAfter , std::list< ast::ptr< ast::Decl > > )
-		FIELD_PTR( visit_children, __pass::bool_ref )
-		FIELD_PTR( at_cleanup, __pass::at_cleanup_t )
-		FIELD_PTR( visitor, ast::Pass<pass_t> * const )
-
-		// Remove the macro to make sure we don't clash
-		#undef FIELD_PTR
-
-		// Another feature of the templated visitor is that it calls beginScope()/endScope() for compound statement.
-		// All passes which have such functions are assumed desire this behaviour
-		// detect it using the same strategy
-		namespace scope {
-			template<typename pass_t>
-			static inline auto enter( pass_t & pass, int ) -> decltype( pass.beginScope(), void() ) {
-				pass.beginScope();
-			}
-
-			template<typename pass_t>
-			static inline void enter( pass_t &, long ) {}
-
-			template<typename pass_t>
-			static inline auto leave( pass_t & pass, int ) -> decltype( pass.endScope(), void() ) {
-				pass.endScope();
-			}
-
-			template<typename pass_t>
-			static inline void leave( pass_t &, long ) {}
-		};
-
-		// Finally certain pass desire an up to date indexer automatically
-		// detect the presence of a member name indexer and call all the members appropriately
-		namespace indexer {
-			// Some simple scoping rules
-			template<typename pass_t>
-			static inline auto enter( pass_t & pass, int ) -> decltype( pass.indexer.enterScope(), void() ) {
-				pass.indexer.enterScope();
-			}
-
-			template<typename pass_t>
-			static inline auto enter( pass_t &, long ) {}
-
-			template<typename pass_t>
-			static inline auto leave( pass_t & pass, int ) -> decltype( pass.indexer.leaveScope(), void() ) {
-				pass.indexer.leaveScope();
-			}
-
-			template<typename pass_t>
-			static inline auto leave( pass_t &, long ) {}
-
-			// The indexer has 2 kind of functions mostly, 1 argument and 2 arguments
-			// Create macro to condense these common patterns
-			#define INDEXER_FUNC1( func, type ) \
-			template<typename pass_t> \
-			static inline auto func( pass_t & pass, int, type arg ) -> decltype( pass.indexer.func( arg ), void() ) {\
-				pass.indexer.func( arg ); \
-			} \
+		template<typename pass_t> \
+		static inline void func( pass_t &, long, type ) {}
+
+		#define INDEXER_FUNC2( func, type1, type2 ) \
+		template<typename pass_t> \
+		static inline auto func( pass_t & pass, int, type1 arg1, type2 arg2 ) -> decltype( pass.indexer.func( arg1, arg2 ), void () ) {\
+			pass.indexer.func( arg1, arg2 ); \
+		} \
 			\
-			template<typename pass_t> \
-			static inline void func( pass_t &, long, type ) {}
-
-			#define INDEXER_FUNC2( func, type1, type2 ) \
-			template<typename pass_t> \
-			static inline auto func( pass_t & pass, int, type1 arg1, type2 arg2 ) -> decltype( pass.indexer.func( arg1, arg2 ), void () ) {\
-				pass.indexer.func( arg1, arg2 ); \
-			} \
-			 \
-			template<typename pass_t> \
-			static inline void func( pass_t &, long, type1, type2 ) {}
-
-			INDEXER_FUNC1( addId     , DeclarationWithType *       );
-			INDEXER_FUNC1( addType   , NamedTypeDecl *             );
-			INDEXER_FUNC1( addStruct , StructDecl *                );
-			INDEXER_FUNC1( addEnum   , EnumDecl *                  );
-			INDEXER_FUNC1( addUnion  , UnionDecl *                 );
-			INDEXER_FUNC1( addTrait  , TraitDecl *                 );
-			INDEXER_FUNC2( addWith   , std::list< Expression * > &, BaseSyntaxNode * );
-
-			// A few extra functions have more complicated behaviour, they are hand written
-			template<typename pass_t>
-			static inline auto addStructFwd( pass_t & pass, int, ast::StructDecl * decl ) -> decltype( pass.indexer.addStruct( decl ), void() ) {
-				ast::StructDecl * fwd = new ast::StructDecl( decl->location, decl->name );
-				fwd->parameters = decl->parameters;
-				pass.indexer.addStruct( fwd );
-			}
-
-			template<typename pass_t>
-			static inline void addStructFwd( pass_t &, long, ast::StructDecl * ) {}
-
-			template<typename pass_t>
-			static inline auto addUnionFwd( pass_t & pass, int, ast::UnionDecl * decl ) -> decltype( pass.indexer.addUnion( decl ), void() ) {
-				UnionDecl * fwd = new UnionDecl( decl->name );
-				fwd->parameters = decl->parameters;
-				pass.indexer.addUnion( fwd );
-			}
-
-			template<typename pass_t>
-			static inline void addUnionFwd( pass_t &, long, ast::UnionDecl * ) {}
-
-			template<typename pass_t>
-			static inline auto addStruct( pass_t & pass, int, const std::string & str ) -> decltype( pass.indexer.addStruct( str ), void() ) {
-				if ( ! pass.indexer.lookupStruct( str ) ) {
-					pass.indexer.addStruct( str );
-				}
-			}
-
-			template<typename pass_t>
-			static inline void addStruct( pass_t &, long, const std::string & ) {}
-
-			template<typename pass_t>
-			static inline auto addUnion( pass_t & pass, int, const std::string & str ) -> decltype( pass.indexer.addUnion( str ), void() ) {
-				if ( ! pass.indexer.lookupUnion( str ) ) {
-					pass.indexer.addUnion( str );
-				}
-			}
-
-			template<typename pass_t>
-			static inline void addUnion( pass_t &, long, const std::string & ) {}
-
-			#undef INDEXER_FUNC1
-			#undef INDEXER_FUNC2
-		};
+		template<typename pass_t> \
+		static inline void func( pass_t &, long, type1, type2 ) {}
+
+		INDEXER_FUNC1( addId     , DeclWithType *  );
+		INDEXER_FUNC1( addType   , NamedTypeDecl * );
+		INDEXER_FUNC1( addStruct , StructDecl *    );
+		INDEXER_FUNC1( addEnum   , EnumDecl *      );
+		INDEXER_FUNC1( addUnion  , UnionDecl *     );
+		INDEXER_FUNC1( addTrait  , TraitDecl *     );
+		INDEXER_FUNC2( addWith   , std::list< Expression * > &, Node * );
+
+		// A few extra functions have more complicated behaviour, they are hand written
+		// template<typename pass_t>
+		// static inline auto addStructFwd( pass_t & pass, int, ast::StructDecl * decl ) -> decltype( pass.indexer.addStruct( decl ), void() ) {
+		// 	ast::StructDecl * fwd = new ast::StructDecl( decl->location, decl->name );
+		// 	fwd->parameters = decl->parameters;
+		// 	pass.indexer.addStruct( fwd );
+		// }
+
+		// template<typename pass_t>
+		// static inline void addStructFwd( pass_t &, long, ast::StructDecl * ) {}
+
+		// template<typename pass_t>
+		// static inline auto addUnionFwd( pass_t & pass, int, ast::UnionDecl * decl ) -> decltype( pass.indexer.addUnion( decl ), void() ) {
+		// 	UnionDecl * fwd = new UnionDecl( decl->name );
+		// 	fwd->parameters = decl->parameters;
+		// 	pass.indexer.addUnion( fwd );
+		// }
+
+		// template<typename pass_t>
+		// static inline void addUnionFwd( pass_t &, long, ast::UnionDecl * ) {}
+
+		// template<typename pass_t>
+		// static inline auto addStruct( pass_t & pass, int, const std::string & str ) -> decltype( pass.indexer.addStruct( str ), void() ) {
+		// 	if ( ! pass.indexer.lookupStruct( str ) ) {
+		// 		pass.indexer.addStruct( str );
+		// 	}
+		// }
+
+		// template<typename pass_t>
+		// static inline void addStruct( pass_t &, long, const std::string & ) {}
+
+		// template<typename pass_t>
+		// static inline auto addUnion( pass_t & pass, int, const std::string & str ) -> decltype( pass.indexer.addUnion( str ), void() ) {
+		// 	if ( ! pass.indexer.lookupUnion( str ) ) {
+		// 		pass.indexer.addUnion( str );
+		// 	}
+		// }
+
+		// template<typename pass_t>
+		// static inline void addUnion( pass_t &, long, const std::string & ) {}
+
+		#undef INDEXER_FUNC1
+		#undef INDEXER_FUNC2
 	};
 };
+};
