Exemplo n.º 1
0
Arquivo: Peg.cs Projeto: xrisjc/misc
    static Grammer()
    {
        Number = new TerminalMatch("[0-9]");
        Plus = new TerminalChar('+');
        Minus = new TerminalChar('-');
        Mul = new TerminalChar('*');
        Div = new TerminalChar('/');
        LeftParen = new TerminalChar('(');
        RigtParen = new TerminalChar(')');

        Value = Number / (() => LeftParen + Expr + RigtParen);
        Product = Value + new ZeroOrMore((Mul / (() => Div)) + Value);
        Sum = Product + new ZeroOrMore((Plus / (() => Minus)) + Product);
        Expr = Sum;
    }
Exemplo n.º 2
0
        Expresion factor()
        {
            Expresion x = null;

            switch (token.TokenType)
            {
            case TokenType.IPAREN:
                eat(TokenType.IPAREN); x = parseExpression(); eat(TokenType.DPAREN);
                return(x);

            case TokenType.ENTERO:
                x = new Constante(token, Tipo.Int); eat(TokenType.ENTERO); return(x);

            case TokenType.FLOTANTE:
                x = new Constante(token, Tipo.Float); eat(TokenType.FLOTANTE); return(x);

            case TokenType.TRUE:
                x = Constante.True; eat(TokenType.TRUE); return(x);

            case TokenType.FALSE:
                x = Constante.False; eat(TokenType.FALSE); return(x);

            case TokenType.ID:
                Identifier id = entornoActual.Get(token);
                if (id == null)
                {
                    error(token.Lexeme + " no declarado");
                }
                eat(TokenType.ID);
                return(id);

            case TokenType.CADENA:
                Token tok = token;
                eat(TokenType.CADENA);
                return(new Expresion(tok, Tipo.String));

            default:
                error("error de sintaxis");
                return(x);
            }
        }
        public object getValor(Ambito ambito)
        {
            try
            {
                if (tipo == 1)
                {
                    int    maximo = this.expresiones.Count - 1;      /// TOMO EL VALOR MAXIMO
                    Random r      = new Random();                    /// FUNCION RANDOM
                    int    index  = r.Next(0, maximo);               /// VALOR DEL INDEX DE LA EXPRESION

                    Expresion v = this.expresiones.ElementAt(index); /// ELEMENTO

                    this.valor = v.getValor(ambito);

                    if (valor is string || valor is int || valor is double)
                    {
                        return(valor);
                    }
                    else
                    {
                        TError error = new TError("Semantico", "La Funcion Random() solo permite retornar valores: Cadena, entero o Decimal | Clase: " + clase + " | Archivo: " + ambito.archivo, linea, columna, false);
                        Estatico.errores.Add(error);
                        Estatico.ColocaError(error);
                    }
                    return(new Nulo());
                }
                else
                {
                    Random r = new Random();
                    this.valor = r.Next(0, 1);
                    return(this.valor);
                }
            }
            catch (Exception e)
            {
                TError error = new TError("Ejecucion", "Error al ejecutar la funcion: Random() | Clase: " + this.clase + " | Archivo: " + ambito.archivo + " | Mensaje: " + e.Message, linea, columna, false);
                Estatico.errores.Add(error);
                Estatico.ColocaError(error);
            }
            return(new Nulo());
        }
Exemplo n.º 4
0
 public object ejecutar(Entorno ent, AST arbol)
 {
     foreach (NodoAST nodo in Instrucciones)
     {
         if (nodo is Instruccion)
         {
             Instruccion ins    = (Instruccion)nodo;
             object      result = ins.ejecutar(ent, arbol);
             if (result != null)
             {
                 if (verificarTipo(this.Tipo, result))
                 {
                     return(result);
                 }
                 else
                 {
                     Program.getGUI().appendSalida("EL tipo del retorno no es el declarado en la funcion");
                     return(null);
                 }
             }
         }
         else if (nodo is Expresion)
         {
             Expresion expr   = (Expresion)nodo;
             object    result = expr.getValorImplicito(ent, arbol);
             if (result != null)
             {
                 if (expr.getTipo(ent, arbol) == this.Tipo)
                 {
                     return(result);
                 }
                 else
                 {
                     Program.getGUI().appendSalida("EL tipo del retorno no es el declarado en la funcion");
                     return(null);
                 }
             }
         }
     }
     return(null);
 }
