Exemplo n.º 1
0
        //public FiniteAutomaton(System.IO.FileInfo source)
        //{
        //    loadAutomaton(source);
        //}
        //public FiniteAutomaton(System.String filename)
        //{
        //    if (!loadAutomaton(filename))
        //        throw new InvalidAutomatonFormat("The source file \"" + filename + "\" does not define a valid automaton.");
        //}

        public virtual FAState createState()
        {
            FAState st = new FAState(num);

            num++;
            states.Add(st);
            return(st);
        }
Exemplo n.º 2
0
        private void LoadEGT(BinaryReader reader)
        {
            using (EGTReader egtReader = new EGTReader(reader))
            {
                while (egtReader.GetNextRecord())
                {
                    switch (egtReader.ReadRecordType())
                    {
                    case EGTRecord.Property:
                        GrammarProperties.SetProperty(egtReader.ReadGrammarProperty());
                        break;

                    case EGTRecord.TableCounts:
                        GrammarTables = egtReader.ReadGrammarTables();
                        break;

                    case EGTRecord.InitialStates:
                        //DFA, LALR
                        ushort dfaState  = egtReader.ReadUInt16();
                        ushort lalrState = egtReader.ReadUInt16();

                        Debug.Assert(dfaState == 0, "The initial DFA State is not 0!");
                        Debug.Assert(lalrState == 0, "The initial LALR State is not 0!");
                        break;

                    case EGTRecord.Symbol:
                        Symbol sym = egtReader.ReadSymbol();
                        GrammarTables.Symbols[sym.TableIndex] = sym;
                        break;

                    case EGTRecord.Group:
                        Group group = egtReader.ReadGroup();
                        GrammarTables.Groups[group.TableIndex] = group;
                        break;

                    case EGTRecord.CharRanges:
                        CharacterSet charSet = egtReader.ReadCharacterSet();
                        GrammarTables.CharacterSets[charSet.Index] = charSet;
                        break;

                    case EGTRecord.Production:
                        Production prod = egtReader.ReadProduction();
                        GrammarTables.Productions[prod.TableIndex] = prod;
                        break;

                    case EGTRecord.DFAState:
                        FAState faState = egtReader.ReadFAState();
                        GrammarTables.FAStates[faState.TableIndex] = faState;
                        break;

                    case EGTRecord.LRState:
                        LRActionList actionList = egtReader.ReadLRActionList();
                        GrammarTables.LRActionLists[actionList.Index] = actionList;
                        break;
                    }
                }
            }
        }
Exemplo n.º 3
0
        /**
         * Simplify a finite automaton by merging simulation equivalent states
         * @param fa: a finite automaton
         * @param Sim: some simulation rel_specation over states in the spec automaton
         *
         * @return an equivalent finite automaton
         */
        private FiniteAutomaton quotient(FiniteAutomaton fa, HashSet <Pair <FAState, FAState> > rel)
        {
            FiniteAutomaton result                   = new FiniteAutomaton();
            Dictionary <FAState, FAState> map        = new Dictionary <FAState, FAState>();
            Dictionary <FAState, FAState> reducedMap = new Dictionary <FAState, FAState>();

            foreach (FAState state in fa.states)
            {
                map.Add(state, state);
                foreach (FAState state2 in fa.states)
                {
                    if (rel.Contains(new Pair <FAState, FAState>(state, state2)) &&
                        rel.Contains(new Pair <FAState, FAState>(state2, state)))
                    {
                        map.Add(state, state2);
                    }
                }
            }

            FAState init = result.createState();

            reducedMap.Add(map[fa.InitialState], init);
            result.InitialState = init;

            foreach (FAState state in fa.states)
            {
                if (!reducedMap.ContainsKey(map[state]))
                {
                    reducedMap.Add(map[state], result.createState());
                }
                if (fa.F.Contains(state))
                {
                    result.F.Add(reducedMap[map[state]]);
                }
                foreach (KeyValuePair <string, HashSet <FAState> > sym_it in state.next)
                {
                    String sym = sym_it.Key;
                    foreach (FAState to in sym_it.Value)
                    {
                        if (!reducedMap.ContainsKey(map[to]))
                        {
                            reducedMap.Add(map[to], result.createState());
                        }
                        result.addTransition(reducedMap[map[state]], reducedMap[map[to]], sym);
                    }
                }
            }
            HashSet <Pair <FAState, FAState> > newrel_spec = new HashSet <Pair <FAState, FAState> >();

            foreach (Pair <FAState, FAState> sim in rel)
            {
                newrel_spec.Add(new Pair <FAState, FAState>(reducedMap[map[sim.Left]], reducedMap[map[sim.Right]]));
            }
            rel.Clear();
            rel = new HashSet <Pair <FAState, FAState> >(newrel_spec);

            return(result);
        }
