///////////////////////////////////////////////////////////////////////////
// Copyright (c) 2013 Academy of Motion Picture Arts and Sciences 
// ("A.M.P.A.S."). Portions contributed by others as indicated.
// All rights reserved.
// 
// A worldwide, royalty-free, non-exclusive right to copy, modify, create
// derivatives, and use, in source and binary forms, is hereby granted, 
// subject to acceptance of this license. Performance of any of the 
// aforementioned acts indicates acceptance to be bound by the following 
// terms and conditions:
//
//  * Copies of source code, in whole or in part, must retain the 
//    above copyright notice, this list of conditions and the 
//    Disclaimer of Warranty.
//
//  * Use in binary form must retain the above copyright notice, 
//    this list of conditions and the Disclaimer of Warranty in the
//    documentation and/or other materials provided with the distribution.
//
//  * Nothing in this license shall be deemed to grant any rights to 
//    trademarks, copyrights, patents, trade secrets or any other 
//    intellectual property of A.M.P.A.S. or any contributors, except 
//    as expressly stated herein.
//
//  * Neither the name "A.M.P.A.S." nor the name of any other 
//    contributors to this software may be used to endorse or promote 
//    products derivative of or based on this software without express 
//    prior written permission of A.M.P.A.S. or the contributors, as 
//    appropriate.
// 
// This license shall be construed pursuant to the laws of the State of 
// California, and any disputes related thereto shall be subject to the 
// jurisdiction of the courts therein.
//
// Disclaimer of Warranty: THIS SOFTWARE IS PROVIDED BY A.M.P.A.S. AND 
// CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, 
// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS 
// FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED. IN NO 
// EVENT SHALL A.M.P.A.S., OR ANY CONTRIBUTORS OR DISTRIBUTORS, BE LIABLE 
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, RESITUTIONARY, 
// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 
// THE POSSIBILITY OF SUCH DAMAGE.
//
// WITHOUT LIMITING THE GENERALITY OF THE FOREGOING, THE ACADEMY 
// SPECIFICALLY DISCLAIMS ANY REPRESENTATIONS OR WARRANTIES WHATSOEVER 
// RELATED TO PATENT OR OTHER INTELLECTUAL PROPERTY RIGHTS IN THE ACADEMY 
// COLOR ENCODING SYSTEM, OR APPLICATIONS THEREOF, HELD BY PARTIES OTHER 
// THAN A.M.P.A.S., WHETHER DISCLOSED OR UNDISCLOSED.
///////////////////////////////////////////////////////////////////////////


#ifndef INCLUDED_CTL_PARSER_H
#define INCLUDED_CTL_PARSER_H

//-----------------------------------------------------------------------------
//
//	class Parser -- the parser for the color transformation language.
//	The parser converts the sequence of tokens that is generated by
//	the lexical analyzer into an abstract syntax tree.
//	The parser also computes the value types of all expressions, and
//	it simplifies expressions by evaluating constant subexpressions.
//
//-----------------------------------------------------------------------------

#include <CtlLex.h>
#include <CtlSyntaxTree.h>
#include <CtlType.h>
#include <vector>

namespace Ctl {

class SymbolTable;
class Interpreter;


class Parser
{
  public:

     Parser (LContext &lcontext, Interpreter &interpreter);
    ~Parser ();

    SyntaxNodePtr	parseInput ();

    Interpreter &	interpreter ()		{return _interpreter;}

  private:

    enum AllocationMode
    {
	AM_STATIC,
	AM_AUTO
    };

    void		parseCtlVersion ();
    void		parseImportList ();
    void		parseImportStatement ();
    SyntaxNodePtr	parseModuleBody ();
    ModuleNodePtr	parseFunctionOrConstList ();
    FunctionNodePtr	parseFunction ();

    void		parseParameterList
				(ParamVector &parameters,
				 const std::string &funcName);

    void		parseParameter
				(ParamVector &parameters,
				 const std::string &funcName,
				 bool &foundDefaults);

    StatementNodePtr	parseCompoundStatement();
    StatementNodePtr	parseStatement();

    StatementNodePtr	parseVariableDefinition
				(AllocationMode mode,
				 DataTypePtr baseType = 0);