Exemplo n.º 5
0
        private bool EvaluarExpresionLogica(Expresion nodo)
        {
            if (nodo is ExpresionBool n)
            {
                return(Boolean.Parse(n.TokenBool.Value.ToString()));
            }

            if (nodo is ExpresionBinaria b)
            {
                var izquierda = EvaluarExpresionLogica(b.Izquierda);
                var derecha   = EvaluarExpresionLogica(b.Derecha);

                if (b.Operador.Tipo == TipoSintaxis.TokenAnd)
                {
                    return(izquierda && derecha);
                }
                else if (b.Operador.Tipo == TipoSintaxis.TokenOr)
                {
                    return(izquierda || derecha);
                }
                else if (b.Operador.Tipo == TipoSintaxis.TokenIgualIgual)
                {
                    return(izquierda == derecha);
                }
                else if (b.Operador.Tipo == TipoSintaxis.TokenNotIgual)
                {
                    return(izquierda != derecha);
                }
                else
                {
                    throw new Exception($"Operador binario inesperado: {b.Operador.Tipo}");
                }
            }

            if (nodo is ExpresionEnParentesis p)
            {
                return(EvaluarExpresionLogica(p.Expresion));
            }

            throw new Exception($"Nodo inesperado {nodo.Tipo}");
        }
Exemplo n.º 6
0
        private static Expresion resolverExpresion(ParseTreeNode raiz, Entorno ent)
        {
            Expresion retorno = null;

            switch (raiz.Term.Name)
            {
            case "int":
            {
                retorno = new Expresion(Simbolo.EnumTipo.entero, raiz.Token.ValueString);
            }
            break;

            case "string":
            {
                retorno = new Expresion(Simbolo.EnumTipo.cadena, raiz.Token.ValueString);
            }
            break;

            case "identificador":
            {
                Simbolo sim = ent.buscar(raiz.Token.ValueString, raiz.Token.Location.Line + 1, raiz.Token.Location.Column + 1);
                if (sim != null)
                {
                    retorno = new Expresion(sim.tipo, sim.valor);
                }
                else
                {
                    Program.ventanaPrincipal.richConsola.AppendText("La variable no ha sido previamente declarada. Línea: " + (raiz.Token.Location.Line + 1) + " Columna: " + (raiz.Token.Location.Column + 1) + "\n");
                }
            }
            break;

            default:
            {
                retorno = new Expresion(Simbolo.EnumTipo.error, "Error", "No se reconoce el tipo. Línea: " + (raiz.Token.Location.Line + 1) + " Columna: " + (raiz.Token.Location.Column + 1));
            }
            break;
            }
            return(retorno);
        }
Exemplo n.º 7
0
        public override object ejecutar(Entorno ent)
        {
            ejecutado = false;
            Expresion valor = Condicion.getValor(ent);

            if (valor.tipo.tipo == Tipo.enumTipo.booleano)
            {
                bool condition = bool.Parse(valor.valor.ToString());
                if (condition)
                {
                    Entorno nuevo    = new Entorno(ent, ent.global); //
                    Object  retornar = instrucciones.ejecutar(nuevo);
                    ejecutado = true;
                    if (retornar != null)
                    {
                        if (typeof(Break).IsInstanceOfType(retornar))
                        {
                            //si viene un break se detiene el flujo del ciclo
                            return(retornar);
                        }
                        else if (typeof(Continue).IsInstanceOfType(retornar))
                        {
                            //aqui solo se debe continuar el ciclo
                            //continue;
                        }
                        else if (typeof(Primitivo).IsInstanceOfType(retornar))
                        {
                            //Aqui devolvemos el valor del retorno
                            return(retornar);
                        }
                    }
                }
            }
            else
            {
                MasterClass.Instance.addError(new C_Error("Semantico", "No se puede operar tipo de dato: " + valor.tipo.tipo + " como condicion ", linea, columna));
            }

            return(null);
        }