Exemplo n.º 4
0
        private FAState GetOptimalState(FAState sourceState, IEnumerable <FATransition> filterTransition, FiniteAutomata DFA)
        {
            FAState selectedState = null;
            IEnumerable <FAState> finalStateFilter = filterTransition.SelectMany(x => x.ToState.Where(y => y.IsFinalState));

            if (finalStateFilter.Count() == 1)
            {
                selectedState = finalStateFilter.First();
            }
            else
            {
                bool xLoop = filterTransition.All(x => x.FromState == sourceState &&
                                                  x.ToState.Any(y => y.StateName == sourceState.StateName) &&
                                                  x.FromState.IsFinalState);
                if (xLoop)
                {
                    string  emptySName = "Empty";
                    FAState emptySet   = new FAState(emptySName);
                    if (!DFA.States.Any(x => x.StateName == emptySet.StateName))
                    {
                        _ = DFA.AddState(emptySet);

                        foreach (char symbol in DFA.Alphabet)
                        {
                            _ = DFA.AddTransition(symbol, emptySName, emptySName);
                        }
                    }
                    selectedState = emptySet;
                    return(selectedState);
                }

                IEnumerable <FAState> selfRefStates = filterTransition.Where(x => x.ToState.Any(y => y == sourceState && x.FromState == sourceState) && !x.Direction)
                                                      .Select(x => x.FromState);
                FAState selfRefSt = selfRefStates.FirstOrDefault();
                if (selfRefSt != null)
                {
                    FAState updState = new FAState(selfRefSt.StateName, selfRefSt.IsInitialState);
                    DFA.UpdateState(updState);
                    selectedState = updState;
                    return(selectedState);
                }


                IEnumerable <FAState> selfReferenceFilter = filterTransition.SelectMany(x => x.ToState.Where(y => y != sourceState));
                if (selfReferenceFilter.Count() == 1)
                {
                    selectedState = selfReferenceFilter.First();
                }
                else
                {
                    selectedState = filterTransition.First().FromState;
                }
            }

            return(selectedState);
        }
        public void Should_ReturnsZero_When_CompareTo_Transition()
        {
            FAState state  = new FAState("State1");
            FAState state2 = new FAState("State2");

            FATransition transition1 = new FATransition('a', state, state2);
            FATransition transition2 = new FATransition('a', state, state2);

            Assert.Zero(transition1.CompareTo(transition2));
        }
        public void Should_ReturnsNegative_When_CompareTo_Transition()
        {
            FAState state  = new FAState("State1");
            FAState state2 = new FAState("State2");

            FATransition transition1 = new FATransition('a', state, state2);
            FATransition transition2 = new FATransition('b', state, state2);

            Assert.AreEqual(-1, transition1.CompareTo(transition2));
        }
Exemplo n.º 7
0
        public void Should_ReturnFalse_When_AddState_WithNullFaState()
        {
            List <char> alphabet = new List <char>()
            {
                'a'
            };
            FiniteAutomata automata = new FiniteAutomata(FiniteAutomataType.DFA, alphabet);
            FAState        state    = null;

            Assert.False(automata.AddState(state));
        }
Exemplo n.º 8
0
        public void Should_ReturnTrue_When_AddState_WithFAState()
        {
            List <char> alphabet = new List <char>()
            {
                'a'
            };
            FiniteAutomata automata = new FiniteAutomata(FiniteAutomataType.DFA, alphabet);
            FAState        state    = new FAState("State");

            Assert.True(automata.AddState(state));
        }
Exemplo n.º 9
0
        public void Should_Equal_When_InitalState_ComparedByInitialState()
        {
            List <char> alphabet = new List <char> {
                '0', '1'
            };
            FiniteAutomata automata = new FiniteAutomata(FiniteAutomataType.NFA, alphabet);

            FAState state = new FAState("A", isInitialState: true);

            automata.AddState(state);

            Assert.AreEqual(state, automata.InitialState);
        }
Exemplo n.º 10
0
        public void Should_ReturnTrue_When_AddTransition_WithFATranstion()
        {
            List <char> alphabet = new List <char>()
            {
                'a'
            };
            FiniteAutomata automata = new FiniteAutomata(FiniteAutomataType.DFA, alphabet);

            FAState      state1     = new FAState("q1", isInitialState: true, isFinalState: true);
            FATransition transition = new FATransition('a', state1, state1);

            Assert.True(automata.AddTransition(transition));
        }
Exemplo n.º 11
0
        public void Should_ReturnTrue_When_UpdateState_WithFAState()
        {
            List <char> alphabet = new List <char>()
            {
                'a'
            };
            FiniteAutomata automata = new FiniteAutomata(FiniteAutomataType.TwoWayDFA, alphabet);
            FAState        state    = new FAState("State Name", isInitialState: true, isFinalState: true);

            automata.AddState(state);
            state = new FAState("State Name", isInitialState: true, isFinalState: false);
            Assert.True(automata.UpdateState(state));
        }
