public TransitionTable(Grammar grammar) { if (grammar == null) throw new ArgumentNullException("grammar"); _table = new Dictionary<ParserState, Dictionary<GrammarSymbol, TransitionAction>>(); _grammar = grammar; _stateMap = grammar.CreateStateMap(); ConstructTable(); }
/// <summary> /// Create a map of the transitions out of each state based upon symbol inputs. /// Refer Dragon Book pg 246 /// </summary> /// <returns></returns> public StateTransitionMap CreateStateMap() { var stateMap = new StateTransitionMap(); int currentStateNumber = 0; //The first state is the closure of the starting symbol. IList<ParserState> states = new List<ParserState> { new ParserState(currentStateNumber++, GetClosure(AugmentedState)) }; var grammarSymbols = Symbols; //iterate through the states list. // this list grows as we iterate for (int i = 0; i < states.Count; i++) { var state = states[i]; foreach (var grammarSymbol in grammarSymbols) { //get the set of items to transition to for this input var gotoForSymbol = Goto(state.Items, grammarSymbol); //if the state exists if (gotoForSymbol.Count > 0) { ParserState transitionTo; if (!StateAlreadyExists(states, gotoForSymbol, out transitionTo)) { //if there is not already a state with this set of items // then create a new state with that set of items // and add it to the states list transitionTo = new ParserState(currentStateNumber++, gotoForSymbol); states.Add(transitionTo); } //add the state transition from the current state // to the state of the goto set. // We do this here so that it is not necessary to // calculate it again at a later stage. stateMap.AddTransition(state, grammarSymbol, transitionTo); } } } return stateMap; }