Esempio n. 1
0
 public Class1()
 {
     this.dato   = "";
     this.estado = 0;
     this.next1  = null;
     this.next2  = null;
 }
Esempio n. 2
0
 //Inicializo lo estrictamente necesario. Creo el buffer a partir del archivo y el AFD a partir de otro archivo
 public AnalizadorLexicografico()
 {
     try
     {
         afd = new AFD();
     }
     catch (Exception ex)
     {
         Utils.Log.AddError(ex.Message);
         throw new Exception("Error al crear el analizador lexicografico" + "\r\n" + ex.Message);
     }
 }
Esempio n. 3
0
 private void button2_Click(object sender, EventArgs e)
 {
     expresion--;
     if (images.Count() > expresion && expresion > -1)
     {
         pictureBox1.Image = Picture.ElementAt(expresion);
         pictureBox2.Image = AFD.ElementAt(expresion);
     }
     else
     {
         expresion         = images.Count() - 1;
         pictureBox1.Image = Picture.ElementAt(expresion);
         pictureBox2.Image = AFD.ElementAt(expresion);
     }
 }
Esempio n. 4
0
 protected void OnBtnCreateTreeClicked(object sender, EventArgs e)
 {
     try
     {
         var arbol = AFD.GeneraArbol(this.rTxtBPInversa.Text);
     }
     catch (Exception)
     {
         MessageDialog md = new MessageDialog(null,
                                              DialogFlags.Modal,
                                              MessageType.Error,
                                              ButtonsType.Ok,
                                              "Ha ocurrido un error al generar el arbol");
         md.Run();
         md.Destroy();
     }
 }