Exemplo n.º 8
0
        public Expresion EXPRESION_PRIMA(ParseTreeNode actual, Expresion izq, int cant_tabs)
        {
            /*
             * EXPRESION_PRIMA.Rule
             *  = PLUS + TERMINO + EXPRESION_PRIMA
             | MIN + TERMINO + EXPRESION_PRIMA
             |  ;
             */
            if (actual.ChildNodes.Count > 0)
            {
                var simb = actual.ChildNodes[0].Token.Text;

                var derecho = TERMINO(actual.ChildNodes[1], cant_tabs);
                var row     = actual.ChildNodes[0].Token.Location.Line;
                var col     = actual.ChildNodes[0].Token.Location.Column;

                var aritmetica = new Arithmetic(izq, derecho, simb, row, col, cant_tabs);

                return(EXPRESION_PRIMA(actual.ChildNodes[2], aritmetica, cant_tabs));
            }
            return(izq);
        }
Exemplo n.º 9
0
        private static void ejecutarDeclaracion(ParseTreeNode raiz, Entorno ent)
        {
            ParseTreeNode[]  hijos        = raiz.ChildNodes.ToArray();
            Simbolo.EnumTipo tipoVariable = obtenerTipo(hijos[0].ToString().Replace(" (Keyword)", ""));
            String           id           = hijos[1].Token.ValueString;

            if (hijos.Length > 2)
            {
                Expresion resultado = resolverExpresion(hijos[3], ent);
                if (tipoVariable != resultado.tipo)
                {
                    Program.ventanaPrincipal.richConsola.AppendText("El tipo que se le quiere asignar a la variable '" + id + "' no es permitido. '" + tipoVariable + "' != '" + resultado.tipo + "'. Línea: " + (hijos[3].Token.Location.Line + 1) + " Columna: " + (hijos[3].Token.Location.Column + 1) + "\n");
                    return;
                }
                Simbolo nuevo = new Simbolo(tipoVariable, resultado.valor);
                ent.insertar(id, nuevo, hijos[1].Token.Location.Line + 1, hijos[1].Token.Location.Column + 1);
            }
            else
            {
                ent.insertar(id, new Simbolo(), hijos[1].Token.Location.Line + 1, hijos[1].Token.Location.Column + 1);
            }
        }
Exemplo n.º 10
0
        public Expresion EXPLOGICA_PRIMA(ParseTreeNode actual, Expresion izq, int cant_Tabs)
        {
            /*
             * EXPLOGICA_PRIMA.Rule
             *  = AND + EXPRELACIONAL + EXPLOGICA_PRIMA
             | OR + EXPRELACIONAL + EXPLOGICA_PRIMA
             | Empty
             |  ;
             */

            if (actual.ChildNodes.Count > 0)
            {
                var simb    = actual.ChildNodes[0].Token.Text.ToLower();
                var derecho = EXPRELACIONAL(actual.ChildNodes[1], cant_Tabs);
                var row     = actual.ChildNodes[0].Token.Location.Line;
                var col     = actual.ChildNodes[0].Token.Location.Column;

                var logica = new Logical(izq, derecho, simb, row, col, cant_Tabs);
                return(EXPLOGICA_PRIMA(actual.ChildNodes[2], logica, cant_Tabs));
            }
            return(izq);
        }
        public override Resultado ejecutar(Contexto ctx, int nivel)
        {
            Resultado exec = null;

            while (true)
            {
                Resultado condicion = new Expresion(instruccion.ChildNodes[0].ChildNodes[0]).resolver(ctx);
                if (condicion.Tipo != Constantes.T_BOOL)
                {
                    ListaErrores.getInstance().setErrorSemantico(instruccion.Token.Location.Line, instruccion.Token.Location.Line, "La condicion no retorna un valor booleando", Interprete.archivo);
                    return(FabricarResultado.creaFail());
                }
                bool cond = condicion.Boleano;
                if (!cond)
                {
                    exec = FabricarResultado.creaOk();
                    break;
                }
                Cuerpo cuerpo = new Cuerpo(instruccion.ChildNodes[1], true);
                exec = cuerpo.ejecutar(ctx, nivel);

                if (exec.esContinuar())
                {
                    continue;
                }
                if (exec.esDetener())
                {
                    exec = FabricarResultado.creaOk();
                    break;
                }
                if (exec.esRetorno())
                {
                    break;
                }
                ctx.limpiarContexto(nivel);
            }
            ctx.limpiarContexto(nivel);
            return(exec);
        }
