/* 
 * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
 *
 * This program 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; version 2 of the
 * License.
 * 
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

#ifndef _MYSQL_PARSER_H_
#define _MYSQL_PARSER_H_

#include "mysql-parser-common.h"
#include <stack>

/**
 * C++ interface for the ANTLR based MySQL parser.
 */

// Describes the type of a given query.
enum MySQLQueryType
{
  QtUnknown,
  QtAmbiguous,

  // DDL
  QtAlterDatabase,
  QtAlterLogFileGroup,
  QtAlterFunction,
  QtAlterProcedure,
  QtAlterServer,
  QtAlterTable,
  QtAlterTableSpace,
  QtAlterEvent,
  QtAlterView,

  QtCreateTable,
  QtCreateIndex,
  QtCreateDatabase,
  QtCreateEvent,
  QtCreateView,
  QtCreateProcedure,
  QtCreateFunction,
  QtCreateUdf,
  QtCreateTrigger,
  QtCreateLogFileGroup,
  QtCreateServer,
  QtCreateTableSpace,

  QtDropDatabase,
  QtDropEvent,
  QtDropFunction, // Includes UDF.
  QtDropProcedure,
  QtDropIndex,
  QtDropLogfileGroup,
  QtDropServer,
  QtDropTable,
  QtDropTablespace,
  QtDropTrigger,
  QtDropView,

  QtRenameTable,
  QtTruncateTable,

  // DML
  QtCall,
  QtDelete,
  QtDo,

  QtHandler, // Do we need Handler open/close etc.?
  
  QtInsert,
  QtLoadData,
  QtLoadXML,
  QtReplace,
  QtSelect,
  QtUpdate,

  QtPartition, // Cannot be used standalone.

  QtStartTransaction,
  QtBeginWork,
  QtCommit,
  QtRollbackWork,
  QtSetAutoCommit, // "set autocommit" is especially mentioned in transaction help, so identify this too.
  QtSetTransaction,

  QtSavepoint,
  QtReleaseSavepoint,
  QtRollbackSavepoint,

  QtLock,
  QtUnlock,

  QtXA,    // Do we need xa start, xa end etc.?
  
  QtPurge,
  QtChangeMaster,
  QtReset,
  QtResetMaster,
  QtResetSlave,
  QtStartSlave,
  QtStopSlave,
  QtLoadDataMaster,
  QtLoadTableMaster,

  QtPrepare,
  QtExecute,
  QtDeallocate,

  // Database administration
  QtAlterUser,
  QtCreateUser,
  QtDropUser,
  QtGrantProxy,
  QtGrant,
  QtRenameUser,
  QtRevokeProxy,
  QtRevoke,
  
  QtAnalyzeTable,
  QtCheckTable,
  QtChecksumTable,
  QtOptimizeTable,
  QtRepairTable,
  QtBackUpTable,
  QtRestoreTable,

  QtInstallPlugin,
  QtUninstallPlugin,

  QtSet,   // Any variable assignment.
  QtSetPassword,

  QtShow,
  QtShowAuthors,
  QtShowBinaryLogs,
  QtShowBinlogEvents,
  QtShowRelaylogEvents,
  QtShowCharset,
  QtShowCollation,
  QtShowColumns,
  QtShowContributors,
  QtShowCreateDatabase,
  QtShowCreateEvent,
  QtShowCreateFunction,
  QtShowCreateProcedure,
  QtShowCreateTable,
  QtShowCreateTrigger,
  QtShowCreateView,
  QtShowDatabases,
  QtShowEngineStatus,
  QtShowStorageEngines,
  QtShowErrors,
  QtShowEvents,
  QtShowFunctionCode,
  QtShowFunctionStatus,
  QtShowGrants,
  QtShowIndexes, // Index, Indexes, Keys
  QtShowInnoDBStatus,
  QtShowMasterStatus,
  QtShowOpenTables,
  QtShowPlugins,
  QtShowProcedureStatus,
  QtShowProcedureCode,
  QtShowPrivileges,
  QtShowProcessList,
  QtShowProfile,
  QtShowProfiles,
  QtShowSlaveHosts,
  QtShowSlaveStatus,
  QtShowStatus,
  QtShowVariables,
  QtShowTableStatus,
  QtShowTables,
  QtShowTriggers,
  QtShowWarnings,

