Exemple #1
0
import gramatica as g
import Utils.TablaSimbolos as table
import Utils.Lista as l

datos = l.Lista([], '')

ruta = '../G26/entrada.txt'
f = open(ruta, "r")
input = f.read()

instrucciones = g.parse(input)

for instr in instrucciones :
    instr.execute(datos)

print (datos)
Exemple #2
0
# Server imports
from http.server import HTTPServer, BaseHTTPRequestHandler
import io
import os
import json

# Parser imports
import Instrucciones.DML.select as select
from Error import *
import Librerias.storageManager.jsonMode as storage
import gramatica as g
import Utils.Lista as l

# Data list
storage.dropAll()
datos = l.Lista({}, '')

# Setting server port
PORT = 8000


#Def. requests handler.
class MyRequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        #Definiendo rutas para peticiones get
        if self.path == '/getUsers':
            self.do_getUsers()
        elif self.path == '/getDatabases':
            self.do_getDatabases()
        else:
            self.send_response(400)
Exemple #3
0
def analisis():
    global datos

    salida.delete("1.0", "end")
    texto = editor.get("1.0", "end")

    #g2.tempos.restartTemp() #reinicia el contador de temporales.
    prueba = g2.parse(texto)
    try:
        escribirEnSalidaFinal(prueba['printList'])
    except:
        ''
    #print(prueba['text'])
    try:
        exepy = '''
#imports
import sys
sys.path.append('../G26/Librerias/goto')

from goto import *
import gramatica as g
import Utils.Lista as l
import Librerias.storageManager.jsonMode as storage
import Instrucciones.DML.select as select
from Error import *
import reporte as reporte

#storage.dropAll()

heap = []
semerrors = []
erroresS = list()

datos = l.Lista({}, '')
l.readData(datos)
'''
        exepy += '''
#funcion intermedia
def mediador(value):
    global heap
    global semerrors
    global reporte
   # Analisis sintactico
    instrucciones = g.parse(heap.pop())
    erroresS = (g.getMistakes())

    for instr in instrucciones['ast'] :
        if instr == None:
            erroresS = g.getMistakes()
            return 0
        try:
            val = instr.execute(datos)
        except:
            val = (instr.execute(datos, {}))

        if isinstance(val, Error):
            'error semantico'
            print(val)
            semerrors.append(val)
        elif isinstance(instr, select.Select) :

            if value == 0:
                try:
                    print(val)
                    if len(val.keys()) > 1 :
                        print('El numero de columnas retornadas es mayor a 1')
                        return 0
                    for key in val:
                        if len(val[key]['columnas']) > 1 :
                            print('El numero de filas retornadas es mayor a 1')
                        else :
                            return val[key]['columnas'][0][0]
                        break
                except:
                    return 0
            else:
                print(instr.ImprimirTabla(val))
        else :
            try:
                return val.val
            except:
                print(val)

    l.writeData(datos)
'''

        exepy += '''
#funciones de plg-sql


'''
        l.readData(datos)
        optt = ""
        for val in datos.tablaSimbolos.keys():
            if val == 'funciones_':
                for func in datos.tablaSimbolos[val]:
                    try:
                        f = open("./Funciones/" + func['name'] + ".py", "r")
                        pruebaaa = f.read()
                        optt = opt.optimizar(pruebaaa)
                        exepy += optt
                        f.close()
                    except:
                        exepy += '#Se cambio el nombre del archivo que guarda la funcion. Funcion no encontrada'
        exepy += '''
#main
@with_goto
def main():
    global heap
'''

        exepy += str(prueba['text'])
        exepy += '''
    reporte.Rerrores(erroresS, semerrors, "Reporte_Errores_Semanticos.html")

#Ejecucion del main
if __name__ == "__main__":
    main()
'''

        f = open("./c3d.py", "w")
        f.write(exepy)
        f.close()

        l.readData(datos)
        if 'funciones_' in datos.tablaSimbolos:
            for funciones in datos.tablaSimbolos['funciones_']:
                #print(funciones)
                if funciones['drop'] == 0:
                    try:
                        os.remove('../G26/Funciones/' + funciones['name'] +
                                  '.py')
                    except:
                        ''

        try:
            reporte.hacerReporteGramatica(prueba['reporte'])
            errores = g2.getMistakes()
            recorrerErrores(errores)
            reporte.Rerrores(errores, [],
                             "Reporte_Errores_Sintactico_Lexicos.html")
            reporte.reporteTabla(datos)
        except:
            ''

        escribirEnSalidaFinal('Se ha generado el codigo en 3 direcciones.')
        #aqui se puede poner o llamar a las fucniones para imprimir en la consola de salida
        reptOpti = prueba['opt']
        fro = open("./Reportes/ReporteOptimizacion.txt", "w")
        fro.write(reptOpti)
        fro.close()
    except:
        print(
            "No se ha podido generar el codigo ya que existen errores sintacticos"
        )
        escribirEnSalidaFinal(
            "No se ha podido generar el codigo ya que existen errores sintacticos"
        )