Exemplo n.º 12
0
        public override Expresion getValor(Entorno ent)
        {
            //creamos el objeto que vamos a devolver
            Expresion l = new Primitivo(new Tipo(Tipo.enumTipo.error), "@error@");

            //Creamos una variable de entorno para ir buscando en ellos
            //Iniciamos en el entorno actual
            Entorno entBuscar = ent;

            //recorremos la lista
            foreach (Id id in accesos)
            {
                //buscamos el objeto en el entorno que viene
                Expresion sim = id.getValor(entBuscar);

                //vamos preguntando si es el ultimo
                if (id == accesos.Last.Value)
                {
                    //si es el ultimo no debe ser un objeto
                    //retornamos el simbolo
                    l = new Primitivo(sim.tipo, sim.valor);
                    break;
                }
                else
                {
                    //Como no es ultimo de la lista de ids
                    //Tiene que ser de tipo objeto
                    if (sim.tipo.tipo != Tipo.enumTipo.Objecto)
                    {
                        //Si es diferente de objeto no puede ser acceso
                        /*Error*/
                    }
                    //Si es de tipo objeto nos metemos a su entorno y seguimos buscando
                    //entBuscar = ((Objecto)sim.valor).global;
                }
            }

            return(l);
        }
Exemplo n.º 13
0
        public Expresion masTexto(ParseTreeNode actual)
        {
            if (actual.ChildNodes.Count == 0)
            {
                return(null);
            }
            else
            {
                //Tiene 3 hijos (, Expresion_Cadena Mas_Texto)
                Expresion expresionCadena = this.expresionCadena(actual.ChildNodes[1]);
                Expresion masTexto        = this.masTexto(actual.ChildNodes[2]);

                if (expresionCadena != null && masTexto != null)
                {
                    return(new Aritmetica(expresionCadena, masTexto, '+'));
                }
                else
                {
                    return(expresionCadena);
                }
            }
        }
Exemplo n.º 14
0
        public Expresion TERMINO_PRIMA(ParseTreeNode actual, Expresion izq, int cant_tabs)
        {
            /*
             * TERMINO_PRIMA.Rule
             *  = POR + FACTOR + TERMINO_PRIMA
             | DIVI + FACTOR + TERMINO_PRIMA
             | MODULE + FACTOR + TERMINO_PRIMA
             | Empty
             |  ;
             */

            if (actual.ChildNodes.Count > 0)
            {
                var simb    = actual.ChildNodes[0].Token.Text;
                var derecho = FACTOR(actual.ChildNodes[1], cant_tabs);
                var row     = actual.ChildNodes[0].Token.Location.Line;
                var col     = actual.ChildNodes[0].Token.Location.Column;

                var aritmetica = new Arithmetic(izq, derecho, simb, row, col, cant_tabs);
                return(TERMINO_PRIMA(actual.ChildNodes[2], aritmetica, cant_tabs));
            }
            return(izq);
        }
Exemplo n.º 15
0
        private List <Object> linealizadaValores(List <Object> linealizada, Ambito am)
        {
            List <Object> valores = new List <object>();

            foreach (Object o in linealizada)
            {
                if (o is Expresion)
                {
                    Expresion aux  = (Expresion)o;
                    Object    val  = aux.getValor(am);
                    String    tipo = aux.getTipo(am).ToLower();
                    if (tipo != this.tipo.ToLower())
                    {
                        return(null);
                    }
                    else
                    {
                        valores.Add(val);
                    }
                }
            }
            return(valores);
        }
Exemplo n.º 16
0
        Expresion rel()
        {
            Expresion x = expr();
            Token     tok;

            switch (token.TokenType)
            {
            case TokenType.MENOR:
                tok = token; mover(); return(new Relacion(tok, x, expr()));

            case TokenType.MENORIGUAL:
                tok = token; mover(); return(new Relacion(tok, x, expr()));

            case TokenType.MAYORIGUAL:
                tok = token; mover(); return(new Relacion(tok, x, expr()));

            case TokenType.MAYOR:
                tok = token; mover(); return(new Relacion(tok, x, expr()));

            default:
                return(x);
            }
        }
