示例#1
0
        private void button1_Click(object sender, System.EventArgs e)
        {
            if (!TextArea.Text.Equals(string.Empty))
            {
                Consola.Text = "";
                Gramatica    grammar  = new Gramatica();
                LanguageData lenguaje = new LanguageData(grammar);
                Parser       parser   = new Parser(lenguaje);
                ParseTree    arbol    = parser.Parse(TextArea.Text);

                if (arbol.ParserMessages.Count != 0)
                {
                    MessageBox.Show("Se han encontrado errores", "Errores",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Error);

                    List <LogMessage> errores = arbol.ParserMessages;
                    foreach (LogMessage error in errores)
                    {
                        if (error.Message.Contains("Sintax"))
                        {
                            Consola.AppendText("Error Sintactico, " + error.Message + " Linea: " + error.Location.Line + ", Columna: " + error.Location.Column);
                        }
                        else
                        {
                            Consola.AppendText("Error Lexico, " + error.Message + " Linea: " + error.Location.Line + ", Columna: " + error.Location.Column);
                        }
                    }
                }
                else
                {
                    GeneradorAST generadorAST = new GeneradorAST(arbol);
                    AST          ast          = generadorAST.arbol;
                    Entorno      ent          = new Entorno(null);

                    if (ast != null)
                    {
                        foreach (Instruccion ins in ast.Instrucciones)
                        {
                            ins.ejecutar(ent, ast);
                        }

                        if (ast.existeFuncion("main"))
                        {
                            Funcion main = ast.getFuncion("main");
                            foreach (Instruccion ins in main.instrucciones)
                            {
                                ins.ejecutar(ent, ast);
                            }
                        }
                        else
                        {
                            MessageBox.Show("No se encontró la funcion main!!", "Errores",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Error);
                        }

                        Graficador j = new Graficador();
                        j.graficar(arbol.Root);
                    }
                    else
                    {
                        MessageBox.Show("Error generando el AST", "Errores",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Error);
                    }
                }
            }
        }
示例#2
0
        private void compilarToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (tabsEntradas.TabCount > 0)
            {
                String entrada = obtenerEntrada().Replace("”", "\"").Replace("“", "\"").Replace("\r", "").Replace("\f", "").Trim();
                if (entrada.Length > 0)
                {
                    Importar.Reset();
                    Gramatica     gramatica = new Gramatica();
                    LanguageData  lenguaje  = new LanguageData(gramatica);
                    Parser        parser    = new Parser(lenguaje);
                    ParseTree     arbol     = parser.Parse(entrada);
                    ParseTreeNode AST       = arbol.Root;

                    List <Instruccion> myAST = new List <Instruccion>();
                    if (AST != null)
                    {
                        myAST = new GeneradorAST().Analizar(AST);
                    }
                    bool debug = true;
                    if (!debug)
                    {
                        if (AST != null)
                        {
                            Graficador g = new Graficador();
                            string     s = g.GenerarGrafo(AST);

                            StreamWriter archivo = new StreamWriter("debug.dot", false);
                            archivo.Write(s);
                            archivo.Close();

                            Process p = new Process();
                            p.StartInfo.FileName    = @"C:\Program Files (x86)\Graphviz2.38\bin\dot.exe";
                            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            p.StartInfo.Arguments   = "-Tpng debug.dot -o debug.png";
                            p.EnableRaisingEvents   = true;
                            p.Exited += (sender1, e1) =>
                            {
                                Thread.Sleep(100);
                                Process.Start("debug.png");
                            };
                            p.Start();
                        }
                    }

                    Stuff stuff = new Stuff(textBoxConsola);
                    foreach (Irony.LogMessage error in parser.Context.CurrentParseTree.ParserMessages)
                    {
                        stuff.erroresLexicosSintacticos.Add(new Irony.LogMessage(error.Level, error.Location, ((((MyTab)tabsEntradas.SelectedTab).file != null) ? Path.GetFileName(((MyTab)tabsEntradas.SelectedTab).file) + ": " : "No File: ") + error.Message, error.ParserState));
                    }
                    ejecutar(myAST, stuff);
                }
                else
                {
                    MessageBox.Show("Entrada vacía", "Advertencia");
                }
            }
            else
            {
                MessageBox.Show("No hay ni una tab para compilar", "Advertencia");
            }
        }