Exemplo n.º 12
0
        public virtual FAState createState(System.String name)
        {
            int i = S.IndexOf(name);

            if (i < 0)
            {
                FAState st = new FAState(num);
                S.Add(name);
                states.Add(st);
                num++;
                return(st);
            }
            else
            {
                return(states[i]);
            }
        }
Exemplo n.º 13
0
        internal FAState ReadFAState()
        {
            ushort index       = ReadUInt16();
            bool   accept      = ReadBoolean();
            ushort acceptIndex = ReadUInt16();

            //Reserved; skip
            ReadEntry();

            FAState faState = accept ? new FAState(index, grammarTables.Symbols[acceptIndex]) : new FAState(index);

            while (!IsRecordComplete())
            {
                faState.Edges.Add(ReadFAEdge());
            }
            return(faState);
        }
Exemplo n.º 14
0
        public void Should_Equal_When_FinalState_ComparedByFinalState()
        {
            List <char> alphabet = new List <char> {
                '0', '1'
            };
            FiniteAutomata automata = new FiniteAutomata(FiniteAutomataType.NFA, alphabet);

            FAState state = new FAState("A", isFinalState: true);

            _ = automata.AddState(state);

            List <FAState> states = new List <FAState>()
            {
                state
            };

            Assert.AreEqual(states, automata.FinalState);
        }
Exemplo n.º 15
0
        public virtual void addTransition(FAState state, FAState state2, System.String label)
        {
            if (state.next.ContainsKey(label))
            {
                if (state.next[label].Contains(state2))
                {
                    return;
                }
            }


            trans++;
            if (!alphabet.Contains(label))
            {
                alphabet.Add(label);
            }
            state.addNext(label, state2, this);
            state2.addPre(label, state);
        }
Exemplo n.º 16
0
        public static Automata BuildAutomata(ConfigurationBase initStep)
        {
            Dictionary <string, FAState> visited = new Dictionary <string, FAState>();
            Stack <ConfigurationBase>    working = new Stack <ConfigurationBase>(1024);

            working.Push(initStep);
            Automata auto = new Automata();
            FAState  init = auto.AddState();

            auto.SetInitialState(init);
            visited.Add(initStep.GetID(), init);

            do
            {
                ConfigurationBase current      = working.Pop();
                FAState           currentState = visited[current.GetID()];

                IEnumerable <ConfigurationBase> list = current.MakeOneMove();

                //for (int i = 0; i < list.Length; i++)
                foreach (ConfigurationBase step in list)
                {
                    //ConfigurationBase step = list[i];
                    FAState target;
                    string  nextID = step.GetID();
                    if (visited.ContainsKey(nextID))
                    {
                        target = visited[nextID];
                    }
                    else
                    {
                        target = auto.AddState();
                        working.Push(step);
                        visited.Add(nextID, target);
                    }

                    auto.AddTransition(currentState, step.Event, target);
                }
            }while (working.Count > 0);

            return(auto);
        }
Exemplo n.º 17
0
        public void Should_ReturnTrue_When_AddTransition_MultipleToStatesInNFA()
        {
            List <char> alphabet = new List <char>()
            {
                'a'
            };
            FiniteAutomata automata = new FiniteAutomata(FiniteAutomataType.NFA, alphabet);

            FAState state1 = new FAState("q1", isInitialState: true, isFinalState: true);
            FAState state2 = new FAState("q2");

            List <FAState> states = new List <FAState>()
            {
                state1, state2
            };

            FATransition transition = new FATransition('a', state1, states);

            Assert.True(automata.AddTransition(transition));
        }
Exemplo n.º 18
0
        /// <summary>
        ///  Inserts initial state to DFA from NFA.
        /// </summary>
        /// <param name="NFA"></param>
        /// <param name="DFA"></param>
        /// <returns>Updated DFA object.</returns>
        private FiniteAutomata InsertInitalState(FiniteAutomata NFA, FiniteAutomata DFA)
        {
            _ = DFA.AddState(NFA.InitialState);

            // TR: Sadece initial state'in yaptığı geçişleri NFA dan getirilir.
            IEnumerable <FATransition> transitions = NFA.Transitions.Where(x => x.FromState == NFA.InitialState);

            foreach (FATransition transition in transitions)
            {
                if (transition.ToState.Count() == 1)
                {
                    // TR: Hedef state yoksa oluşturulur.
                    FAState toState = transition.ToState.First();
                    _ = DFA.AddState(toState);

                    // TR: 1-1 geçiş olduğundan DFA'ya uyumludur. Geçişi olduğu gibi eklenir.
                    _ = DFA.AddTransition(transition);
                }
                else if (transition.ToState.Count() > 1) // 1 den fazla to state varsa
                {
                    IEnumerable <FAState> toStates = transition.ToState;
                    // TR: Stateleri aralarına ayraç koyarak birleştir.
                    string newStateName = string.Join(STATE_SEPARATOR, toStates);
                    // TR: Herhangi bir state final state ise bu state final olmalıdır.
                    bool isFinalState = toStates.Any(state => state.IsFinalState);

                    // TR: Hedef state yoksa oluşturulur.
                    FAState aState = new FAState(newStateName, isFinalState: isFinalState);
                    _ = DFA.AddState(aState);

                    _ = DFA.AddTransition(transition.TransitionSymbol, transition.FromState.StateName, aState.StateName);
                }
                else // 0 olma durumu
                {
                }
            }

            return(DFA);
        }