Exemplo n.º 17
0
        private Comando ParsearComandoPrint()
        {
            lexer.Aceptar();
            Expresion exp   = ParsearExpresion();
            string    alias = null;

            if (lexer.tokenActual.Type == TokenType.id)
            {
                alias = lexer.tokenActual.Valor;
                lexer.Aceptar(TokenType.id);
            }
            else if (lexer.tokenActual.Type == TokenType.hilera)
            {
                alias = lexer.tokenActual.Valor;
                lexer.Aceptar(TokenType.hilera);
            }
            else
            {
                throw new LanguageException($"Se esperaba el alias para la expresion '{exp.ToString()}' del Print");
            }
            lexer.Aceptar(TokenType.puntoComa);
            return(new ComandoPrint(salida, exp, alias));
        }
Exemplo n.º 18
0
        private static void ejecutarImprimir(ParseTreeNode raiz, Entorno ent)
        {
            Expresion resultado = resolverExpresion(raiz, ent);

            if (resultado != null)
            {
                if (resultado.tipo != Simbolo.EnumTipo.error)
                {
                    if (resultado.valor != null)
                    {
                        Program.ventanaPrincipal.richConsola.AppendText(resultado.valor.ToString() + "\n");
                    }
                    else
                    {
                        Program.ventanaPrincipal.richConsola.AppendText("La variable no ha sido previamente inicializada. Línea: " + (raiz.Token.Location.Line + 1) + " Columna: " + (raiz.Token.Location.Column + 1) + "\n");
                    }
                }
                else
                {
                    Program.ventanaPrincipal.richConsola.AppendText(resultado.error + "\n");
                }
            }
        }
Exemplo n.º 19
0
        public Resultado ejecutar(Contexto ctx, int nivel)
        {
            if (instruccion.ChildNodes.Count > 0)
            {
                string cad = instruccion.ChildNodes[0].Token.Text;
                //            string Cadena = cad.Substring(1, cad.Length - 2);

                if (instruccion.ChildNodes.Count == 1)
                {
                    Interprete.ConcatenarSalida(cad);
                    Interprete.ConcatenarSalida("\r\n");
                    return(FabricarResultado.creaOk());
                }
                ParseTreeNode Param = instruccion.ChildNodes[1];

                List <String> valores = new List <String>();

                foreach (var parametro in Param.ChildNodes)
                {
                    Resultado res     = new Expresion(parametro.ChildNodes[0]).resolver(ctx);
                    String    tempval = "";
                    if (res.Tipo == Constantes.T_ERROR)
                    {
                    }
                    tempval = res.Valor;
                    valores.Add(tempval);
                }

                String[] parametrosMostrar = valores.ToArray();

                String resultado = String.Format(cad, parametrosMostrar);

                Interprete.ConcatenarSalida(resultado);
                Interprete.ConcatenarSalida("\r\n");
            }
            return(FabricarResultado.creaOk());
        }
Exemplo n.º 20
0
 public object getValor(Entorno.Entorno ent)
 {
     if (contenido == null)
     {
         return(new Lista(tipo));
     }
     else
     {
         Expresion primero      = contenido.First();
         Tipo      tipo_primero = primero.getTipo(ent);
         bool      todos_igual  = true;
         foreach (Expresion exp in contenido)
         {
             Tipo exp_tipo = exp.getTipo(ent);
             if (!tipo_primero.tipo.Equals(exp_tipo.tipo))
             {
                 todos_igual = false;
             }
         }
         if (todos_igual)
         {
             valores = new List <object>();
             foreach (Expresion exp in contenido)
             {
                 Object exp_valor = exp.getValor(ent);
                 valores.Add(exp_valor);
             }
             return(new Lista(valores, tipo_primero));
         }
         else
         {
             Estatico.errores.Add(new ErrorCQL("Semantico", "Error de tipos en la lista no todos son del mismo tipo ", this.fila, this.columna));
         }
     }
     return(null);
 }