  QtCacheIndex,
  QtFlush,
  QtKill,   // Connection, Query
  QtLoadIndex,

  QtExplainTable,
  QtExplainStatement,
  QtHelp,
  QtUse,

  QtSentinel
};

class MySQLRecognizer;

/**
 * The tree walker allows to easily navigate the AST generated by the recognizer and get all kind
 * of token information (like position, type, content etc.).
 */
class MYSQL_PARSER_PUBLIC_FUNC MySQLRecognizerTreeWalker
{
  friend class MySQLRecognizer; // For protected c-tor.
public:
  MySQLRecognizer *recognizer() { return _recognizer; };
  
  bool next();
  bool next_sibling();
  bool previous();
  bool previous_by_index();
  bool previous_sibling();
  bool up();
  bool advance_to_position(int line, int offset);
  bool advance_to_type(unsigned int type, bool recurse);
  void go_to_subquery_start();
  bool skip_token_sequence(unsigned int start_token, ...);
  unsigned int look_ahead(bool recursive);
  unsigned int parent_type();
  unsigned int previous_type();
  
  void reset();
  void push();
  bool pop();
  void remove_tos();
  
  // Properties of the current token.
  bool is_nil();
  bool is_subtree();
  bool is_identifier();
  bool is_keyword();
  bool is_relation();
  bool is_first_child();
  bool is_number();
  bool is_operator();

  std::string token_text();
  unsigned int token_type();
  unsigned int token_line();
  unsigned int token_start();
  int token_length();
  
  MySQLQueryType get_current_query_type();
  MySQLQueryType get_main_query_type();

protected:
  MySQLRecognizerTreeWalker(MySQLRecognizer *recognizer, pANTLR3_BASE_TREE tree);
  
  pANTLR3_BASE_TREE get_next(pANTLR3_BASE_TREE node, bool recurse);
  pANTLR3_BASE_TREE get_previous(pANTLR3_BASE_TREE node, bool recurse);
  pANTLR3_BASE_TREE get_previous_by_index(pANTLR3_BASE_TREE node);
  void print_token(pANTLR3_BASE_TREE tree);
private:
  pANTLR3_BASE_TREE _origin;
  pANTLR3_BASE_TREE _tree;
  std::stack<pANTLR3_BASE_TREE> _token_stack;
  std::vector<pANTLR3_BASE_TREE> _token_list; // A list of all tokens in incoming order (no hierarchy).
  MySQLRecognizer *_recognizer;
};

class MYSQL_PARSER_PUBLIC_FUNC MySQLRecognizer : public MySQLParsingBase
{
public:
  MySQLRecognizer(const char *text, int length, bool is_utf8, long server_version, 
    const std::string &sql_mode, const std::set<std::string> &charsets);
  virtual ~MySQLRecognizer();
  
  std::string dump_tree();
  std::string dump_tree(pANTLR3_BASE_TREE tree, const std::string &indentation);
  
  MySQLRecognizerTreeWalker tree_walker();

  std::string token_text(pANTLR3_BASE_TREE node);
  MySQLQueryType query_type();
  MySQLQueryType query_type(pANTLR3_BASE_TREE node);

  // Internal routine, called from the error callback.
  void add_error(const std::string &text, ANTLR3_UINT32 error, ANTLR3_UINT32 token, ANTLR3_UINT32 line,
                 ANTLR3_UINT32 offset, ANTLR3_UINT32 length);
protected:
  void parse();

private:
  class Private;
  Private *d;
};

#endif // _MYSQL_PARSER_H_
