<?php

/* MIT License

Copyright (c) 2018 Eridan Domoratskiy

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE. */

namespace Kmyacc;

use JLexPHP\AbstractLexer;
use JLexPHP\Token;

/**
 * Based on prototype file of PHP parser
 * written by Masato Bito
 *
 * @author Eridan Domoratskiy
 * @author Masato Bito
 */
abstract class AbstractParser {

    protected $yytranslate = [];

    /** @var bool Debug mode flag **/
    protected $yydebug = false;

    protected $yyaction = [];
    protected $yycheck = [];
    protected $yybase = [];
    protected $yydefault = [];
    protected $yygoto = [];
    protected $yygcheck = [];
    protected $yygbase = [];
    protected $yygdefault = [];
    protected $yylhs = [];
    protected $yylen = [];
    protected $yyastk = [];
    protected $yyval = null;

    /** @var AbstractLexer Lexer generated by JLexPHP */
    protected $lexer = null;

    /** @var callable[] Reduce callbacks */
    protected $reduceCallbacks = [];

    public function __construct(AbstractLexer $lexer) {
        $this->lexer = $lexer;

        $this->initReduceCallbacks();
    }

    abstract protected function initReduceCallbacks();

    protected function yyerror(string $msg) {
        throw new \Exception($msg);
    }

    /**
     * Parser entry point
     */
    public function yyparse() {
        $this->yyastk = [];
        $yysstk = [];

        $yyn = $yyl = 0;
        $yystate = 0;
        $yychar = -1;

        $yysp = 0;
        $yysstk[$yysp] = 0;
        $yyerrflag = 0;
        while (true) {
            $this->YYTRACE_NEWSTATE($yystate, $yychar);

            if ($this->yybase[$yystate] == 0) {
                $yyn = $this->yydefault[$yystate];
            } else {
                if ($yychar < 0) {
                    $token = $this->lexer->yylex() ?? new Token();
                    $yylval = $token->value;

                    if (($yychar = $token->type) <= 0) {
                        $yychar = 0;
                    }

                    $yychar = ($yychar < static::YYMAXLEX)?
                        $this->yytranslate[$yychar]:
                        static::YYBADCH;

                    $this->YYTRACE_READ($yychar);
                }

                if (
                    ((
                        ($yyn = ($this->yybase[$yystate] + $yychar)) >= 0 &&
                        $yyn < static::YYLAST &&
                        $this->yycheck[$yyn] == $yychar
                    ) || (
                        $yystate < static::YY2TBLSTATE &&

                        ($yyn = $this->yybase[$yystate + static::YYNLSTATES] + $yychar) >= 0 &&
                        $yyn < static::YYLAST &&
                        $this->yycheck[$yyn] == $yychar
                    )) &&
                    ($yyn = $this->yyaction[$yyn]) != static::YYDEFAULT
                ) {
                    /*
                     * >= YYNLSTATE: shift and reduce
                     * > 0: shift
                     * = 0: accept
                     * < 0: reduce
                     * = -static::YYUNEXPECTED: error
                     */
                    if ($yyn > 0) {
                        /* shift */

                        $this->YYTRACE_SHIFT($yychar);

                        ++$yysp;

                        $yysstk[$yysp] = $yystate = $yyn;
                        $this->yyastk[$yysp] = $yylval;
                        $yychar = -1;

                        if ($yyerrflag > 0) {
                            --$yyerrflag;
                        }

                        if ($yyn < static::YYNLSTATES) {
                            continue;
                        }

                        /* $yyn >= static::YYNLSTATES means shift-and-reduce */
                        $yyn -= static::YYNLSTATES;
                    } else {
                        $yyn = -$yyn;
                    }
                } else {
                    $yyn = $this->yydefault[$yystate];
                }
            }

            while (true) {
                /* reduce/error */
                if ($yyn == 0) {
                    /* accept */

                    $this->YYTRACE_ACCEPT();

                    return $this->yyval;
                } else if ($yyn != static::YYUNEXPECTED) {
                    /* reduce */
                    $yyl = $this->yylen[$yyn];
                    $n = $yysp - $yyl + 1;
                    $this->yyval = $this->yyastk[$n] ?? null;

                    $this->YYTRACE_REDUCE($yyn);

                    $this->reduceCallbacks[$yyn]($yysp);

                    /* Goto - shift nonterminal */
                    $yysp -= $yyl;
                    $yyn = $this->yylhs[$yyn];
                    if (
                        ($yyp = $this->yygbase[$yyn] + $yysstk[$yysp]) >= 0 &&
                        $yyp < static::YYGLAST &&
                        $this->yygcheck[$yyp] == $yyn
                    ) {
                        $yystate = $this->yygoto[$yyp];
                    } else {
                        $yystate = $this->yygdefault[$yyn];
                    }

                    ++$yysp;

                    $yysstk[$yysp] = $yystate;
                    $this->yyastk[$yysp] = $this->yyval;
                } else {
                    /* error */
                    switch ($yyerrflag) {
                    case 0:
                        $this->yyerror('syntax error');
                    case 1:
                    case 2:
                        $yyerrflag = 3;
                        /* Pop until error-expecting state uncovered */

                        while (
                            !((
                                ($yyn = $this->yybase[$yystate] + static::YYINTERRTOK) >= 0 &&
                                $yyn < static::YYLAST &&
                                $this->yycheck[$yyn] == static::YYINTERRTOK
                            ) || (
                                $yystate < static::YY2TBLSTATE &&

                                ($yyn = $this->yybase[$yystate + static::YYNLSTATES] + static::YYINTERRTOK) >= 0 &&
                                $yyn < static::YYLAST &&
                                $this->yycheck[$yyn] == static::YYINTERRTOK
                            ))
                        ) {
                            if ($yysp <= 0) {
                                return null;
                            }

                            $yystate = $yysstk[--$yysp];

                            $this->YYTRACE_POP($yystate);
                        }

                        $yyn = $this->yyaction[$yyn];

                        $this->YYTRACE_SHIFT(static::YYINTERRTOK);

                        $yysstk[++$yysp] = $yystate = $yyn;
                        break;

                    case 3:
                        $this->YYTRACE_DISCARD($yychar);

                        if ($yychar == 0) {
                            return null;
                        }

                        $yychar = -1;
                        break;
                    }
                }

                if ($yystate < static::YYNLSTATES) {
                    break;
                }

                /* >= static::YYNLSTATES means shift-and-reduce */
                $yyn = $yystate - static::YYNLSTATES;
            }
        }
    }

