// Copyright (C) 2003, 2005 Daisuke Arai <darai@users.sourceforge.jp>
// Copyright (C) 2008, 2013 panacoran <panacoran@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: FunctionDefinitionNode.cs 472 2013-06-26 15:26:49Z panacoran $

using System.Collections.Generic;

namespace Protra.Lib.Lang
{
    /// <summary>
    /// 関数定義のノードを表すクラス。
    /// </summary>
    public class FunctionDefinitionNode : ExecutableNode
    {
        /// <summary>
        /// 関数名
        /// </summary>
        private string _name;

        /// <summary>
        /// 引数名のリストを取得する。
        /// </summary>
        public List<string> Arguments { get; private set; }

        /// <summary>
        /// ノードのリストを取得する。
        /// </summary>
        public List<ExecutableNode> Nodes { get; private set; }

        /// <summary>
        /// 構文解析する。
        /// </summary>
        /// <exception cref="Protra.Lib.Lang.ParseException">
        /// 構文解析中にエラーが発生したときにthrowされる。
        /// </exception>
        /// <return>
        /// 解析した結果のノード。
        /// </return>
        public override ExecutableNode Parse(Scanner scanner)
        {
            Token = scanner.Token;

            // 関数名のチェック
            scanner.Scan();
            if (scanner.Token.Type != TokenType.FunctionName)
                throw new ParseException("function name expected", scanner.Token);
            _name = scanner.Token.Value;

            // 引数のチェック
            Arguments = new List<string>();
            scanner.Scan();
            if (scanner.Token.Value != "(")
            {
                if (scanner.Token.Value != ";")
                    throw new ParseException("';' expected", scanner.Token);
            }
            else
            {
                scanner.Scan();
                if (scanner.Token.Value == ")")
                {
                    scanner.Scan();
                    if (scanner.Token.Value != ";")
                        throw new ParseException("';' expected", scanner.Token);
                }
                else
                {
                    do
                    {
                        if (scanner.Token.Type != TokenType.LocalVariable)
                            throw new ParseException("function argument expected", scanner.Token);
                        Arguments.Add(scanner.Token.Value);
                        scanner.Scan();
                        if (scanner.Token.Value == ")")
                        {
                            scanner.Scan();
                            if (scanner.Token.Value != ";")
                                throw new ParseException("';' expected", scanner.Token);
                            break;
                        }
                        if (scanner.Token.Value != ",")
                            throw new ParseException("',' or ')' expected", scanner.Token);
                    } while (scanner.Scan());
                }
            }

            // 本体のチェック
            Nodes = new List<ExecutableNode>();
            while (scanner.Scan())
            {
                if (scanner.Token.Value == "end")
                {
                    scanner.Scan();
                    if (scanner.Token.Value != ";")
                        throw new ParseException("';' expected", scanner.Token);
                    return this;
                }
                Nodes.Add(new StatementNode().Parse(scanner));
            }

            throw new ParseException("unexpected EOF", Token);
        }

        /// <summary>
        /// プログラムを実行する。
        /// </summary>
        /// <exception cref="Protra.Lib.Lang.RuntimeException">
        /// プログラム実行中にエラーが発生した場合にthrowされる。
        /// </exception>
        /// <param name="resource">リソース</param>
        /// <param name="at">int型@作用素の値</param>
        /// <param name="ats">string型@作用素の値</param>
        /// <returns>実行結果</returns>
        public override Result Execute(Resource resource, int at, string ats)
        {
            // 関数テーブルに登録
            var ft = new FunctionType(_name, Arguments.Count);
            if (resource.FunctionTable.ContainsKey(ft))
                throw new RuntimeException("function is already defined --- " + ft, Token);
            resource.FunctionTable[ft] = this;
            return Result.Normal;
        }
    }
}