/*
 *  Copyright (c) 2010 Cyrille Berger <cberger@cberger.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * either version 2, or (at your option) any later version of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this library; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 */

#include "Tree.h"

#include <algorithm>
#include <list>

#include "Statement.h"
#include "../Macros_p.h"
#include "GenerationVisitor.h"
#include "FunctionDefinition.h"
#include "../Utils_p.h"
#include "../Variable.h"

using namespace Cauchy::AST;

struct Tree::Private {
  std::list<Statement*> main;
  std::list<FunctionDefinition*> functions;
  std::list<Variable*> globals;
};

Tree::Tree() : d(new Private)
{
}

Tree::~Tree()
{
  deleteAll(d->main);
  deleteAll(d->functions);
  deleteAll(d->globals);
  delete d;
}

void Tree::appendToMain(Statement* statement)
{
  d->main.push_back(statement);
}

void Tree::appendFunction(FunctionDefinition* function)
{
  d->functions.push_back(function);
}

void Tree::appendGlobal(Cauchy::Variable* global)
{
  if(std::find(d->globals.begin(), d->globals.end(), global) == d->globals.end())
  {
    d->globals.push_back(global);
  }
}

void Tree::generate( GenerationVisitor* _generationVisitor )
{
  foreach(Cauchy::Variable* var, d->globals)
  {
    _generationVisitor->declareGlobal(var);
  }
  foreach(FunctionDefinition* f, d->functions)
  {
    f->generate(_generationVisitor);
  }
  if(not d->main.empty())
  {
    _generationVisitor->startMainFunction();
    foreach(Statement* statement, d->main)
    {
      statement->generateStatement(_generationVisitor);
    }
  }
}