    private function yytokname($n) {
        switch ($n) {
            #switch-for-token-name;
        default:
            return "???";
        }
    }

    /** Traditional Debug Mode */
    protected function YYTRACE_NEWSTATE($state, $sym) {
        if ($this->yydebug) {
            echo "% State $state, Lookahead ".(($sym < 0)? "--none--": $this->yyterminals[$sym])."\n";
        }
    }

    protected function YYTRACE_READ($sym) {
        if ($this->yydebug) {
            echo "% Reading {$this->yyterminals[$sym]}\n";
        }
    }

    protected function YYTRACE_SHIFT($sym) {
        if ($this->yydebug) {
            echo "% Shift {$this->yyterminals[$sym]}\n";
        }
    }

    protected function YYTRACE_ACCEPT() {
        if ($this->yydebug) {
            echo "% Accepted.\n";
        }
    }

    protected function YYTRACE_REDUCE($n) {
        if ($this->yydebug) {
            echo "% Reduce by ($n) {$this->yyproduction[$n]}\n";
        }
    }

    protected function YYTRACE_POP($state) {
        if ($this->yydebug) {
            echo "% Recovering, uncovers state $state\n";
        }
    }

    protected function YYTRACE_DISCARD($sym) {
        if ($this->yydebug) {
            echo "% Discard {$this->yyterminals[$sym]}\n";
        }
    }
}

#tailcode;