Exemplo n.º 21
0
        private Comando ParsearComandoIf()
        {
            Comando resultado;

            lexer.Aceptar();
            lexer.Aceptar(TokenType.lParentesis);
            Expresion exp = ParseExpresionLogica();

            lexer.Aceptar(TokenType.rParentesis);

            Comando comandosDelIF = ParsearComando();

            if (lexer.tokenActual.Type == TokenType.ELSE)
            {
                lexer.Aceptar();
                Comando comandosDelElse = ParsearComando();
                resultado = new ComandoIf(exp, comandosDelIF, comandosDelElse);
            }
            else
            {
                resultado = new ComandoIf(exp, comandosDelIF);
            }
            return(resultado);
        }
Exemplo n.º 22
0
        public Instruccion nuevaAsignacion(ParseTreeNode actual)
        {
            switch (actual.ChildNodes.Count)
            {
            case 7:
                return(new AsignacionObjeto(actual.ChildNodes[0].Token.Text, actual.ChildNodes[2].Token.Text, expresionCadena(actual.ChildNodes[5])));

            default:
                switch (actual.ChildNodes[0].Term.ToString())
                {
                case "ID":
                    return(new NuevaAsignacion(actual.ChildNodes[0].Token.Text, expresionCadena(actual.ChildNodes[3])));

                case "Valor_Arreglo":
                    Expresion expresion = expresionCadena(actual.ChildNodes[3]);
                    actual = actual.ChildNodes[0];
                    LinkedList <Expresion> indices = new LinkedList <Expresion>();
                    return(new AsignacionArreglo(actual.ChildNodes[0].Token.Text, getIndicesArray(actual.ChildNodes[2], indices), expresion));

                default:
                    return(null);
                }
            }
        }
Exemplo n.º 23
0
        static void Main(string[] args)
        {
            Console.WriteLine("DEMO Expresion!");
            var       x = new Variable("x", 100);
            Expresion e = x + 5 * 20;

            Console.WriteLine();
            Console.WriteLine($"Evaluar | {e} => {e.Evaluar()}");
            Console.WriteLine();
            Console.WriteLine(e.NPI());
            Console.WriteLine();
            e.Mostrar();
            Console.ReadLine();
            return;

            Console.WriteLine();
            Expresion contador = new Asignar(x, x + 1);

            Console.WriteLine("> CONTADOR");
            contador.Mostrar();
            Console.WriteLine();
            Console.WriteLine(contador.NPI());
            Console.WriteLine($"Contador | {contador} => {contador.Evaluar()}");
            Console.WriteLine($"Contador | {contador} => {contador.Evaluar()}");
            Console.WriteLine($"Contador | {contador} => {contador.Evaluar()}");

            Console.WriteLine();
            var repetir = new Repeticion(new Menor(x, 20), contador);

            Console.WriteLine("> REPETICION");
            Console.WriteLine(repetir.NPI());
            repetir.Mostrar();

            Console.WriteLine($"Repeticion | {repetir} => {repetir.Evaluar()}");
            Console.ReadLine();
        }
Exemplo n.º 24
0
 public Logica(Expresion op1, Expresion op2, Operador op, int linea, int columna) : base(op1, op2, op, linea, columna)
 {
 }
Exemplo n.º 25
0
 public Logica(Expresion op1, int linea, int columna) : base(op1, null, Operador.NOT, linea, columna)
 {
 }
Exemplo n.º 26
0
 public Unario(Expresion op1, Operador op, int linea, int columna) : base(op1, null, op, linea, columna)
 {
 }
