// Copyright (C) 2003, 2005 Daisuke Arai <darai@users.sourceforge.jp>
// 
// This program is part of Protra.
//
// Protra is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
// 
// $Id: InterpreterFacade.cs,v 1.3 2007-12-27 08:34:39 panacoran Exp $

using System;

namespace Protra.Lib.Lang
{
	/// <summary>
	/// プログラムの実行処理を担うFacadeです。
	/// </summary>
	public class InterpreterFacade
	{
		/// <summary>
		/// プログラムのノード
		/// </summary>
		Node node = new ProgramNode();
		/// <summary>
		/// リソース
		/// </summary>
		private Resource resource;

		/// <summary>
		/// コンストラクタ
		/// </summary>
		/// <exception cref="Protra.Lib.Lang.ParseException">
		/// プログラムの構文解析中にエラーが発生した場合にthrowされます。
		/// </exception>
		/// <param name="file">プログラムファイルのパス</param>
		/// <param name="factory">IExecuterを生成するFactory</param>
		public InterpreterFacade(string file, IExecuterFactory factory)
		{
			Context context = new Context(file);
			context.LibraryPath = Global.DirLib;
			try
			{
				node = new ProgramNode();
				node.Parse(context);
				node = node.Simplify();
			}
			catch(ParseException exc)
			{
				ContextToken ct = exc.ContextToken;
				throw new ParseException
					("parse error in " + ct.FileName + ":" + (ct.Line + 1) + ": " + exc.Message, exc.ContextToken);
			}

			resource = new Resource();
			resource.Stack = new StackArea();
			resource.GlobalVariableTable = new VariableTable();
			resource.FunctionTable = new FunctionTable();
			resource.ExecuterFactory = factory;
		}

		/// <summary>
		/// プログラムを実行します。
		/// </summary>
		/// <exception cref="Protra.Lib.Lang.RuntimeException">
		/// プログラム実行中にエラーが発生した場合にthrowされます。
		/// </exception>
		/// <returns>プログラムの戻り値です。</returns>
		public Value Execute()
		{
			resource.Stack.Clear();
			resource.FunctionTable.Clear();
			try
			{
				return node.Execute(resource, 0);
			}
			catch(RuntimeException exc)
			{
				ContextToken ct = exc.ContextToken;
				throw new RuntimeException
					("runtime error in " + ct.FileName + ":" + (ct.Line + 1) + ": " + exc.Message, exc.ContextToken);
			}
		}

		/// <summary>
		/// グローバル変数のテーブルを取得または設定します。
		/// </summary>
		public VariableTable GlobalVariableTable
		{
			get { return resource.GlobalVariableTable; }
			set { resource.GlobalVariableTable = value; }
		}
	}
}