Exemplo n.º 19
0
        private FiniteAutomata InsertLeftDirectionStates(FiniteAutomata TWDFA, FiniteAutomata DFA)
        {
            IEnumerable <FATransition> leftTransitions     = TWDFA.Transitions.Where(x => !x.Direction);
            Queue <FATransition>       leftTransitionQueue = new Queue <FATransition>(leftTransitions);

            do
            {
                FATransition transition = leftTransitionQueue.Dequeue();
                FAState      toState    = transition.ToState.First();
                IEnumerable <FATransition> l0Transitions = TWDFA.Transitions.Where(x => x.FromState == toState);
                FAState targetState = null;
                if (l0Transitions.Any(x => !x.Direction))
                {
                    IEnumerable <FATransition> l1Transitions = l0Transitions.Where(x => !x.Direction);
                    if (l1Transitions.Count() > 1)
                    {
                        leftTransitionQueue.Enqueue(transition);
                    }
                    else
                    {
                        FATransition l1Transition = l1Transitions.First();
                        FAState      l1State      = l1Transition.FromState;

                        targetState = GetOptimalState(l1State, l0Transitions, DFA);
                    }
                }
                else
                {
                    targetState = GetOptimalState(toState, l0Transitions, DFA);
                }

                FATransition newTransition = new FATransition(transition.TransitionSymbol, transition.FromState, targetState);
                _ = DFA.AddTransition(newTransition);
            } while (leftTransitionQueue.Count > 0);

            return(DFA);
        }
 public static bool Compare(this FAState first, FAState second)
 {
     return(first.StateName == second.StateName);
 }
Exemplo n.º 21
0
        public Terminal PeekNextTerminal()
        {
            //This function implements the DFA for th parser's lexer.
            //It generates a token which is used by the LALR state
            //machine.

            //===================================================
            //Match DFA token
            //===================================================

            short CurrentDFA = m_loaded.InitialDFAState;
            //Next byte in the input Stream
            short LastAcceptState = -1;
            //We have not yet accepted a character string
            int LastAcceptPosition = -1;

            char?Ch = Lookahead(0);

            //NO MORE DATA
            if (!Ch.HasValue)
            {
                // End of file reached, create End Token
                return(CreateTerminal(m_loaded.GetFirstSymbolOfType(SymbolType.End), 0));
            }

            for (int CurrentPosition = 0; ; ++CurrentPosition)
            {
                // This code searches all the branches of the current DFA state
                // for the next character in the input Stream. If found the
                // target state is returned.

                Ch = Lookahead(CurrentPosition);
                short?Found = null;
                //End reached, do not match
                if (Ch.HasValue)
                {
                    ushort  charCode = m_charToShort(Ch.Value);
                    FAState faState  = m_loaded.GetFAState(CurrentDFA);
                    foreach (FAEdge Edge in faState.Edges)
                    {
                        //==== Look for character in the Character Set Table
                        if (Edge.Characters.Contains(charCode))
                        {
                            Found = Edge.Target;
                            break;
                        }
                    }
                }

                // This block-if statement checks whether an edge was found from the current state. If so, the state and current
                // position advance. Otherwise it is time to exit the main loop and report the token found (if there was one).
                // If the LastAcceptState is -1, then we never found a match and the Error Token is created. Otherwise, a new
                // token is created using the Symbol in the Accept State and all the characters that comprise it.

                if (Found.HasValue)
                {
                    // This code checks whether the target state accepts a token.
                    // If so, it sets the appropiate variables so when the
                    // algorithm in done, it can return the proper token and
                    // number of characters.
                    short Target = Found.Value;

                    //NOT is very important!
                    if ((m_loaded.GetFAState(Target).Accept != null))
                    {
                        LastAcceptState    = Target;
                        LastAcceptPosition = CurrentPosition;
                    }

                    CurrentDFA = Target;

                    //No edge found
                }
                else
                {
                    // Lexer cannot recognize symbol
                    if (LastAcceptState == -1)
                    {
                        return(CreateTerminal(m_loaded.GetFirstSymbolOfType(SymbolType.Error), 1));
                    }
                    else
                    {
                        //Created Terminal contains the total number of accept characters
                        return(CreateTerminal(m_loaded.GetFAState(LastAcceptState).Accept, LastAcceptPosition + 1));
                    }
                }
            }
        }
Exemplo n.º 22
0
        private static Automata BuildAutomataWithRefusalsAndDiv(ConfigurationBase InitSpecStep)
        {
            Dictionary <string, FAState> visited = new Dictionary <string, FAState>();
            Stack <ConfigurationBase>    working = new Stack <ConfigurationBase>(1024);

            working.Push(InitSpecStep);
            Automata auto = new Automata();
            FAState  init = auto.AddState();

            auto.SetInitialState(init);
            visited.Add(InitSpecStep.GetID(), init);

            do
            {
                ConfigurationBase current      = working.Pop();
                FAState           currentState = visited[current.GetID()];

                if (current.IsDivergent())
                {
                    currentState.IsDiv = true;
                }
                else
                {
                    IEnumerable <ConfigurationBase> list = current.MakeOneMove();
                    List <string> negateRefusal          = new List <string>();
                    bool          hasTau = false;

                    //for (int i = 0; i < list.Length; i++)
                    foreach (ConfigurationBase step in list)
                    {
                        //ConfigurationBase step = list[i];

                        if (step.Event == Constants.TAU)
                        {
                            hasTau = true;
                        }
                        else
                        {
                            negateRefusal.Add(step.Event);
                        }

                        FAState target;
                        string  nextID = step.GetID();
                        if (visited.ContainsKey(nextID))
                        {
                            target = visited[nextID];
                        }
                        else
                        {
                            target = auto.AddState();
                            working.Push(step);
                            visited.Add(nextID, target);
                        }

                        auto.AddTransition(currentState, step.Event, target);
                    }

                    if (hasTau)
                    {
                        currentState.NegatedRefusal = null;
                    }
                    else
                    {
                        currentState.NegatedRefusal = negateRefusal;
                    }
                }
            }while (working.Count > 0);

            return(auto);
        }