Exemplo n.º 27
0
        public override object Ejecutar(Entorno e, bool funcion, bool ciclo, bool sw, bool tc, LinkedList <Salida> log, LinkedList <Error> errores)
        {
            BD actual = e.Master.Actual;

            if (actual != null)
            {
                if (e.Master.UsuarioActual != null)
                {
                    if (e.Master.UsuarioActual.GetPermiso(actual.Id))
                    {
                        Simbolo sim = actual.GetTabla(Id);

                        if (sim != null)
                        {
                            Tabla tabla = (Tabla)sim.Valor;

                            if (Columnas != null)
                            {
                                if (Columnas.Count() == Valores.Count())
                                {
                                    Entorno datos = tabla.GetNuevaFila();
                                    LinkedList <Simbolo> primary = new LinkedList <Simbolo>();

                                    for (int i = 0; i < Columnas.Count(); i++)
                                    {
                                        Expresion valor    = Valores.ElementAt(i);
                                        object    valValor = valor.GetValor(e, log, errores);
                                        if (valValor != null)
                                        {
                                            if (valValor is Throw)
                                            {
                                                return(valValor);
                                            }

                                            string  col  = Columnas.ElementAt(i);
                                            Simbolo dato = datos.GetCualquiera(col);
                                            if (dato != null)
                                            {
                                                if (dato.Tipo.IsCounter())
                                                {
                                                    return(new Throw("CounterTypeException", Linea, Columna));
                                                    //dato.Valor = tabla.Contador;
                                                    //continue;
                                                }

                                                if (dato.Tipo.Equals(valor.Tipo))
                                                {
                                                    dato.Valor = valValor;

                                                    if (dato.Rol == Rol.PRIMARY)
                                                    {
                                                        if (valValor is Null)
                                                        {
                                                            errores.AddLast(new Error("Semántico", "Una llave primaria no puede ser Null.", Linea, Columna));
                                                            return(null);
                                                        }
                                                    }
                                                }
                                                else
                                                {
                                                    Casteo cast = new Casteo(dato.Tipo, new Literal(valor.Tipo, valValor, 0, 0), 0, 0)
                                                    {
                                                        Mostrar = false
                                                    };
                                                    valValor = cast.GetValor(e, log, errores);

                                                    if (valValor != null)
                                                    {
                                                        if (valValor is Throw)
                                                        {
                                                            return(valValor);
                                                        }

                                                        dato.Valor = valValor;
                                                        continue;
                                                    }

                                                    return(new Throw("ValuesException", Linea, Columna));
                                                    //errores.AddLast(new Error("Semántico", "El tipo de la expresión no corresponde al tipo en la columna: " + sim.Id + ".", Linea, Columna));
                                                    //return null;
                                                }
                                            }
                                            else
                                            {
                                                errores.AddLast(new Error("Semántico", "No hay un campo con el id: " + col + " en la Tabla.", Linea, Columna));
                                                return(null);
                                            }
                                        }
                                        else
                                        {
                                            return(null);
                                        }
                                    }

                                    foreach (Simbolo col in datos.Simbolos)
                                    {
                                        if (col.Tipo.IsCounter())
                                        {
                                            col.Valor = tabla.Contador;
                                        }

                                        if (col.Rol == Rol.PRIMARY)
                                        {
                                            if (col.Valor is Null)
                                            {
                                                errores.AddLast(new Error("Semántico", "Una llave primaria no puede ser Null.", Linea, Columna));
                                                return(null);
                                            }
                                            primary.AddLast(col);
                                        }
                                    }


                                    if (!tabla.Insertar(datos, primary))
                                    {
                                        errores.AddLast(new Error("Semántico", "No se pueden insertar valores con la misma llave primaria.", Linea, Columna));
                                    }
                                    else
                                    {
                                        tabla.Contador++;
                                        Correcto = true;
                                    }

                                    return(null);
                                }
                                else
                                {
                                    errores.AddLast(new Error("Semántico", "La lista de campos no corresponde a la lista de valores.", Linea, Columna));
                                }
                            }
                            else
                            {
                                if (tabla.Cabecera.Simbolos.Count() == Valores.Count())
                                {
                                    Entorno datos = new Entorno(null, new LinkedList <Simbolo>());
                                    LinkedList <Simbolo> primary = new LinkedList <Simbolo>();

                                    for (int i = 0; i < Valores.Count(); i++)
                                    {
                                        Expresion valor    = Valores.ElementAt(i);
                                        object    valValor = valor.GetValor(e, log, errores);
                                        if (valValor != null)
                                        {
                                            if (valValor is Throw)
                                            {
                                                return(valValor);
                                            }

                                            Simbolo col = tabla.Cabecera.Simbolos.ElementAt(i);

                                            if (col.Tipo.IsCounter())
                                            {
                                                return(new Throw("CounterTypeException", Linea, Columna));
                                                //errores.AddLast(new Error("Semántico", "No se puede insertar un valor en una columna tipo Counter.", Linea, Columna));
                                                //return null;
                                            }

                                            if (!col.Tipo.Equals(valor.Tipo))
                                            {
                                                Casteo cast = new Casteo(col.Tipo, new Literal(valor.Tipo, valValor, 0, 0), 0, 0)
                                                {
                                                    Mostrar = false
                                                };
                                                valValor = cast.GetValor(e, log, errores);

                                                if (valValor == null)
                                                {
                                                    if (valValor is Throw)
                                                    {
                                                        return(valValor);
                                                    }

                                                    return(new Throw("ValuesException", Linea, Columna));
                                                    //errores.AddLast(new Error("Semántico", "El tipo de la expresión no corresponde al tipo en la columna: " + col.Id + ".", Linea, Columna));
                                                    //return null;
                                                }
                                            }

                                            Simbolo dato = new Simbolo(col.Tipo, col.Rol, col.Id, valValor);
                                            if (col.Rol == Rol.PRIMARY)
                                            {
                                                if (valValor is Null)
                                                {
                                                    errores.AddLast(new Error("Semántico", "Una llave primaria no puede ser Null.", Linea, Columna));
                                                    return(null);
                                                }
                                                primary.AddLast(dato);
                                            }
                                            datos.Add(dato);
                                        }
                                        else
                                        {
                                            return(null);
                                        }
                                    }

                                    if (!tabla.Insertar(datos, primary))
                                    {
                                        errores.AddLast(new Error("Semántico", "No se pueden insertar valores con la misma llave primaria.", Linea, Columna));
                                    }
                                    else
                                    {
                                        Correcto = true;
                                    }
                                    return(null);
                                }
                                else
                                {
                                    return(new Throw("ValuesException", Linea, Columna));
                                }
                                //errores.AddLast(new Error("Semántico", "Los valores no corresponden a las columnas en la Tabla.", Linea, Columna));
                            }
                        }
                        else
                        {
                            return(new Throw("TableDontExists", Linea, Columna));
                        }
                        //errores.AddLast(new Error("Semántico", "No existe una Tabla con el id: " + Id + " en la base de datos.", Linea, Columna));
                    }
                    else
                    {
                        errores.AddLast(new Error("Semántico", "El Usuario no tiene permisos sobre: " + actual.Id + ".", Linea, Columna));
                    }
                }
                else
                {
                    errores.AddLast(new Error("Semántico", "No hay un Usuario logeado.", Linea, Columna));
                }
            }
            else
            {
                return(new Throw("UseBDException", Linea, Columna));
            }
            //errores.AddLast(new Error("Semántico", "No se ha seleccionado una base de datos, no se pudo Insertar.", Linea, Columna));

            return(null);
        }
