// 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: LiteralNode.cs,v 1.3 2007-12-27 08:34:39 panacoran Exp $

using System;

namespace Protra.Lib.Lang
{
	/// <summary>
	/// リテラルのノードを表すクラスです。
	/// </summary>
	public class LiteralNode : Node
	{
		/// <summary>
		/// 値
		/// </summary>
		private Value val;

		/// <summary>
		/// コンストラクタ
		/// </summary>
		public LiteralNode() {}

		/// <summary>
		/// コンストラクタ
		/// </summary>
		/// <param name="val">値</param>
		public LiteralNode(Value val)
		{
			this.val = val;
		}

		/// <summary>
		/// 文脈を解析します。
		/// </summary>
		/// <exception cref="Protra.Lib.Lang.ParseException">
		/// 文脈にエラーがある場合にthrowされます。
		/// </exception>
		/// <param name="context">コンテキスト</param>
		public override void Parse(Context context)
		{
			this.ContextToken = (ContextToken)context.Current;

			ContextToken ct = (ContextToken)context.Current;
			if(ct.IsInt)
				val = new Value(int.Parse(ct.ToString()));
			else if(ct.IsFloat)
				val = new Value(double.Parse(ct.ToString()));
			else if(ct.IsString)
			{
				string str = ct.ToString();
				val = new Value(str.Substring(1, str.Length - 2));
			}

			context.MoveNext();
		}

		/// <summary>
		/// 構文木を簡略化します。
		/// </summary>
		/// <returns>簡略化されたノード</returns>
		public override Node Simplify()
		{
			return this;
		}

		/// <summary>
		/// プログラムを実行します。
		/// </summary>
		/// <exception cref="Protra.Lib.Lang.RuntimeException">
		/// プログラム実行中にエラーが発生した場合にthrowされます。
		/// </exception>
		/// <param name="resource">リソース</param>
		/// <param name="at">@作用素の値</param>
		/// <returns>実行結果</returns>
		public override Value Execute(Resource resource, int at)
		{
			return val;
		}
	}
}
