/*
 *  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 "Source.h"

#include "CompilationMessages.h"
#include "Debug.h"
#include "String.h"
#include "Lexer.h"
#include "Parser.h"
#include "EigenBackend/GenerationVisitor.h"
#include "AST/Tree.h"
#include "MathMLBackend/GenerationVisitor.h"

using namespace Cauchy;

struct Source::Private {
  String fileName;
  String source;
  bool isCompiled;
  CompilationMessages compilationMessages;
  AST::Tree* tree;
  DeclarationsRegistry* registry;
};

Source::Source() : d(new Private)
{
  d->isCompiled = false;
  d->tree = 0;
}

void Source::setSource(const String& _fileName, const String& _source, DeclarationsRegistry* _registry)
{
  d->fileName = _fileName;
  d->source = _source;
  d->registry = _registry;
}

void Source::compile()
{
  delete d->tree;
  
  std::istringstream iss(d->source);
  Lexer lexer( &iss );
  Parser parser( &lexer, d->registry );
  d->tree = parser.parse();
  d->compilationMessages = parser.compilationMessages();
  if(d->tree)
  {
    d->isCompiled = true;
  } else {
    d->isCompiled = false;
  }
}

bool Source::isCompiled()
{
  return d->isCompiled;
}

CompilationMessages Source::compilationMessages() const
{
  return d->compilationMessages;
}

String Source::generate(const Cauchy::Options& options, const String& backend)
{
  if(backend == "MathML")
  {
    MathMLBackend::GenerationVisitor v(options);
    d->tree->generate(&v);
    return v.result();
  } else {
    CAUCHY_ASSERT(backend == "eigen3");
    EigenBackend::GenerationVisitor v(options);
    v.loadFunctionsDeclarations(d->registry);
    d->tree->generate(&v);
    return v.result();
  }
}
