1: <?php
2:
3: namespace BN\Compiler\Parser;
4:
5: use BN\Collections\Stack;
6: use BN\Collections\Queue;
7: use BN\Compiler\Token\Token;
8: use BN\Compiler\Token\TokenType;
9:
10: class QueueAccumulator
11: {
12: private $stack;
13: private $queue;
14: private $errorHandler;
15: private $continueInParsing;
16:
17: public function __construct(ParserErrorHandler $errorHandler)
18: {
19: $this->errorHandler = $errorHandler;
20: $this->stack = new Stack();
21: }
22:
23: public function init()
24: {
25: $this->continueInParsing = true;
26: $this->queue = new Queue();
27: $this->stack->clear();
28: }
29:
30: public function noError()
31: {
32: return $this->continueInParsing;
33: }
34:
35: public function pushTokenToStack(Token $token)
36: {
37: $this->stack->push($token);
38: }
39:
40: public function popTokenFromStack()
41: {
42: return $this->stack->pop();
43: }
44:
45: public function isStackEmpty()
46: {
47: return $this->stack->isEmpty();
48: }
49:
50: public function isOperatorAtTopOfStack()
51: {
52: return $this->isTypeAtStackPeek(TokenType::OPERATOR)
53: || $this->isTypeAtStackPeek(TokenType::ASSIGN);
54: }
55:
56: public function isTypeAtStackPeek($tokenType)
57: {
58: return $this->stack->peek()->type == $tokenType;
59: }
60:
61: public function valueAtStackPeek()
62: {
63: return $this->stack->peek()->value;
64: }
65:
66: public function pushTokenFromStackToQueue()
67: {
68: $this->pushTokenToQueue($this->stack->pop());
69: }
70:
71: public function pushTokenToQueue(Token $token)
72: {
73: $this->queue->push($token);
74: }
75:
76: public function stopParsing($method, $arg = null)
77: {
78: $this->stack->clear();
79: $this->continueInParsing = false;
80: $this->errorHandler->$method($arg);
81: }
82:
83: public function getResult()
84: {
85: if ($this->noError()) {
86: return $this->queue;
87: } else {
88: return false;
89: }
90: }
91: }
92: