1- from typing import Iterable , Optional , TypeAlias
1+ from typing import Iterable , Optional , Protocol , TypeAlias
22
33from syntactes import Grammar , Token
44from syntactes ._action import Action
5- from syntactes ._state import LR0State
5+ from syntactes ._state import LR0State , LR1State , State
66from syntactes .parsing_table import Conflict , Entry
77
88Row : TypeAlias = dict [Token , list [Action ]]
99
1010
11+ class ParsingTable (Protocol ):
12+ rows : dict [State , Row ]
13+ initial_state : State
14+
15+ @staticmethod
16+ def from_entries (entries : Iterable [Entry ], grammar : Grammar ) -> "ParsingTable" : ...
17+
18+ def get (self , state : State ) -> Optional [Row ]: ...
19+
20+ def get_actions (self , state : State , token : Token ) -> Optional [list [Action ]]: ...
21+
1122class LR0ParsingTable :
1223 """
1324 Table that contains all the transitions from state to state with a symbol.
@@ -19,13 +30,11 @@ def __init__(self, grammar: Grammar) -> None:
1930 self ._initial_state = None
2031
2132 @staticmethod
22- def from_entries (
23- entries : Iterable [Entry ], tokens : Iterable [Token ]
24- ) -> "LR0ParsingTable" :
33+ def from_entries (entries : Iterable [Entry ], grammar : Grammar ) -> "LR0ParsingTable" :
2534 """
2635 Create a parsing table from the given entries.
2736 """
28- table = LR0ParsingTable (tokens )
37+ table = LR0ParsingTable (grammar )
2938 {table .add_entry (entry ) for entry in entries }
3039 return table
3140
@@ -133,3 +142,46 @@ def from_entries(
133142
134143 def _header_str (self ) -> str :
135144 return "SLR PARSING TABLE"
145+
146+
147+ class LR1ParsingTable (LR0ParsingTable ):
148+ """
149+ Table that contains all the transitions from state to state with a symbol.
150+ """
151+
152+ def __init__ (self , grammar : Grammar ) -> None :
153+ self .rows : dict [LR1State , Row ] = dict ()
154+ self ._grammar = grammar
155+ self ._initial_state = None
156+
157+ @staticmethod
158+ def from_entries (
159+ entries : Iterable [Entry ], tokens : Iterable [Token ]
160+ ) -> "LR1ParsingTable" :
161+ """
162+ Create a parsing table from the given entries.
163+ """
164+ table = LR1ParsingTable (tokens )
165+ {table .add_entry (entry ) for entry in entries }
166+ return table
167+
168+ @property
169+ def initial_state (self ) -> LR1State :
170+ return self ._initial_state
171+
172+ def get_actions (self , state : LR1State , token : Token ) -> Optional [list [Action ]]:
173+ """
174+ Get the actions from state with given number with `token`.
175+ If there are no actions, returns None.
176+ """
177+ return self .rows .get (state , {}).get (token , None )
178+
179+ def get (self , state : LR1State ) -> Optional [Row ]:
180+ """
181+ Get the mapping of tokens to actions for the given state number.
182+ Returns None if the state is not found.
183+ """
184+ return self .rows .get (state , None )
185+
186+ def _header_str (self ) -> str :
187+ return "LR1 PARSING TABLE"
0 commit comments