示例#3
0
        public object ejecutar(Contexto ctx, Stuff stuff)
        {
            object resOp = Operacion.Validar(op.ejecutar(ctx, stuff), ctx, stuff, fila, columna);

            if (resOp == null)
            {
                return(null);
            }
            if (!(resOp is string))
            {
                stuff.error("Semántico", "'IMPORTAR', el parámetro 1 es del tipo incorrecto. Encontrado: " + Operacion.getTipo(resOp) + ", Esperado: 'CADENA'.", fila, columna, ctx);
                return(null);
            }
            foreach (Contexto instancia in instanciasArchivos)
            {
                string filee;
                if (ctx.currentFile == null)
                {
                    filee = Path.GetFullPath(Path.Combine(resOp.ToString()));
                }
                else
                {
                    filee = Path.GetFullPath(Path.Combine(ctx.currentFile, @"..\", resOp.ToString()));
                }
                if (instancia.currentFile.Equals(filee))
                {
                    if (ctx != instancia)
                    {
                        ctx.otrosArchivos.Add(instancia);
                    }
                    return(null);
                }
            }
            string file = "";

            try
            {
                StringBuilder sb = new StringBuilder();
                if (ctx.currentFile == null)
                {
                    file = Path.GetFullPath(Path.Combine(resOp.ToString()));
                }
                else
                {
                    file = Path.GetFullPath(Path.Combine(ctx.currentFile, @"..\", resOp.ToString()));
                }
                foreach (string line in File.ReadLines(file))
                {
                    sb.AppendLine(line);
                }

                String entrada = sb.Replace("”", "\"").Replace("“", "\"").Replace("\r", "").Replace("\f", "").ToString();
                if (entrada.Length > 0)
                {
                    Gramatica     gramatica = new Gramatica();
                    LanguageData  lenguaje  = new LanguageData(gramatica);
                    Parser        parser    = new Parser(lenguaje);
                    ParseTree     arbol     = parser.Parse(entrada);
                    ParseTreeNode AST       = arbol.Root;

                    List <Instruccion> myAST = new List <Instruccion>();
                    if (AST != null)
                    {
                        myAST = new GeneradorAST().Analizar(AST);
                    }
                    foreach (Irony.LogMessage error in parser.Context.CurrentParseTree.ParserMessages)
                    {
                        stuff.erroresLexicosSintacticos.Add(new Irony.LogMessage(error.Level, error.Location, ((file != null) ? Path.GetFileName(file) + ": " : "No File: ") + error.Message, error.ParserState));
                    }

                    if (stuff.erroresLexicosSintacticos.Count == 0)
                    {
                        Contexto otroGlobal = new Contexto();
                        otroGlobal.currentFile = file;
                        foreach (Instruccion i in myAST)
                        {
                            if (i is Importar)
                            {
                                i.ejecutar(otroGlobal, stuff);
                            }
                        }
                        foreach (Instruccion i in myAST)
                        {
                            if (i is DeclaracionMetodo || i is DeclaracionClase)
                            {
                                i.ejecutar(otroGlobal, stuff);
                            }
                        }
                        foreach (Instruccion i in myAST)
                        {
                            if (i is DeclaracionMetodo || i is DeclaracionClase || i is Main || i is Importar)
                            {
                            }
                            else
                            {
                                i.ejecutar(otroGlobal, stuff);
                            }
                        }
                        foreach (Instruccion i in myAST)
                        {
                            if (i is Main)
                            {
                                stuff.error("Semántico", "'MAIN' está declarado en otro archivo que no es el principal.", i.getLinea(), i.getColumna(), otroGlobal);
                            }
                        }
                        foreach (Clase c in otroGlobal.clases)
                        {
                            ctx.clases.Add(c);
                        }
                        ctx.otrosArchivos.Add(otroGlobal);
                        instanciasArchivos.Add(otroGlobal);
                        return(null);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                stuff.error("Semántico", "'IMPORTAR', el archivo '" + file + "' no existe o no se puede leer.", fila, columna, ctx);
            }
            catch (IOException e)
            {
                stuff.error("Semántico", e.Message, fila, columna, ctx);
            }
            return(null);
        }
示例#4
0
        public static void generarC3D(ParseTree arbol, Errores errores)
        {
            GeneradorAST migenerador = new GeneradorAST(arbol);
            AST          ast         = migenerador.miarbol;
            Entorno      ent         = new Entorno(null, "GLOBAL", "GLOBAL");

            if (ast != null)
            {
                //Primera pasada: solo funciones y structs
                foreach (Instruccion element in ast.instrucciones)
                {
                    if (element is FunctionSt || element is StructSt)
                    {
                        element.compilar(ent, errores);
                    }
                }

                //Segunda pasada: Solo declaraciones
                foreach (Instruccion element in ast.instrucciones)
                {
                    if (element is Declaracion || element is DeclaConstante)
                    {
                        element.compilar(ent, errores);
                    }
                }
                string declaraciones = Generator.getInstance().getCode() + "\n"; //obtengo las declaraciones antes para guardarlos en los entornos antes de todo

                //Tercera pasada: Solo funciones (genera codigo);
                foreach (Instruccion element in ast.instrucciones)
                {
                    if (element is FunctionSt)
                    {
                        element.compilar(ent, errores);
                    }
                }
                string funciones = Generator.getInstance().getCode(); //obtengo las funciones no nativas

                //Cuarta pasada: Las instrucciones que van dentro del main
                foreach (Instruccion element in ast.instrucciones)
                {
                    if (!(element is FunctionSt || element is StructSt || element is Declaracion || element is DeclaConstante))
                    {
                        element.compilar(ent, errores);
                    }
                }
                //GENERAMOS C3D
                string codigo = Generator.getInstance().getEncabezado();
                codigo            += Generator.getInstance().getFuncionesNativas();
                codigo            += funciones;
                codigo            += Generator.getInstance().getOpenMain();
                codigo            += declaraciones;
                codigo            += Generator.getInstance().getCode();
                codigo            += Generator.getInstance().getCloseMain();
                Form1.consola.Text = codigo;
                Generator.getInstance().clearCode();
                TableSymbol tabla = new TableSymbol();
                tabla.generarTablaSimbolos(ent);
            }
            else
            {
                MessageBox.Show("Error generando mi AST", "Errores", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }