Removed dep on API
[ninja.git] / src / op5 / ninja_sdk / parsegen / LalrItem.php
blob62d737e9380ae16f57b1e0a45f53e6cd1c8dd6fd
1 <?php
3 class LalrItem {
4 private $name;
5 private $generate;
6 private $symbols;
7 private $symbol_state;
8 private $ptr = 0;
10 public function __construct( $name, $generate, $symbols ) {
11 $this->name = $name;
12 $this->generate = $generate;
13 $this->symbols = array();
14 $this->symbol_state = array();
15 foreach( $symbols as $sym ) {
16 if( $sym[0] == '_' ) {
17 $this->symbols[] = substr($sym,1);
18 $this->symbol_state[] = false;
19 } else {
20 $this->symbols[] = $sym;
21 $this->symbol_state[] = true;
24 $this->ptr = 0;
27 public function get_name() {
28 return $this->name;
31 public function get_ptr() {
32 return $this->ptr;
34 public function generates() {
35 return $this->generate;
38 public function produces( $symbol ) {
39 return $this->generate == $symbol;
42 /**
43 * Returns the next symbol to match
45 * @return symbol name, or false
47 public function next() {
48 if( !isset( $this->symbols[$this->ptr] ) )
49 return false;
50 return $this->symbols[$this->ptr];
53 /**
54 * Returns a copy of the current rule, where a symbol is matched. If not matched, returns false
56 * @param symbol name
57 * @return lalr item, or false
59 public function take( $symbol ) {
60 if( $this->ptr == count( $this->symbols ) )
61 return false;
63 if( $this->symbols[$this->ptr] != $symbol )
64 return false;
66 $rule = new self( $this->name, $this->generate, $this->symbols );
67 $rule->ptr = $this->ptr + 1;
68 return $rule;
71 public function complete() {
72 return $this->ptr == count( $this->symbols );
75 public function count() {
76 return count( $this->symbols );
79 public function equals( $item ) {
80 return ($item->name == $this->name) && ($item->ptr == $this->ptr);
83 public function follow( $symbol ) {
84 $next = array();
85 for( $i=0; $i<count($this->symbols); $i++ ) {
86 if( $this->symbols[$i] == $symbol ) {
87 if( !isset($this->symbols[$i+1]) ) {
88 $next[] = false;
89 } else {
90 $next[] = $this->symbols[$i+1];
94 return $next;
97 public function get_symbols() {
98 return $this->symbols;
101 public function symbol_enabled( $symbol_id ) {
102 return $this->symbol_state[$symbol_id];
105 public function __toString() {
106 $outp = sprintf( "%s: %s :=", $this->name, $this->generate );
107 foreach( $this->symbols as $i=>$sym ) {
108 if( $i == $this->ptr )
109 $outp .= ' *';
110 $outp .= " $sym";
112 if( count($this->symbols) == $this->ptr )
113 $outp .= ' *';
114 return $outp;