Esempio n. 1
0
        private ParserTable Construct()
        {
            ParserTable result = new ParserTable()
            {
                Grammar   = _grammar,
                StateRows = new List <ParserTableRow>()
            };

            var graph = ConstructStateTransitionGraph();

            var orderedStates = graph.OrderBy(kvp => kvp.Value.Id);

            foreach (var stateKvp in orderedStates)
            {
                var reducableRules = stateKvp.Key.RuleOffsets.Where(r => r.IsFinal).Select(r => r.Rule.Id);

                var row = new ParserTableRow
                {
                    StateId         = stateKvp.Value.Id,
                    ShiftActionsMap = stateKvp.Value.ShiftToIds,
                    ReduceRulesIds  = new HashSet <int>(reducableRules)
                };

                result.StateRows.Add(row);
            }

            return(result);
        }
        private void FormatState(ParserTableRow row, IReadOnlyList <GrammarRuleToken> allTokens)
        {
            AppendCell(row.StateId.ToString());

            foreach (var t in allTokens.Where(t => t.IsTerminal))
            {
                if (row.ShiftActionsMap.TryGetValue(t, out int nextState))
                {
                    AppendCell("s" + nextState.ToString());
                }
                else
                {
                    AppendCell(string.Empty);
                }
            }

            AppendSeparator();
            AppendCell(string.Join(",", row.ReduceRulesIds.Select(r => "r" + r.ToString())), 10);
            AppendSeparator();

            foreach (var t in allTokens.Where(t => !t.IsTerminal))
            {
                if (row.ShiftActionsMap.TryGetValue(t, out int nextState))
                {
                    AppendCell(nextState.ToString());
                }
                else
                {
                    AppendCell(string.Empty);
                }
            }

            CompleteRow();
        }