parse_engine.php 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. <?php
  2. /*
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU Library General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program; if not, write to the Free Software
  15. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
  16. */
  17. define('LIME_CALL_PROTOCOL', '$tokens, &$result');
  18. abstract class lime_parser {
  19. }
  20. class parse_error extends Exception {} # If this happens, the input doesn't match the grammar.
  21. class parse_bug extends Exception {} # If this happens, I made a mistake.
  22. class parse_unexpected_token extends parse_error {
  23. function __construct($type, $state) {
  24. parent::__construct("Unexpected token of type ($type)");
  25. $this->type = $type;
  26. $this->state = $state;
  27. }
  28. }
  29. class parse_premature_eof extends parse_error {
  30. function __construct() {
  31. parent::__construct("Premature EOF");
  32. }
  33. }
  34. class parse_stack {
  35. function __construct($qi) {
  36. $this->q = $qi;
  37. $this->qs = array();
  38. $this->ss = array();
  39. }
  40. function shift($q, $semantic) {
  41. $this->ss[] = $semantic;
  42. $this->qs[] = $this->q;
  43. $this->q = $q;
  44. # echo "Shift $q -- $semantic<br/>\n";
  45. }
  46. function top_n($n) {
  47. if (!$n) return array();
  48. return array_slice($this->ss, 0-$n);
  49. }
  50. function pop_n($n) {
  51. if (!$n) return array();
  52. $qq = array_splice($this->qs, 0-$n);
  53. $this->q = $qq[0];
  54. return array_splice($this->ss, 0-$n);
  55. }
  56. function occupied() { return !empty($this->ss); }
  57. function index($n) {
  58. if ($n) $this->q = $this->qs[count($this->qs)-$n];
  59. }
  60. function text() {
  61. return $this->q." : ".implode(' . ', array_reverse($this->qs));
  62. }
  63. }
  64. class parse_engine {
  65. function __construct($parser) {
  66. $this->parser = $parser;
  67. $this->qi = $parser->qi;
  68. $this->rule = $parser->a;
  69. $this->step = $parser->i;
  70. #$this->prepare_callables();
  71. $this->reset();
  72. #$this->debug = false;
  73. }
  74. function reset() {
  75. $this->accept = false;
  76. $this->stack = new parse_stack($this->qi);
  77. }
  78. private function enter_error_tolerant_state() {
  79. while ($this->stack->occupied()) {
  80. if ($this->has_step_for('error')) return true;
  81. $this->drop();
  82. };
  83. return false;
  84. }
  85. private function drop() { $this->stack->pop_n(1); }
  86. function eat_eof() {
  87. {/*
  88. So that I don't get any brilliant misguided ideas:
  89. The "accept" step happens when we try to eat a start symbol.
  90. That happens because the reductions up the stack at the end
  91. finally (and symetrically) tell the parser to eat a symbol
  92. representing what they've just shifted off the end of the stack
  93. and reduced. However, that doesn't put the parser into any
  94. special different state. Therefore, it's back at the start
  95. state.
  96. That being said, the parser is ready to reduce an EOF to the
  97. empty program, if given a grammar that allows them.
  98. So anyway, if you literally tell the parser to eat an EOF
  99. symbol, then after it's done reducing and accepting the prior
  100. program, it's going to think it has another symbol to deal with.
  101. That is the EOF symbol, which means to reduce the empty program,
  102. accept it, and then continue trying to eat the terminal EOF.
  103. This infinte loop quickly runs out of memory.
  104. That's why the real EOF algorithm doesn't try to pretend that
  105. EOF is a terminal. Like the invented start symbol, it's special.
  106. Instead, we pretend to want to eat EOF, but never actually
  107. try to get it into the parse stack. (It won't fit.) In short,
  108. we look up what reduction is indicated at each step in the
  109. process of rolling up the parse stack.
  110. The repetition is because one reduction is not guaranteed to
  111. cascade into another and clean up the entire parse stack.
  112. Rather, it will instead shift each partial production as it
  113. is forced to completion by the EOF lookahead.
  114. */}
  115. # We must reduce as if having read the EOF symbol
  116. do {
  117. # and we have to try at least once, because if nothing
  118. # has ever been shifted, then the stack will be empty
  119. # at the start.
  120. list($opcode, $operand) = $this->step_for('#');
  121. switch ($opcode) {
  122. case 'r': $this->reduce($operand); break;
  123. case 'e': $this->premature_eof(); break;
  124. default: throw new parse_bug(); break;
  125. }
  126. } while ($this->stack->occupied());
  127. {/*
  128. If the sentence is well-formed according to the grammar, then
  129. this will eventually result in eating a start symbol, which
  130. causes the "accept" instruction to fire. Otherwise, the
  131. step('#') method will indicate an error in the syntax, which
  132. here means a premature EOF.
  133. Incedentally, some tremendous amount of voodoo with the parse
  134. stack might help find the beginning of some unfinished
  135. production that the sentence was cut off during, but as a
  136. general rule that would require deeper knowledge.
  137. */}
  138. if (!$this->accept) throw new parse_bug();
  139. return $this->semantic;
  140. }
  141. private function premature_eof() {
  142. $seen = array();
  143. while ($this->enter_error_tolerant_state()) {
  144. if (isset($seen[$this->state()])) {
  145. // This means that it's pointless to try here.
  146. // We're guaranteed that the stack is occupied.
  147. $this->drop();
  148. continue;
  149. }
  150. $seen[$this->state()] = true;
  151. $this->eat('error', NULL);
  152. if ($this->has_step_for('#')) {
  153. // Good. We can continue as normal.
  154. return;
  155. } else {
  156. // That attempt to resolve the error condition
  157. // did not work. There's no point trying to
  158. // figure out how much to slice off the stack.
  159. // The rest of the algorithm will make it happen.
  160. }
  161. }
  162. throw new parse_premature_eof();
  163. }
  164. private function current_row() { return $this->step[$this->state()]; }
  165. private function step_for($type) {
  166. $row = $this->current_row();
  167. if (!isset($row[$type])) return array('e', $this->stack->q);
  168. return explode(' ', $row[$type]);
  169. }
  170. private function has_step_for($type) {
  171. $row = $this->current_row();
  172. return isset($row[$type]);
  173. }
  174. private function state() { return $this->stack->q; }
  175. function eat($type, $semantic) {
  176. # assert('$type == trim($type)');
  177. # if ($this->debug) echo "Trying to eat a ($type)\n";
  178. list($opcode, $operand) = $this->step_for($type);
  179. switch ($opcode) {
  180. case 's':
  181. # if ($this->debug) echo "shift $type to state $operand\n";
  182. $this->stack->shift($operand, $semantic);
  183. # echo $this->stack->text()." shift $type<br/>\n";
  184. break;
  185. case 'r':
  186. $this->reduce($operand);
  187. $this->eat($type, $semantic);
  188. # Yes, this is tail-recursive. It's also the simplest way.
  189. break;
  190. case 'a':
  191. if ($this->stack->occupied()) throw new parse_bug('Accept should happen with empty stack.');
  192. $this->accept = true;
  193. #if ($this->debug) echo ("Accept\n\n");
  194. $this->semantic = $semantic;
  195. break;
  196. case 'e':
  197. # This is thought to be the uncommon, exceptional path, so
  198. # it's OK that this algorithm will cause the stack to
  199. # flutter while the parse engine waits for an edible token.
  200. # if ($this->debug) echo "($type) causes a problem.\n";
  201. if ($this->enter_error_tolerant_state()) {
  202. $this->eat('error', NULL);
  203. if ($this->has_step_for($type)) $this->eat($type, $semantic);
  204. } else {
  205. # If that didn't work, give up:
  206. throw new parse_error("Parse Error: ($type)($semantic) not expected");
  207. }
  208. break;
  209. default:
  210. throw new parse_bug("Bad parse table instruction ".htmlspecialchars($opcode));
  211. }
  212. }
  213. private function reduce($rule_id) {
  214. $rule = $this->rule[$rule_id];
  215. $len = $rule['len'];
  216. $semantic = $this->perform_action($rule_id, $this->stack->top_n($len));
  217. #echo $semantic.br();
  218. if ($rule['replace']) $this->stack->pop_n($len);
  219. else $this->stack->index($len);
  220. $this->eat($rule['symbol'], $semantic);
  221. }
  222. private function perform_action($rule_id, $slice) {
  223. # we have this weird calling convention....
  224. $result = null;
  225. $method = $this->parser->method[$rule_id];
  226. #if ($this->debug) echo "rule $id: $method\n";
  227. $this->parser->$method($slice, $result);
  228. return $result;
  229. }
  230. }