Exemplo n.º 23
0
        internal virtual void  tarjan(FAState v)
        {
            v_index.Add(v.id, index);
            v_lowlink.Add(v.id, index);
            index++;
            S.Push(v);

            foreach (KeyValuePair <string, HashSet <FAState> > pair in v.next)
            {
                //System.String next = pair.Key;
                foreach (FAState v_prime in pair.Value)
                {
                    if (!v_index.ContainsKey(v_prime.id))
                    {
                        tarjan(v_prime);
                        v_lowlink.Add(v.id, Math.Min(v_lowlink[v.id], v_lowlink[v_prime.id]));
                    }
                    else if (S.Contains(v_prime))
                    {
                        v_lowlink.Add(v.id, Math.Min(v_lowlink[v.id], v_index[v_prime.id]));
                    }
                }
            }

            if (v_lowlink[v.id] == v_index[v.id])
            {
                HashSet <FAState> SCC = new HashSet <FAState>();
                while (S.Count > 0)
                {
                    FAState t = S.Pop();
                    SCC.Add(t);

                    if (t.id == v.id)
                    {
                        break;
                    }
                }

                foreach (FAState st in SCC)
                {
                    if (st.next.ContainsKey("1"))
                    {
                        HashSet <FAState> states = st.next["1"];

                        //states..retainAll(SCC);
                        if (states.Overlaps(SCC))
                        {
                            foreach (FAState state in SCC)
                            {
                                OneSCC.Add(state);
                            }

                            ////is 1-SCC
                            ////UPGRADE_NOTE: There is an untranslated Statement.  Please refer to original code. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1153'"
                            //while (SCC_it2.hasNext())
                            //{
                            //    OneSCC.add(SCC_it2.next());
                            //}
                            break;
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
        private bool PreStateSimulated(HashSet <Pair <FAState, FAState> > sim, FiniteAutomaton omega, FAState p, FAState q)
        {
            foreach (KeyValuePair <string, HashSet <FAState> > keyValuePair in p.pre)
            {
                String a = keyValuePair.Key;
                if (keyValuePair.Value == null)
                {
                    return(false);
                }

                foreach (FAState p_pre in keyValuePair.Value)
                {
                    bool hasSimulatingState = false;

                    foreach (FAState q_pre in q.pre[a])
                    {
                        if (sim.Contains(new Pair <FAState, FAState>(p_pre, q_pre)))
                        {
                            hasSimulatingState = true;
                            break;
                        }
                    }

                    if (!hasSimulatingState)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 25
0
        private bool NextStateSimulated(HashSet <Pair <FAState, FAState> > sim, FiniteAutomaton omega, FAState p, FAState q)
        {
            foreach (KeyValuePair <string, HashSet <FAState> > symbol_it in p.next)
            {
                String a = symbol_it.Key;
                if (symbol_it.Value == null)
                {
                    return(false);
                }

                foreach (FAState p_next in symbol_it.Value)
                {
                    bool hasSimulatingState = false;

                    foreach (FAState q_next in q.next[a])
                    {
                        if (sim.Contains(new Pair <FAState, FAState>(p_next, q_next)))
                        {
                            hasSimulatingState = true;
                            break;
                        }
                    }

                    if (!hasSimulatingState)
                    {
                        return(false);
                    }
                }
            }

            return(true);
        }
Exemplo n.º 26
0
        /**
         * Compute forward simulation relation of a Buchi automaton using Henzinger, Henzinger, Kopke FOCS 1995
         * @param omega: a Buchi automaton
         * @param FSim: maximum simulation relation
         *
         * @return simulation relation on states of the input automaton
         */
        public HashSet <Pair <FAState, FAState> > FastFSimRelNBW2(FiniteAutomaton omega, HashSet <Pair <FAState, FAState> > FSim)
        {
            Dictionary <State_Label, HashSet <FAState> > Remove = new Dictionary <State_Label, HashSet <FAState> >();

            Dictionary <String, int> symMap = new Dictionary <String, int>();

            int [,,] counter = new int[omega.states.Count, omega.states.Count, omega.alphabet.Count];
            for (int i = 0; i < omega.states.Count; i++)
            {
                for (int j = 0; j < omega.states.Count; j++)
                {
                    for (int k = 0; k < omega.alphabet.Count; k++)
                    {
                        counter[i, j, k] = 0;
                    }
                }
            }

            foreach (FAState v in omega.states)
            {
                HashSet <String> sym_it = omega.getAllTransitionSymbols();

                int sym_index = 0;
                foreach (string sym in sym_it)
                {
                    symMap.Add(sym, sym_index);
                    sym_index++;
                    HashSet <FAState> allStates = new HashSet <FAState>(omega.states);
                    Remove.Add(new State_Label(v, sym), allStates);
                }
            }

            foreach (Pair <FAState, FAState> cur in FSim)
            {
                FAState v     = cur.Left;
                FAState sim_v = cur.Right;

                foreach (KeyValuePair <string, HashSet <FAState> > symbol_it in sim_v.pre)
                {
                    String symbol = symbol_it.Key;

                    foreach (FAState from in symbol_it.Value)
                    {
                        State_Label label = new State_Label(v, symbol);
                        if (Remove.ContainsKey(label))
                        {
                            Remove[label].Remove(from);
                        }

                        counter[from.id, v.id, symMap[symbol]]++;
                    }
                }
            }

            while (Remove.Count > 0)
            {
                Dictionary <State_Label, HashSet <FAState> > .Enumerator iterator = Remove.GetEnumerator();

                State_Label       key    = iterator.Current.Key;
                HashSet <FAState> remove = iterator.Current.Value;
                Remove.Remove(key);

                FAState v      = key.State;
                String  symbol = key.Label;

                if (!v.pre.ContainsKey(symbol))
                {
                    continue;
                }

                foreach (FAState u in v.pre[symbol])
                {
                    foreach (FAState w in remove)
                    {
                        if (FSim.Contains(new Pair <FAState, FAState>(u, w)))
                        {
                            FSim.Remove(new Pair <FAState, FAState>(u, w));

                            foreach (KeyValuePair <string, HashSet <FAState> > symbol_it in w.pre)
                            {
                                String w_symbol = symbol_it.Key;
                                foreach (FAState w_pre in symbol_it.Value)
                                {
                                    counter[w_pre.id, u.id, symMap[w_symbol]]--;
                                    if (counter[w_pre.id, u.id, symMap[w_symbol]] == 0)
                                    {
                                        State_Label label = new State_Label(u, w_symbol);
                                        if (!Remove.ContainsKey(label))
                                        {
                                            HashSet <FAState> emptyStates = new HashSet <FAState>();
                                            Remove.Add(label, emptyStates);
                                        }
                                        Remove[label].Add(w_pre);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(FSim);
        }
Exemplo n.º 27
0
        internal EGT(BinaryReader Reader)
        {
            EGTReader EGT = new EGTReader(Reader);
            EGTRecord RecType = default(EGTRecord);

            try
            {
                while (!EGT.EndOfFile())
                {
                    EGT.GetNextRecord();

                    RecType = (EGTRecord)EGT.RetrieveByte();

                    switch (RecType)
                    {
                        case EGTRecord.Property:
                            {
                                //Index, Name, Value
                                int Index = 0;
                                string Name = null;

                                Index = EGT.RetrieveInt16();
                                Name = EGT.RetrieveString();
                                //Just discard
                                m_Grammar.SetValue(Index, EGT.RetrieveString());
                            }
                            break;
                        case EGTRecord.TableCounts:
                            //Symbol, CharacterSet, Rule, DFA, LALR
                            m_SymbolTable = new SymbolList(EGT.RetrieveInt16());
                            m_CharSetTable = new CharacterSetList(EGT.RetrieveInt16());
                            m_ProductionTable = new ProductionList(EGT.RetrieveInt16());
                            m_DFA = new FAStateList(EGT.RetrieveInt16());
                            m_LRStates = new LRStateList(EGT.RetrieveInt16());
                            m_GroupTable = new GroupList(EGT.RetrieveInt16());

                            break;
                        case EGTRecord.InitialStates:
                            //DFA, LALR
                            m_DFA.InitialState = EGT.RetrieveInt16();
                            m_LRStates.InitialState = EGT.RetrieveInt16();

                            break;
                        case EGTRecord.Symbol:
                            {
                                //#, Name, Kind
                                short Index = 0;
                                string Name = null;
                                SymbolType Type = default(SymbolType);

                                Index = EGT.RetrieveInt16();
                                Name = EGT.RetrieveString();
                                Type = (SymbolType)EGT.RetrieveInt16();

                                m_SymbolTable[Index] = new Symbol(Name, Type, Index);
                            }
                            break;
                        case EGTRecord.Group:
                            //#, Name, Container#, Start#, End#, Tokenized, Open Ended, Reserved, Count, (Nested Group #...)
                            {
                                Group G = new Group();

                                G.TableIndex = EGT.RetrieveInt16();
                                //#

                                G.Name = EGT.RetrieveString();
                                G.Container = m_SymbolTable[EGT.RetrieveInt16()];
                                G.Start = m_SymbolTable[EGT.RetrieveInt16()];
                                G.End = m_SymbolTable[EGT.RetrieveInt16()];

                                G.Advance = (Group.AdvanceMode)EGT.RetrieveInt16();
                                G.Ending = (Group.EndingMode)EGT.RetrieveInt16();
                                EGT.RetrieveEntry();
                                //Reserved

                                int Count = EGT.RetrieveInt16();
                                for (int n = 1; n <= Count; n++)
                                {
                                    G.Nesting.Add(EGT.RetrieveInt16());
                                }

                                //=== Link back
                                m_GroupStart.Add(G.Start, G);
                                m_GroupTable[G.TableIndex] = G;
                            }
                            break;
                        case EGTRecord.CharRanges:
                            //#, Total Sets, RESERVED, (Start#, End#  ...)
                            {
                                int Index = 0;
                                int Total = 0;

                                Index = EGT.RetrieveInt16();
                                EGT.RetrieveInt16();
                                //Codepage
                                Total = EGT.RetrieveInt16();
                                EGT.RetrieveEntry();
                                //Reserved

                                m_CharSetTable[Index] = new CharacterSet();
                                while (!(EGT.RecordComplete()))
                                {
                                    m_CharSetTable[Index].Add(new CharacterRange(EGT.RetrieveUInt16(), EGT.RetrieveUInt16()));
                                }
                            }
                            break;
                        case EGTRecord.Production:
                            //#, ID#, Reserved, (Symbol#,  ...)
                            {
                                short Index = 0;
                                int HeadIndex = 0;
                                int SymIndex = 0;

                                Index = EGT.RetrieveInt16();
                                HeadIndex = EGT.RetrieveInt16();
                                EGT.RetrieveEntry();
                                //Reserved

                                List<Symbol> symbols = new List<Symbol>();
                                while (!(EGT.RecordComplete()))
                                {
                                    SymIndex = EGT.RetrieveInt16();
                                    //m_ProductionTable[Index].Handle().Add(m_SymbolTable[SymIndex]);
                                    symbols.Add(m_SymbolTable[SymIndex]);
                                }
                                SymbolList symbolList = new SymbolList(symbols);
                                m_ProductionTable[Index] = new Production(m_SymbolTable[HeadIndex], Index, symbolList);
                            }
                            break;
                        case EGTRecord.DFAState:
                            //#, Accept?, Accept#, Reserved (CharSet#, Target#, Reserved)...
                            {
                                int Index = 0;
                                bool Accept = false;
                                int AcceptIndex = 0;
                                int SetIndex = 0;
                                short Target = 0;

                                Index = EGT.RetrieveInt16();
                                Accept = EGT.RetrieveBoolean();
                                AcceptIndex = EGT.RetrieveInt16();
                                EGT.RetrieveEntry();
                                //Reserved

                                if (Accept)
                                {
                                    m_DFA[Index] = new FAState(m_SymbolTable[AcceptIndex]);
                                }
                                else
                                {
                                    m_DFA[Index] = new FAState();
                                }

                                //(Edge chars, Target#, Reserved)...
                                while (!(EGT.RecordComplete()))
                                {
                                    SetIndex = EGT.RetrieveInt16();
                                    //Char table index
                                    Target = EGT.RetrieveInt16();
                                    //Target
                                    EGT.RetrieveEntry();
                                    //Reserved

                                    m_DFA[Index].Edges.Add(new FAEdge(m_CharSetTable[SetIndex], Target));
                                }
                            }
                            break;
                        case EGTRecord.LRState:
                            //#, Reserved (Symbol#, Action, Target#, Reserved)...
                            {
                                int Index = 0;
                                int SymIndex = 0;
                                LRActionType Action = 0;
                                short Target = 0;

                                Index = EGT.RetrieveInt16();
                                EGT.RetrieveEntry();
                                //Reserved

                                m_LRStates[Index] = new LRState();

                                //(Symbol#, Action, Target#, Reserved)...
                                while (!EGT.RecordComplete())
                                {
                                    SymIndex = EGT.RetrieveInt16();
                                    Action = (LRActionType)EGT.RetrieveInt16();
                                    Target = EGT.RetrieveInt16();
                                    EGT.RetrieveEntry();
                                    //Reserved

                                    m_LRStates[Index].Add(new LRAction(m_SymbolTable[SymIndex], Action, Target));
                                }
                            }
                            break;
                        default:
                            //RecordIDComment
                            throw new ParserException("File Error. A record of type '" + (char)RecType + "' was read. This is not a valid code.");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ParserException(ex.Message, ex, "LoadTables");
            }
        }
Exemplo n.º 28
0
 public State_Label(FAState st, System.String l)
 {
     this.st = st;
     this.l  = l;
 }
Exemplo n.º 29
0
        /// <summary>
        /// Converts NFA transitions into the DFA transition, except initial state.
        /// </summary>
        /// <param name="NFA"></param>
        /// <param name="DFA"></param>
        /// <returns>Updated DFA object.</returns>
        private FiniteAutomata Convert(FiniteAutomata NFA, FiniteAutomata DFA)
        {
            Queue <FAState> statesQueue = new Queue <FAState>();

            // TR: Initial state tarafından eklenen tüm stateleri bulup kuyruğa ekler.
            IEnumerable <FAState> states = DFA.States.Where(x => !x.IsInitialState);

            foreach (FAState state in states)
            {
                statesQueue.Enqueue(state);
            }

            // TR: Kuyruktaki tüm nesneler için çalışır.
            do
            {
                // TR: Kuyruktan sıradaki eleman getirilir.
                FAState fromState = statesQueue.Dequeue();

                // TR: DFA olduğu için tüm geçişler kullanılmalıdır.
                foreach (char symbol in DFA.Alphabet)
                {
                    string[] subStateNames = fromState.StateName.Split(STATE_SEPARATOR);

                    List <string> newStateNames = new List <string>();
                    bool          isFinalState  = false;

                    foreach (string subStateName in subStateNames)
                    {
                        FAState      subState      = NFA.States.First(x => x.StateName == subStateName);
                        FATransition subTransition = NFA.Transitions.FirstOrDefault(x => x.FromState == subState && x.TransitionSymbol == symbol);

                        IEnumerable <FAState> subToStates = subTransition.ToState;
                        newStateNames.AddNotExists(subToStates.Select(x => x.StateName));

                        // TR: Herhangi bir state final state ise bu state final olmalıdır.
                        if (!isFinalState)
                        {
                            isFinalState = subToStates.Any(state => state.IsFinalState);
                        }
                    }

                    // TR: Stateleri aralarına ayraç koyarak birleştirir.
                    string newStateName = string.Join(STATE_SEPARATOR, newStateNames.OrderBy(x => x));

                    // TR: Hedef state yoksa oluşturulur.
                    FAState targetState;
                    if (!DFA.States.Any(x => x.StateName == newStateName))
                    {
                        targetState = new FAState(newStateName, isFinalState: isFinalState);
                        _           = DFA.AddState(targetState);

                        // TR: Olmayan item kuyruğa da eklenir.
                        statesQueue.Enqueue(targetState);
                    }
                    else
                    {
                        targetState = DFA.States.First(x => x.StateName == newStateName);
                    }

                    _ = DFA.AddTransition(symbol, fromState.StateName, targetState.StateName);
                }
            } while (statesQueue.Count > 0);

            return(DFA);
        }
Exemplo n.º 30
0
        public virtual System.String getName(FAState s)
        {
            string name = S[s.ID];

            return(name == "" ? s.ToString() : name);
        }