Exemple #4
0
def analisis():
    global datos

    salida.delete("1.0", "end")
    texto = editor.get("1.0", "end")

    #g2.tempos.restartTemp() #reinicia el contador de temporales.
    prueba = g2.parse(texto)
    try:
        escribirEnSalidaFinal(prueba['printList'])
    except:
        ''
    #print(prueba['text'])

    exepy = '''
#imports
import sys
sys.path.append('../G26/Librerias/goto')

from goto import *
import gramatica as g
import Utils.Lista as l
import Librerias.storageManager.jsonMode as storage
import Instrucciones.DML.select as select
from Error import *

#storage.dropAll()

heap = []
semerrors = []

datos = l.Lista({}, '')
l.readData(datos)
'''
    exepy += '''
#funcion intermedia
def mediador(value):
    global heap
    global semerrors
   # Analisis sintactico
    instrucciones = g.parse(heap.pop())
    for instr in instrucciones['ast'] :

        try:
            val = instr.execute(datos)
        except:
            val = (instr.execute(datos, {}))

        if isinstance(val, Error):
            'error semántico'
            print(val)
            semerrors.append(val)
        elif isinstance(instr, select.Select) :
            
            if value == 0:
                try:
                    print(val)
                    if len(val.keys()) > 1 :
                        print('El numero de columnas retornadas es mayor a 1')
                        return 0
                    for key in val:
                        if len(val[key]['columnas']) > 1 :
                            print('El numero de filas retornadas es mayor a 1')
                        else :
                            return val[key]['columnas'][0][0]
                        break
                except:
                    return 0
            else:
                print(instr.ImprimirTabla(val))
        else :
            try:
                return val.val
            except:
                print(val)

    l.writeData(datos)
'''

    exepy += '''
#funciones de plg-sql


'''
    l.readData(datos)
    optt = ""
    for val in datos.tablaSimbolos.keys():
        if val == 'funciones_':
            for func in datos.tablaSimbolos[val]:
                try:
                    f = open("./Funciones/" + func['name'] + ".py", "r")
                    pruebaaa = f.read()
                    optt = opt.optimizar(pruebaaa)
                    exepy += optt
                    f.close()
                except:
                    exepy += '#Se cambio el nombre del archivo que guarda la funcion. Funcion no encontrada'
    exepy += '''
#main
@with_goto
def main():
    global heap
'''

    exepy += str(prueba['text'])

    exepy += '''
#Ejecucion del main
if __name__ == "__main__":
    main()
'''

    f = open("./c3d.py", "w")
    f.write(exepy)
    f.close()
    '''try:
        f = open("./Utils/tabla.txt", "r")
        text = f.read()
        f.close()
        text = text.replace('\'','"')
        text = text.replace('False','"False"')
        text = text.replace('None','""')
        text = text.replace('True','"True"')
        datos.reInsertarValores(json.loads(text))
    except:
        print('error')

    instrucciones = g.parse(texto)
    erroresSemanticos = []

    try:
        hacerReporteGramatica(instrucciones['reporte'])
    except:
        print("")

    for instr in instrucciones['ast'] :

            if instr != None:
                result = instr.execute(datos)
                if isinstance(result, Error):
                    escribirEnSalidaFinal(str(result.desc))
                    erroresSemanticos.append(result)
                elif isinstance(instr, select.Select) or isinstance(instr, select.QuerysSelect):
                    escribirEnSalidaFinal(str(instr.ImprimirTabla(result)))
                else:
                    escribirEnSalidaFinal(str(result))


    f = open("./Utils/tabla.txt", "w")
    f.write(str(datos))
    f.close()

    '''
    try:
        errores = g.getMistakes()
        recorrerErrores(errores)
        #Rerrores(errores, erroresSemanticos)
        errores.clear()
        #erroresSemanticos.clear()
        reporteTabla()
        del prueba
    except:
        ''

    escribirEnSalidaFinal('Se ha generado el codigo en 3 direcciones.')
    #aqui se puede poner o llamar a las fucniones para imprimir en la consola de salida
    reptOpti = prueba['opt']
    fro = open("./Reportes/ReporteOptimizacion.txt", "w")
    fro.write(reptOpti)
    fro.close()
Exemple #5
0
import Librerias.storageManager.jsonMode as storage
from tkinter.filedialog import askopenfilename as files
import os
import webbrowser
from Utils.fila import fila
from Error import *
import Instrucciones.DML.select as select
import json
import reporte as reporte
import optimizar as opt
#from select import *

##########################################################################

storage.dropAll()
datos = l.Lista({}, '')


##################################FUNCIONES#################################
def openFile():
    route = files(filetypes=[("TXT Files", "*.txt")])
    if not route:
        salida.insert("end", "\nERROR AL ABRIR AL ARCHIVO")
        return
    editor.delete("1.0", TK.END)
    with open(route, "r") as input_file:
        text = input_file.read()
        editor.insert(TK.END, text)
    root.title(f"TYTUSDB_Parser - {route}")