1- from typing import Iterable , Optional , TypeAlias
1+ from typing import Iterable , Optional , Protocol , TypeAlias
2+
3+ from typing_extensions import Self
24
35from syntactes import Grammar , Token
46from syntactes ._action import Action
5- from syntactes ._state import LR0State
7+ from syntactes ._state import LR0State , LR1State , State
68from syntactes .parsing_table import Conflict , Entry
79
810Row : TypeAlias = dict [Token , list [Action ]]
911
1012
13+ class ParsingTable (Protocol ):
14+ rows : dict [State , Row ]
15+
16+ @staticmethod
17+ def from_entries (entries : Iterable [Entry ], grammar : Grammar ) -> Self : ...
18+
19+
1120class LR0ParsingTable :
1221 """
1322 Table that contains all the transitions from state to state with a symbol.
@@ -19,13 +28,11 @@ def __init__(self, grammar: Grammar) -> None:
1928 self ._initial_state = None
2029
2130 @staticmethod
22- def from_entries (
23- entries : Iterable [Entry ], tokens : Iterable [Token ]
24- ) -> "LR0ParsingTable" :
31+ def from_entries (entries : Iterable [Entry ], grammar : Grammar ) -> "LR0ParsingTable" :
2532 """
2633 Create a parsing table from the given entries.
2734 """
28- table = LR0ParsingTable (tokens )
35+ table = LR0ParsingTable (grammar )
2936 {table .add_entry (entry ) for entry in entries }
3037 return table
3138
@@ -133,3 +140,46 @@ def from_entries(
133140
134141 def _header_str (self ) -> str :
135142 return "SLR PARSING TABLE"
143+
144+
145+ class LR1ParsingTable (LR0ParsingTable ):
146+ """
147+ Table that contains all the transitions from state to state with a symbol.
148+ """
149+
150+ def __init__ (self , grammar : Grammar ) -> None :
151+ self .rows : dict [LR1State , Row ] = dict ()
152+ self ._grammar = grammar
153+ self ._initial_state = None
154+
155+ @staticmethod
156+ def from_entries (
157+ entries : Iterable [Entry ], tokens : Iterable [Token ]
158+ ) -> "LR1ParsingTable" :
159+ """
160+ Create a parsing table from the given entries.
161+ """
162+ table = LR1ParsingTable (tokens )
163+ {table .add_entry (entry ) for entry in entries }
164+ return table
165+
166+ @property
167+ def initial_state (self ) -> LR1State :
168+ return self ._initial_state
169+
170+ def get_actions (self , state : LR1State , token : Token ) -> Optional [list [Action ]]:
171+ """
172+ Get the actions from state with given number with `token`.
173+ If there are no actions, returns None.
174+ """
175+ return self .rows .get (state , {}).get (token , None )
176+
177+ def get (self , state : LR1State ) -> Optional [Row ]:
178+ """
179+ Get the mapping of tokens to actions for the given state number.
180+ Returns None if the state is not found.
181+ """
182+ return self .rows .get (state , None )
183+
184+ def _header_str (self ) -> str :
185+ return "LR1 PARSING TABLE"
0 commit comments