Esempio n. 5
0
        private void txtExpresion_Validating(object sender, CancelEventArgs e)
        {
            string[] symbols = txtSymbolsIN.Text.Split(';');
            string   Value   = txtExpresion.Text.Replace(";", "").Trim();

            foreach (var item in symbolsIn)
            {
                Value = Value.Replace(item.Symbol, "").Trim();
            }
            if (!string.IsNullOrEmpty(Value))
            {
                MessageBox.Show("Debe digitar una expresión con los simbolos de entrada", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }



            char[]   Valores  = txtExpresion.Text.Replace(";", "").Trim().ToCharArray();
            itemGrid itemGrid = new itemGrid();
            string   TipoVal  = string.Empty;

            for (int y = 0; y < Valores.Length; y++)
            {
                if (y == 0)
                {
                    TipoVal = VerificacionRecursiva(txtStatesBegin.Text.Replace(";", ""), Valores[y].ToString());
                }
                else
                {
                    TipoVal = VerificacionRecursiva(TipoVal, Valores[y].ToString());
                }
            }
            itemGrid = AFD.Where(afd => afd.State == TipoVal).FirstOrDefault();

            if (itemGrid.Result == 1)
            {
                MessageBox.Show("ACEPTA");
            }
            else
            {
                MessageBox.Show("RECHAZA");
            }
        }
Esempio n. 6
0
        private string VerificacionRecursiva(string State, string Value)
        {
            string   val      = string.Empty;
            itemGrid itemGrid = AFD.Where(inicio => inicio.State == State).FirstOrDefault();
            string   TipoVal  = string.Empty;

            TipoVal = symbolsIn.Where(s => s.Symbol == Value.ToString()).FirstOrDefault().Value;
            switch (TipoVal)
            {
            case "Value1":
                val = itemGrid.Value1;
                break;

            case "Value2":
                val = itemGrid.Value2;
                break;

            default:
                break;
            }
            return(val);
        }
Esempio n. 7
0
 public void setNext2(AFD next2)
 {
     this.next2 = next2;
 }
Esempio n. 8
0
 public void setNext1(AFD next1)
 {
     this.next1 = next1;
 }
Esempio n. 9
0
        //algiriitmo del analizador
        public void AnalizadorSLR()
        {
            Tokens tk = new Tokens();

            list_reglas_reconocidas = new List <reglas_de_produccion>();
            bool   band = true;
            string simbolo;
            int    estado    = 0;
            int    newestado = 0;
            int    cont      = 0;

            //tomar el token
            tk      = list_tokens_reconocido[cont];
            simbolo = tk.Sinonimo;

            //Guarda el movimiento quese hizo en pila
            pila_sintactica.Push(estado);
            guardarMovimientoPila();

            //bucle del reconosedor hasta cuando reconosca Apectar o Error
            while (band)
            {
                // Movernos en la matriz sintactica con el simbolo
                // para buscar el nuevo estado
                newestado = devolverNuevoEstado(estado, simbolo);

                Console.WriteLine(estado + " leyendo: " + simbolo + " va a: " + newestado);
                // Verificar si encontro el nuevo estado
                if (newestado != 997)
                {
                    // Si encontro nuevo estado
                    if (newestado < 0)
                    {
                        //se reconocio regla
                        newestado = -newestado;
                        reglas_de_produccion rule = devolverRegla(newestado);

                        if (rule == null)
                        {
                            //Error no encontró regla
                            continue;
                        }
                        //Guardar la regla en lista de reglas reconocidas
                        list_reglas_reconocidas.Add(rule);

                        int cuenta = rule.Der_sinonimo.Length;
                        cuenta = cuenta * 2;
                        // Agregamos a la pila sintactica
                        guardarMovimientoPila();
                        //bajar de la pila
                        for (int i = 0; i < cuenta; i++)
                        {
                            pila_sintactica.Pop();
                        }
                        //encontro la regla y tenemos que sacar la parte izquierda
                        estado = (int)pila_sintactica.Peek();
                        // Guardamos en la pila el no terminal que esta la parte izquierda de la regla
                        pila_sintactica.Push(rule.Izq_sinonimo);
                        //movernos en la SLR para ver a que estado va
                        string s = rule.Izq_sinonimo;
                        newestado = devolverNuevoEstado(estado, s);

                        if (newestado != 997)
                        {
                            pila_sintactica.Push(newestado);
                            estado = newestado;
                        }
                        else
                        {
                            // Presentar mensaje de error
                            errores miError = new errores()
                            {
                                NumError = 1,
                                MsjError = "Error sintáctico: " + s + " no se encuentra en la matriz transciones " + newestado
                            };
                            listaErroresSintactico.Add(miError);
                            band = false;
                        }
                        // Guardar movimiento de la pila
                        guardarMovimientoPila();
                    }
                    else if (newestado == 1000)
                    {
                        //Aceptar
                        //bajar de la pila
                        for (int i = 0; i < 3; i++)
                        {
                            pila_sintactica.Pop();
                        }
                        guardarMovimientoPila();
                        break;
                    }
                    else
                    {
                        // Guardar movimientos en la lista de movimientos
                        // para presentar en la tabla mov sintactica
                        AFD miMove = new AFD()
                        {
                            Estado  = estado,
                            Leyendo = Convert.ToChar(simbolo),
                            NEstado = newestado
                        };
                        list_movimientos.Add(miMove);
                        //moverse dentrodel automata
                        pila_sintactica.Push(simbolo);
                        pila_sintactica.Push(newestado);
                        estado = newestado;
                        //tomar el token
                        cont++;
                        tk      = list_tokens_reconocido[cont];
                        simbolo = tk.Sinonimo;
                    }
                }
                else
                {
                    // Guardar movimientos en la lista de movimientos
                    // para presentar en la tabla mov sintactica
                    AFD miMove = new AFD()
                    {
                        Estado  = estado,
                        Leyendo = Convert.ToChar(simbolo),
                        NEstado = newestado
                    };
                    list_movimientos.Add(miMove);
                    //Buscar y presentar posible simbolo con el que debe ir
                    string simbolosPosibles = "";
                    foreach (var item in list_SLR)
                    {
                        if (estado == item.Estado)
                        {
                            if (!Char.IsUpper(Convert.ToChar(item.Simbolos_lee)))
                            {
                                //Buscar en alfabeto
                                string lexema = buscarEnAlfabeto(item.Simbolos_lee);
                                simbolosPosibles += lexema + " ";
                            }
                        }
                    }

                    // Presentar mensaje de error
                    errores miError = new errores()
                    {
                        NumError = 1,
                        MsjError = "Error sintáctico: " + simbolo +
                                   " no se encuentra en la matriz transciones  talvex quizas omitio uno de estos simbolos: " + simbolosPosibles
                    };
                    listaErroresSintactico.Add(miError);
                    band = false;
                    //tomar el token para recuperarse del error
                    cont++;

                    tk      = list_tokens_reconocido[cont];
                    simbolo = tk.Sinonimo;
                }
            }
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            //=== Criar tabela de simbolos
            List <ts> tabela = new List <ts>();

            //Buffer
            string buffer;


            //===== Definir arquivos de entrada
            string[] codigo     = System.IO.File.ReadAllLines(@"codigo.txt");
            string[] afd        = System.IO.File.ReadAllLines(@"AutomatoFinitoEstadoErro.csv");
            string   mapeamento = System.IO.File.ReadAllText(@"mapeamentoEstados.txt");

            //=== Carregar AFD em uma matriz
            List <AFD> afdMatriz = new List <AFD>();

            foreach (String linha in afd)
            {
                AFD afdLin = new AFD();
                buffer = "";
                foreach (char c in linha)
                {
                    if (c == ';')
                    {
                        afdLin.afdCol.Add(buffer);
                        buffer = "";
                    }
                    else
                    {
                        buffer += c;
                    }
                }
                afdMatriz.Add(afdLin);
            }

            //=== Imprimir Matriz do AFD
            foreach (AFD li in afdMatriz)
            {
                foreach (string co in li.afdCol)
                {
                    Console.Write(co + " ");
                }
                Console.WriteLine("");
            }
            //Console.WriteLine("Teste ma[9][4] = " + afdMatriz[9].afdCol[4]);
            //List<int> teste = FindState("L", "6", afdMatriz);
            //Console.WriteLine("Teste ma[L][6] = " + afdMatriz[teste[0]].afdCol[teste[1]]);

            //=== Ler caracter por caracter do codigo e verificar estados no AFD
            string     estado    = afdMatriz[1].afdCol[0]; //Estado atual - inicial
            string     estadoAnt = "";                     //Estado anterior
            List <int> indices   = new List <int> {
                0, 0, 0
            };                                              //Indices da matriz AFD

            buffer = "";
            int pos = 1; //Contador de posição no arquivo, no caso é a linha do codigo onde esta
            ts  tsItem;  //Item da tabela de simbolos

            string Separadores          = "/*+-(){},";
            string SeparadoresSemEstado = " \t \n";

            foreach (String linha in codigo)
            {
                if (linha.Length > 0)
                {
                    foreach (char c in linha)
                    {
                        /*Console.WriteLine(c);
                         * if (SeparadoresSemEstado.Contains(c))    //Separadores sem estado
                         * {
                         *  if (!buffer.Equals(""))
                         *  {
                         *      tsItem = new ts();
                         *      tsItem.estado = estado;
                         *      tsItem.posicao = pos;
                         *      tsItem.rotulo = buffer;
                         *      buffer = "";
                         *      tabela.Add(tsItem);
                         *      estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                         *  }
                         * }
                         * else if (Separadores.Contains(c))  //Separadores com estado
                         * {
                         *  //Salvar o que tem antes no buffer (se tiver)
                         *  if (!buffer.Equals(""))
                         *  {
                         *      tsItem = new ts();
                         *      tsItem.estado = estadoAnt;
                         *      tsItem.posicao = pos;
                         *      tsItem.rotulo = buffer;
                         *      tabela.Add(tsItem);
                         *  }
                         *
                         *  //Agora salva o separador
                         *  tsItem = new ts();
                         *  tsItem.estado = estado;
                         *  tsItem.posicao = pos;
                         *  tsItem.rotulo = c.ToString();
                         *  buffer = "";
                         *  tabela.Add(tsItem);
                         *  estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                         * }
                         * else
                         * {
                         *  indices = FindState(estado, c.ToString(), afdMatriz);
                         *  if (indices == null) Console.WriteLine("Erro ao achar estado: (" + estado + ", " + c.ToString() + ")");
                         *  else
                         *  {
                         *      estadoAnt = estado;
                         *      estado = afdMatriz[indices[0]].afdCol[indices[1]];
                         *  }
                         *  buffer += c;
                         * }*/


                        if (Separadores.Contains(c))
                        {
                            if (buffer != "")
                            {
                                if (FindState(estado, c.ToString(), afdMatriz) != null)
                                {
                                    if (FindState(estado, c.ToString(), afdMatriz)[2] == 1) // se é um estado final
                                    {
                                        tsItem         = new ts();
                                        tsItem.estado  = estado;
                                        tsItem.posicao = pos;
                                        tsItem.rotulo  = buffer;
                                        buffer         = "";
                                        tabela.Add(tsItem);
                                        estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                                    }
                                    else
                                    {
                                        buffer += c;
                                    }
                                }
                                else
                                {
                                    {
                                        tsItem         = new ts();
                                        tsItem.estado  = "!";
                                        tsItem.posicao = pos;
                                        tsItem.rotulo  = buffer;
                                        buffer         = "";
                                        tabela.Add(tsItem);
                                        estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                                    }
                                }
                            }
                            buffer += c;
                            indices = FindState(estado, c.ToString(), afdMatriz);
                            estado  = afdMatriz[indices[0]].afdCol[indices[1]];
                        }
                        else
                        {
                            if (SeparadoresSemEstado.Contains(c))
                            {
                                if (buffer != "")
                                {
                                    tsItem         = new ts();
                                    tsItem.estado  = estado;
                                    tsItem.posicao = pos;
                                    tsItem.rotulo  = buffer;
                                    buffer         = "";
                                    tabela.Add(tsItem);
                                    estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                                }
                            }
                            else
                            {
                                if (FindState(estado, c.ToString(), afdMatriz) != null)
                                {
                                    if (FindState(estado, c.ToString(), afdMatriz)[2] == 1 && (afdMatriz[FindState(estado, c.ToString(), afdMatriz)[0]].afdCol[FindState(estado, c.ToString(), afdMatriz)[1]] == "!"))
                                    {
                                        {
                                            tsItem         = new ts();
                                            tsItem.estado  = estado;
                                            tsItem.posicao = pos;
                                            tsItem.rotulo  = buffer;
                                            buffer         = "";
                                            tabela.Add(tsItem);
                                            estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                                        }
                                    }
                                }
                                else
                                {
                                    tsItem         = new ts();
                                    tsItem.estado  = "!";
                                    tsItem.posicao = pos;
                                    tsItem.rotulo  = buffer;
                                    buffer         = "";
                                    tabela.Add(tsItem);
                                    estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                                }

                                indices = FindState(estado, c.ToString(), afdMatriz);
                                estado  = afdMatriz[indices[0]].afdCol[indices[1]];

                                buffer += c;
                            }
                        }
                    }


                    if (buffer != "")
                    {
                        //Fim de linha também é separador
                        tsItem         = new ts();
                        tsItem.estado  = estado;
                        tsItem.posicao = pos;
                        tsItem.rotulo  = buffer;
                        buffer         = "";
                        tabela.Add(tsItem);
                        estado = afdMatriz[1].afdCol[0]; //Estado atual - inicial
                    }
                }
                pos++;
            }

            tsItem         = new ts();
            tsItem.estado  = estado;
            tsItem.posicao = pos;
            tsItem.rotulo  = "EOF";
            tabela.Add(tsItem);


            //=== Imprimir tabela de simbolos
            foreach (ts item in tabela)
            {
                Console.WriteLine("Linha:" + item.posicao + " Estado:" + item.estado + " Rotulo:" + item.rotulo);
            }

            //=== Imprimir em arquivo CSV
            ImprimirCSV(tabela, "FitaDeSaida.csv");



            //====================== ANÁLISE SINTÁTICA =====================================================================================================


            //=== importa o XML do GOLD Parse
            string    xmlData  = @"GramaticaTeste.xml";
            XDocument doc      = XDocument.Load(xmlData);
            string    jsonText = JsonConvert.SerializeXNode(doc);
            dynamic   Tables   = JsonConvert.DeserializeObject <dynamic>(jsonText);

            //=== Define as estruturas
            List <Symbol>     colecaoSimbolos  = new List <Symbol>();
            List <Estado>     colecaoEstados   = new List <Estado>();
            List <Production> colecaoProducoes = new List <Production>();
            List <LALRState>  colecaoLALRState = new List <LALRState>();


            //============= Importa os Simbolos do XML

            foreach (var m_Symbol in Tables.Tables.m_Symbol)
            {
                foreach (var Symbols in m_Symbol)
                {
                    if (Symbols.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                    {
                        foreach (var Symbol in Symbols)
                        {
                            Symbol novoSimbolo = new Symbol();

                            foreach (var propriedade in Symbol)
                            {
                                if (propriedade.Name == "@Index")
                                {
                                    string teste = propriedade.Value;
                                    novoSimbolo.Index = Int32.Parse(teste);
                                }
                                if (propriedade.Name == "@Name")
                                {
                                    novoSimbolo.Name = propriedade.Value;
                                }
                            }
                            colecaoSimbolos.Add(novoSimbolo);
                        }
                    }
                }
            }

            //============== Importa os Estados do XML


            foreach (var DFAState in Tables.Tables.DFATable)
            {
                foreach (var estados in DFAState)
                {
                    if (estados.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                    {
                        foreach (var estadoAceitacao in estados)
                        {
                            Estado novoEstado = new Estado();
                            foreach (var propriedade in estadoAceitacao)
                            {
                                if (propriedade.Name == "@AcceptSymbol")
                                {
                                    string valor = propriedade.Value;
                                    novoEstado.AcceptSymbol = GetSymbol(Int32.Parse(valor), colecaoSimbolos);
                                }
                                if (propriedade.Name == "@Index")
                                {
                                    novoEstado.Index = propriedade.Value;
                                }
                            }
                            colecaoEstados.Add(novoEstado);
                        }
                    }
                }
            }

            //=============== Importa as Produções do XML

            foreach (var m_Production in Tables.Tables.m_Production)
            {
                foreach (var Productions in m_Production)
                {
                    if (Productions.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                    {
                        foreach (var Production in Productions)
                        {
                            Production novaProducao = new Production();
                            foreach (var propriedade in Production)
                            {
                                if (propriedade.Name == "@Index")
                                {
                                    string valor = propriedade.Value;
                                    novaProducao.Index = Int32.Parse(valor);
                                }
                                if (propriedade.Name == "@NonTerminalIndex")
                                {
                                    string valor = propriedade.Value;
                                    novaProducao.NonTerminalIndex = GetSymbol(Int32.Parse(valor), colecaoSimbolos);
                                }
                                if (propriedade.Name == "@SymbolCount")
                                {
                                    string valor = propriedade.Value;
                                    novaProducao.SymbolCount = Int32.Parse(valor);
                                }
                                if (propriedade.Name == "ProductionSymbol")
                                {
                                    foreach (var ProductionofProduction in propriedade)
                                    {
                                        foreach (var Producao in ProductionofProduction)
                                        {
                                            foreach (var propriedadeInterna in Producao)
                                            {
                                                ProductionSymbol producao = new ProductionSymbol();
                                                string           valor    = propriedadeInterna.Value;
                                                producao.Symbol = GetSymbol(Int32.Parse(valor), colecaoSimbolos);
                                                novaProducao.ProductionSymbol.Add(producao);
                                            }
                                        }
                                    }
                                }
                            }
                            colecaoProducoes.Add(novaProducao);
                        }
                    }
                }
            }

            //=============== Importa tabela LALR do XML

            foreach (var LALRStates in Tables.Tables.LALRTable)
            {
                foreach (var LALRStatesPropertie in LALRStates)
                {
                    if (LALRStatesPropertie.Type == Newtonsoft.Json.Linq.JTokenType.Array)
                    {
                        foreach (var LALRStateProperties in LALRStatesPropertie)
                        {
                            LALRState novoLALRState = new LALRState();
                            foreach (var LALRStatePropertie in LALRStateProperties)
                            {
                                if (LALRStatePropertie.Name == "@Index")
                                {
                                    string valor = LALRStatePropertie.Value;
                                    novoLALRState.Index = Int32.Parse(valor);
                                }
                                if (LALRStatePropertie.Name == "@ActionCount")
                                {
                                    string valor = LALRStatePropertie.Value;
                                    novoLALRState.ActionCount = Int32.Parse(valor);
                                }
                                if (LALRStatePropertie.Name == "LALRAction")
                                {
                                    if (novoLALRState.ActionCount > 1)
                                    {
                                        foreach (var LALRActions in LALRStatePropertie)
                                        {
                                            foreach (var LALRAction in LALRActions)
                                            {
                                                LALRAction novoLALRAction = new LALRAction();
                                                foreach (var LALRActionPropertie in LALRAction)
                                                {
                                                    if (LALRActionPropertie.Name == "@SymbolIndex")
                                                    {
                                                        string valor = LALRActionPropertie.Value;
                                                        novoLALRAction.SymbolIndex = GetSymbol(Int32.Parse(valor), colecaoSimbolos);
                                                    }
                                                    if (LALRActionPropertie.Name == "@Action")
                                                    {
                                                        string valor = LALRActionPropertie.Value;
                                                        novoLALRAction.Action = Int32.Parse(valor);
                                                    }
                                                    if (LALRActionPropertie.Name == "@Value")
                                                    {
                                                        string valor = LALRActionPropertie.Value;
                                                        novoLALRAction.Value = Int32.Parse(valor);
                                                    }
                                                }
                                                novoLALRState.LALRAction.Add(novoLALRAction);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        foreach (var LALRActionProperties in LALRStatePropertie)
                                        {
                                            LALRAction novoLALRAction = new LALRAction();
                                            foreach (var LALRActionPropertie in LALRActionProperties)
                                            {
                                                if (LALRActionPropertie.Name == "@SymbolIndex")
                                                {
                                                    string valor = LALRActionPropertie.Value;
                                                    novoLALRAction.SymbolIndex = GetSymbol(Int32.Parse(valor), colecaoSimbolos);
                                                }
                                                if (LALRActionPropertie.Name == "@Action")
                                                {
                                                    string valor = LALRActionPropertie.Value;
                                                    novoLALRAction.Action = Int32.Parse(valor);
                                                }
                                                if (LALRActionPropertie.Name == "@Value")
                                                {
                                                    string valor = LALRActionPropertie.Value;
                                                    novoLALRAction.Value = Int32.Parse(valor);
                                                }
                                            }
                                            novoLALRState.LALRAction.Add(novoLALRAction);
                                        }
                                    }
                                }
                            }
                            colecaoLALRState.Add(novoLALRState);
                        }
                    }
                }
            }


            //========== Faz o mapeamento dos estados com a fita de saida
            Mapeamento mapeamentoEstados = JsonConvert.DeserializeObject <Mapeamento>(mapeamento);

            foreach (var ts in tabela)
            {
                foreach (var Simbolo in colecaoSimbolos)
                {
                    if (Simbolo.Name == ts.rotulo)
                    {
                        ts.simbolo = Simbolo;
                        break;
                    }
                }
                var temMapeamento = 0;

                if (ts.simbolo == null)
                {
                    foreach (var map in mapeamentoEstados.Data)
                    {
                        if (ts.estado.Substring(0, 1) == map.Estado)
                        {
                            foreach (var Simbolo in colecaoSimbolos)
                            {
                                if (Simbolo.Name == map.Aceita)
                                {
                                    ts.simbolo = Simbolo;
                                    break;
                                }
                            }

                            temMapeamento = 1;
                        }
                    }
                }



                foreach (var Estado in colecaoEstados)
                {
                    if (Estado.AcceptSymbol == ts.simbolo)
                    {
                        ts.estadoGLC = Estado;
                        break;
                    }
                }
            }



            Pilha pilha = new Pilha()
            {
            };

            pilha.item.Add("0");

            var aceita  = 0;
            int posicao = 0;
            int erro    = 1;

            while (aceita == 0)
            {
                erro = 1;
                foreach (var LALRState in colecaoLALRState)
                {
                    if (LALRState.Index == Int32.Parse(pilha.item[pilha.item.Count - 1]))
                    {
                        foreach (var LALRAction in LALRState.LALRAction)
                        {
                            if (LALRAction.SymbolIndex.Index == tabela[posicao].simbolo.Index)
                            {
                                erro = 0;
                                switch (LALRAction.Action)
                                {
                                case 1:     // Salto
                                    pilha.item.Add(tabela[posicao].rotulo);
                                    pilha.item.Add(LALRAction.Value.ToString());
                                    posicao++;
                                    Console.WriteLine(pilha.ToString());
                                    break;

                                case 2:     // Reducao
                                    // busca o tamanho da producao


                                    var ProducaoDaReducao  = LALRAction.Value;
                                    var SimboloNaoTerminal = colecaoProducoes[ProducaoDaReducao].NonTerminalIndex;

                                    var tamanho = colecaoProducoes[ProducaoDaReducao].SymbolCount * 2;

                                    pilha.item.RemoveRange(pilha.item.Count - tamanho, tamanho);

                                    foreach (var LALRStateAux in colecaoLALRState)
                                    {
                                        if (LALRStateAux.Index == Int32.Parse(pilha.item[pilha.item.Count - 1]))
                                        {
                                            foreach (var LALRActionAux in LALRStateAux.LALRAction)
                                            {
                                                if (LALRActionAux.SymbolIndex == SimboloNaoTerminal)
                                                {
                                                    pilha.item.Add(SimboloNaoTerminal.Name);
                                                    pilha.item.Add(LALRActionAux.Value.ToString());
                                                    break;
                                                }
                                            }
                                            break;
                                        }
                                    }
                                    Console.WriteLine(pilha.ToString());
                                    break;

                                case 3:     // Empilhamento
                                    pilha.item.Add(tabela[posicao].simbolo.Name);
                                    pilha.item.Add(LALRAction.Value.ToString());
                                    posicao++;
                                    Console.WriteLine(pilha.ToString());
                                    break;

                                case 4:
                                    /*                                       ProducaoDaReducao = LALRAction.Value;
                                     *                                     SimboloNaoTerminal = colecaoProducoes[ProducaoDaReducao].NonTerminalIndex;
                                     */
                                    aceita = 1;

                                    /*                                       tamanho = 2;
                                     *
                                     *                                     pilha.item.RemoveRange(pilha.item.Count - tamanho, tamanho);
                                     *                                     posicao++;
                                     *                                     Console.WriteLine(pilha.ToString());*/
                                    break;
                                }
                                break;
                            }
                        }
                        break;
                    }
                }
                if (erro == 1)
                {
                    Console.WriteLine("O Analisador sintático encontrou um erro na linha: " + tabela[posicao].posicao);
                    break;
                }
            }

            if (erro == 0)
            {
                Console.WriteLine("Análise Léxica concluída com sucesso!");
            }


            //===================== ANALISADOR SEMÂNTICO ==============================
        }
        public void Insert(String name, ArrayList ar, String path)
        {
            ArrayList vuelta = new ArrayList(); // array que va a almacenar los elementos en orden inverso

            for (int i = ar.Count - 1; i >= 0; i--)
            {
                vuelta.Add(ar[i]);
                NodeController.getInstancia().InsertStack(ar[i].ToString());
            }
            String ast = "";

            foreach (var item in vuelta)
            {
                ast = ast + " " + item;
            }

            Console.WriteLine(ast);

            RegularExpression re = new RegularExpression(name, vuelta);

            arrayListER.Add(re);
            NodeController.getInstancia().Print(name, path);



            //Convierte la expresion regular de prefija a pos
            ArrayList regularExpresion = NodeController.getInstancia().ConvertExpression(NodeController.getInstancia().getRoot());
            ArrayList regex            = new ArrayList();


            try
            {
                regex = RegexController.Instance.infixToPostfix(regularExpresion);
            }
            catch (Exception a)
            {
                Console.WriteLine("Expresión mal ingresada");
            }

            string st = "";

            foreach (var item in regularExpresion)
            {
                st = st + item;
            }

            Console.WriteLine(name + "->" + st);

            //CONSTRUYE EL AUTOMATA ANF
            AFN aFN = new AFN();

            aFN.construirAutomata(regex);
            Automata.Automata afn_result = aFN.Afn;
            ThompsonControlador.Instance.generarDOT("AFN", name, afn_result);
            InsertAutomataAFNName("AFN " + name);
            //CONSTRUYE EL AUTOMATA AFD
            AFD AFD = new AFD();

            AFD.conversionAFN(afn_result);
            Automata.Automata afd_result = AFD.Afd;

            //CONSTRUYE EL AUTOMATA SIN ESTADO STRAMPA
            Automata.Automata afd_trampa = AFD.RemoveCheatStates(afd_result);
            ThompsonControlador.Instance.generarDOT("AFD", name, afd_trampa);
            InsertAutomataAFDName("AFD " + name);



            //CONSTRUYE LA TABLA
            ThompsonControlador.Instance.TableConstructor(name, path, afd_trampa);
            InsertTablaName(name + "Table");
            //ENVIA EL AUTOMATA A SER GUARDADO PARA POSTERIOR EVALUACION
            EvaluatorController.Instance.Insert(name, afd_trampa);


            NodeController.getInstancia().clearList();
        }
Esempio n. 12
0
        public void Syntactic_Analysis()
        {
            //Save the data the section SETS if exist
            if (L_Sets != null)
            {
                foreach (var item in L_Sets)
                {
                    N_Sets.Add(Name_SETS(item));
                }
            }

            //Create ER for syntactic analysis
            //instance class for functions the ER
            ER     FER         = new ER();
            string ER_analysis = "";              //Save here ER for syntactic analysis

            ER_analysis = FER.CreateER(L_Tokens); //SAVE ER version 1
            string flag_SETS = FER.Is_Correct_SETS(ER_analysis, N_Sets);

            if (flag_SETS == "GG")
            {
                ER_analysis   = FER.String_Completed(ER_analysis); //completed string with symbol '.'
                textBox2.Text = ER_analysis;                       //show user

                //create tree
                ETree        T_Tokens    = new ETree();
                Stack <Nodo> Tree_Tokens = new Stack <Nodo>(); //stack the final tree
                Tree_Tokens = T_Tokens.Insert(ER_analysis);    //get tree
                // SECOND PHASE AFD the ETree
                //insert values the first , last and follow for direct method AFD
                AFD  afd        = new AFD(); //instance class
                Nodo Node_Token = new Nodo();
                Node_Token = afd.Direct_Method(Tree_Tokens.Pop());

                //Third Phase Transitions the AFD the Etree

                Columns_Transitions = afd.Transitions_Insert(Columns_Transitions, Node_Token); //save name the columns
                Values_Transitions  = afd.Transitions_values(Values_Transitions, Node_Token, Columns_Transitions, Status);
                Status             = afd.FixList(Status);                                      //order number
                Values_Transitions = afd.FixList2(Values_Transitions);
                //Method for show in DataGridView
                Show_FirstLast(Node_Token);                                        //show in data grid view data the first and last
                Show_Follow(Node_Token);                                           // show in data grid view data the follow
                Show_Transitions(Columns_Transitions, Status, Values_Transitions); //shoq in data grid view data the transitions

                //Me servira para la fase 3
                GetLastFollow(Node_Token);

                //show tree in image
                //string ruta = T_Tokens.graphic(Node_Token);

                //System.Threading.Thread.Sleep(1000);

                //FileStream file = new FileStream(ruta, FileMode.Open);
                //Image img = Image.FromStream(file);
                //pictureBox1.Image = img;
                //file.Close();
            }
            else
            {
                MessageBox.Show(flag_SETS); //END PROGRAM
            }
        }
Esempio n. 13
0
        public void Reconocedor_Lexico()
        {
            listaMovimientos      = new List <AFD>();
            lista_tks_reconocidos = new List <Tokens>();
            listError             = new List <errores>();
            listTDS = new List <TablaSimbolos>();

            int    estado = 0, newestado = 0, nidentificador = 0;
            char   simbolo;
            string lexema    = null;
            bool   flag_main = false;

            // Formateando el texto de entrada tomar en cuenta que al quitar
            // el blando dentro de lo que este en comillas se podra como #
            // Hacer un replace siempre y cuando no este entre comillas
            string entrada = texto_file_name.Replace('\n', '#').Replace('\t', '#').Replace('\r', '#').Replace(' ', '#') + "#";

            char[] palabras = entrada.ToCharArray();

            int    cuenta_simbolos = entrada.Length;
            Tokens tk = new Tokens();
            int    j  = 0;

            AFD move;

            while (j < palabras.Length)
            {
                simbolo = Convert.ToChar(palabras[j]);

                newestado = movimiento_AFD(estado, simbolo);
                if (!(simbolo.Equals('#') && (estado == 0)))
                {
                    move = new AFD()
                    {
                        Estado  = estado,
                        Leyendo = simbolo,
                        NEstado = newestado
                    };
                    if (newestado < 0)
                    {
                        move.Lee = "Token Reconocido " + (-newestado);
                    }

                    listaMovimientos.Add(move);
                }

                if (newestado == 998)
                {
                    estado = 0;
                    lexema = "";
                    j++;
                    continue;
                }

                if (newestado == 999)
                {
                    // Presentar mensaje error
                    errores miError = new errores()
                    {
                        NumError = 1,
                        MsjError = "Error léxico: simbolo " + simbolo + " no reconocido en el lexema " + lexema
                    };
                    listError.Add(miError);
                    // Volvemos a estado 0 y lexema para que vuelva areconocer otro token
                    while (true)
                    {
                        if (palabras[j] != '#')
                        {
                            j++;
                            continue;
                        }
                        break;
                    }
                    estado = 0;
                    lexema = "";
                    j++;
                    continue;
                }
                else if (newestado < 0)
                {
                    newestado = -newestado;
                    BuscarToken(newestado, lexema);
                    if (newestado == 22)
                    {
                        flag_main = true;
                    }
                    // Verificar si es un identificador
                    if (newestado == 1 && !(flag_main))
                    {
                        // Quedarnos solo con 8 carateres significativos
                        if (!(lexema.Length < 8))
                        {
                            lexema = lexema.Substring(0, 8);
                        }

                        // Se reconocio un identificador guardar en la tabla de  simbolos
                        TablaSimbolos identificador = new TablaSimbolos()
                        {
                            Numero = nidentificador++,
                            Nombre = lexema
                                     // Guardar tipo y ancho
                        };
                        //Buscar identificador: si esta error


                        listTDS.Add(identificador);
                    }
                    estado = 0;
                    lexema = "";
                }
                else
                {
                    if (!simbolo.Equals('#'))
                    {
                        lexema += simbolo;
                    }
                    estado = newestado;
                }

                j++;
            }
        }
Esempio n. 14
0
        private void Llenar(string value)
        {
            itemGrid ret        = new itemGrid();
            itemGrid comparador = AFD.Where(a => a.State == value).FirstOrDefault();

            if (comparador == null)
            {
                ret.State = value;
                if (ret.State != string.Empty)
                {
                    if (ret.State.Contains(txtAcceptations.Text.Trim()))
                    {
                        ret.Result = 1;
                    }
                }
                AFD.Add(ret);
                if (value.Contains(";"))
                {
                    string nval = string.Empty;
                    foreach (var item in value.Split(';'))
                    {
                        ret = transitions.Where(a => a.State == item).FirstOrDefault();
                        if (ret.Value1 != string.Empty)
                        {
                            nval += string.IsNullOrEmpty(nval) ? "" : ";";
                            nval += ret.Value1;
                        }
                    }
                    Llenar(nval);
                    nval = string.Empty;
                    foreach (var item in value.Split(';'))
                    {
                        ret = transitions.Where(a => a.State == item).FirstOrDefault();
                        if (ret.Value2 != string.Empty)
                        {
                            nval += string.IsNullOrEmpty(nval) ? "" : ";";
                            nval += ret.Value2;
                        }
                    }
                    Llenar(nval);
                    nval = string.Empty;
                    foreach (var item in value.Split(';'))
                    {
                        ret = transitions.Where(a => a.State == item).FirstOrDefault();
                        if (ret.Value3 != string.Empty)
                        {
                            nval += string.IsNullOrEmpty(nval) ? "" : ";";
                            nval += ret.Value3;
                        }
                    }
                    Llenar(nval);
                    nval = string.Empty;
                    foreach (var item in value.Split(';'))
                    {
                        ret = transitions.Where(a => a.State == item).FirstOrDefault();
                        if (ret.Value4 != string.Empty)
                        {
                            nval += string.IsNullOrEmpty(nval) ? "" : ";";
                            nval += ret.Value4;
                        }
                    }
                    Llenar(nval);
                }
                else
                {
                    ret = transitions.Where(a => a.State == value).FirstOrDefault();
                    if (ret != null)
                    {
                        Llenar(ret.Value1);
                        Llenar(ret.Value2);
                        Llenar(ret.Value3);
                        Llenar(ret.Value4);
                    }
                }
            }
        }