    StatementNodePtr    parseStructDefinition (AllocationMode mode);
    StatementNodePtr	parseExprVariableDefinitionOrAssign();
    StatementNodePtr	parseAssignment (ExprNodePtr lhs);
    StatementNodePtr	parseSimpleAssignment (ExprNodePtr lhs);
    StatementNodePtr	parseExprStatement (ExprNodePtr expr);
    StatementNodePtr	parseSimpleExprStatement (ExprNodePtr expr);
    StatementNodePtr	parseForStatement();
    StatementNodePtr	parseForUpdateStatement();
    StatementNodePtr	parseIfStatement();
    StatementNodePtr	parsePrintStatement();
    StatementNodePtr	parseNullStatement();
    StatementNodePtr	parseReturnStatement();
    StatementNodePtr	parseWhileStatement();
    ExprNodePtr		parseExpression();
    ExprNodePtr		parseOrExpression ();
    ExprNodePtr		parseAndExpression ();
    ExprNodePtr		parseBitXorExpression ();
    ExprNodePtr		parseBitOrExpression ();
    ExprNodePtr		parseBitAndExpression ();
    ExprNodePtr		parseEqualityExpression ();
    ExprNodePtr		parseRelationalExpression ();
    ExprNodePtr		parseShiftExpression ();
    ExprNodePtr		parseAdditiveExpression ();
    ExprNodePtr		parseMultiplicativeExpression ();
    ExprNodePtr		parseUnaryExpression ();
    ExprNodePtr		parsePrimaryExpression ();
    ExprNodePtr         parseMemberArrayExpression (ExprNodePtr lhs);
    std::string		parseScopedString ();
    NameNodePtr		parseScopedName ();
    int	          	parseExprList (ExprNodeVector &arguments);

    bool                parseInitializer
				(ExprNodePtr &initialValue,
				 DataTypePtr dataType,
				 SizeVector &sizes);

    bool                parseInitializerRecursive
				(DataTypePtr dataType,
				 ExprNodeVector &elements,
				 SizeVector &s,
				 int depth);

    DataTypePtr		parseBaseType ();
    bool		parseVaryingHint ();
    void		parseArraySize (SizeVector &sizes);

    ExprNodePtr		evaluateExpression
				(ExprNodePtr expr,
				 TypePtr targetType);

    VariableNodePtr	variableDefinitionNoInit
				(AllocationMode mode,
				 int lineNumber,
				 const std::string &name,
				 const DataTypePtr &baseType,
				 const SizeVector &declArraySizes);

    VariableNodePtr	variableDefinitionImport
				(AllocationMode mode,
				 int lineNumber,
				 const std::string &name,
				 bool isConst,
				 const DataTypePtr &baseType,
				 const SizeVector &declArraySizes,
				 ExprNodePtr &initialValue);

    VariableNodePtr	variableDefinitionCurlyBraces
				(AllocationMode mode,
				 int lineNumber,
				 const std::string &name,
				 bool isConst,
				 const DataTypePtr &baseType,
				 const SizeVector &declArraySizes,
				 ExprNodePtr &initialValue);

    VariableNodePtr	variableDefinitionAssignExpr
				(AllocationMode mode,
				 int lineNumber,
				 const std::string &name,
				 bool isConst,
				 const DataTypePtr &baseType,
				 const SizeVector &declArraySizes,
				 ExprNodePtr &initialValue);

    VariableNodePtr	variableDefinitionExprSideEffect
				(AllocationMode mode,
				 int lineNumber,
				 const std::string &name,
				 bool isConst,
				 const DataTypePtr &baseType,
				 const SizeVector &declArraySizes);

    const Token &	token () const		{return _lex.token();}
    const std::string &	fileName () const	{return _lcontext.fileName();}
    SymbolTable &	symtab () const		{return _lcontext.symtab();}
    const Module *	module () const		{return _lcontext.module();}
    int			currentLineNumber () const;

    int			tokenIntValue () const;
    float		tokenFloatValue () const;
    const std::string &	tokenStringValue () const;

    void		next ()			{_lex.next();}

    void		match (Token expectedToken);
    void		recover (Token expectedToken);
    void		giveUp ();
    void		syntaxError ();
    void		staticVariableError ();
    void		foundError (int lineNumber, Error error);
    int			numErrors () const	{return _lcontext.numErrors();}

    void		duplicateName (const std::string &name,
				       int lineNumber,
				       const std::string &fileName);

    void		undefinedName (const std::string &name);

    Lex			_lex;
    LContext &		_lcontext;
    Interpreter &	_interpreter;

    StatementNodePtr    _firstConst;
    StatementNodePtr    _lastConst;
};


void loadModuleRecursive (Parser &parser, const std::string &moduleName);


} // namespace Ctl

#endif
