/*
 * testsCFG.cpp
 *
 *  Created on: Jul 17, 2015
 *      Author: pgess
 */

#include "passmanager.h"
#include "pass/dfapass.h"
#include "pass/cfapass.h"

#include "analysis/DominatorsTreeAnalysisProvider.h"

#include "gtest/gtest.h"

#include <boost/scoped_ptr.hpp>
#include <boost/smart_ptr/scoped_array.hpp>

using namespace xreate;
using namespace std;

TEST(CFG, testFunctionAnnotationsClasp){
	string&& program =
			"f2 = function::int; annotationF2 {\n"
			"    0\n"
			"}\n"
			"\n"
			"f1 = function:: int; entry; annotationF1 {\n"
			"    f2() + 10\n"
			"}";


	PassManager* man = PassManager::prepareForCode(move(program));
	man->runWithoutCompilation();

	ClaspLayer::ModelFragment answer = man->clasp->query("annotationF1");
	int countNoneValue = 0;
	if (answer)
		countNoneValue = std::distance(answer->first, answer->second);
	EXPECT_EQ(1, countNoneValue);

	answer = man->clasp->query("annotationF2");
	countNoneValue = 0;
	if (answer)
		countNoneValue = std::distance(answer->first, answer->second);
    EXPECT_EQ(1, countNoneValue);
}

TEST(CFG, testLoopContextExists){
	PassManager* man = PassManager::prepareForCode (
		"interface(cfa){\n"
		"    operator fold:: annotation1.\n"
		"}\n"
		"\n"
		"main = function:: int; entry {\n"
		"    x = [1..10]:: [int].\n"
		"    sum = loop fold (x->el:: int, 0->sum):: int {\n"
		"        el + sum + f1()\n"
		"    }.  \n"
		"    sum\n"
		"}"
		"f1 = function::int {\n"
		"	x = 0:: int.		 "
		"    x\n"
		"}"
    );

	man->runWithoutCompilation();
}

TEST(CFG, CFGRoots){
    std::string program = 
R"CODE(
    main = function::int{a()+ b()}
    a= function::int {c1() + c2()}
    b= function::int {c2()}
    c1=function::int{0}
    c2=function::int{0}
)CODE";
    
    boost::scoped_ptr<PassManager> manager
        (PassManager::prepareForCode(move(program)));
    
    manager->registerPass(new CFAPass(manager.get()) , PassId::CFGPass);
    manager->executePasses();
    manager->clasp->run();
    
    DominatorsTreeAnalysisProvider domProvider;
    domProvider.run(manager->clasp);
    
    DominatorsTreeAnalysisProvider::Dominators expectedFDom= {
         {0, {0, 9}}
        ,{1, {1, 4}}
        ,{2, {7, 8}}
        ,{3, {2, 3}}
        ,{4, {5, 6}}
    };
    
    DominatorsTreeAnalysisProvider::Dominators expectedPostDom= {
         {0, {5, 6}}
        ,{1, {3, 4}}
        ,{2, {8, 9}}
        ,{3, {1, 2}}
        ,{4, {7, 10}}
    };
    
    ASSERT_EQ(expectedFDom, domProvider.getForwardDominators());
    ASSERT_EQ(expectedPostDom, domProvider.getPostDominators());
}