Exemplo n.º 28
0
 public Return(Expresion exp, int linea, int columna)
 {
     this.valorRetorno = exp;
     this.linea        = linea;
     this.columna      = columna;
 }
Exemplo n.º 29
0
 /*
  * CONSTRUCTOR DE LA CLASE
  * param {expresion} expresion a mostrar
  */
 public Log(Expresion expresion)
 {
     this.expresion = expresion;
 }
 public FuncionAudio(Expresion ruta, Expresion condicion, String clase, int linea, int col) : base(linea, col, clase)
 {
     this.ruta      = ruta;
     this.condicion = condicion;
 }
Exemplo n.º 31
0
Arquivo: Peg.cs Projeto: xrisjc/misc
 public OrderedChoice(Expresion e1, Factory e2Factory)
 {
     this.e1 = e1;
     this.e2Factory = e2Factory;
 }
Exemplo n.º 32
0
 public Switch(Expresion expr, LinkedList <Case> cases, int linea, int columna) : base(linea, columna)
 {
     Expr  = expr;
     Cases = cases;
 }
Exemplo n.º 33
0
Arquivo: Peg.cs Projeto: xrisjc/misc
 public ZeroOrMore(Expresion e)
 {
     this.e = e;
 }
Exemplo n.º 34
0
Arquivo: Peg.cs Projeto: xrisjc/misc
 public Sequence(Expresion e1, Expresion e2)
 {
     this.e1 = e1;
     this.e2 = e2;
 }