コード例 #1
0
ファイル: gocheck.py プロジェクト: nicolas11258/Compilers
        def visit_FuncDeclaration(self,node):
            node.type = None # tipo None por defecto
            # 1. comprobar si el tipo que retorna (si existe) es nativo de go
            if not isinstance(node.typename,Empty):
                self.visit(node.typename)
                node.type = node.typename.type

            # 2. comprobar que la función no esté definida antes
            if self.current.lookup(node.id):
                error(node.lineno, "La función %s ya se ha declarado antes" % node.id)
            else:
                self.current.add(node.id,node) # guardando el id de la función y el objeto en la tabla de su padre

            # 3. crear tabla de símbolos para el cuerpo de la función
                self.push_symtab('function',node)
                node.symtab.add("int",gotype.int_type)
                node.symtab.add("float",gotype.float_type)
                node.symtab.add("string",gotype.string_type)
                node.symtab.add("bool",gotype.boolean_type)

            # 4. comprobar parámetros de función y anexarlos a la tabla de símbolos
                self.visit(node.parameters)

            # 5. comprobar cuerpo de la función
                self.visit(node.statements)

            # 6. comprobar returns asociados
                # comprobar los return propios del cuerpo de la función
                self.check_returns_on_func(self.current.returnsSet,node)
                # comprobar los return dentro de los statements con tabla de símbolos
                self.check_returns_on_statements_on_func(self.current,node)

            # 7. entregar dominio a tabla de símbolos program
                self.pop_symbol()
コード例 #2
0
 def pro_add_op(self):
     if self.accept('+'):
         return '+'
     elif self.accept('-'):
         return '-'
     else:
         error(self.token[2], 'Unexpected symbol.', 'add_op')
コード例 #3
0
ファイル: runner.py プロジェクト: RaidTheWeb/Quill
 def _import(self, *args):
     name = args[0].val
     try:
         if name.startswith('stdlib'):
             file = open((__file__.rstrip('/src/runner.py') +
                          f'/{name}.qyl').lstrip('/'))
         else:
             file = open(os.path.join(os.getcwd(), f'{name}.qyl'))
         ast = parse.Parser().parse(parse.Lexer().tokenize(file.read()))
         program = Program(ast)
         program.run()
         self.globals.set(data.Symbol(name.split('/')[-1]), program.globals)
     except FileNotFoundError:
         try:
             if name.startswith('stdlib'):
                 file = open((__file__.rstrip('/src/runner.py') +
                              f'/{name}.py').lstrip('/'))
             else:
                 file = open(os.path.join(os.getcwd(), f'{name}.py'))
             out = {}
             exec(compile(file.read(), 'quill', 'exec'), out)
             map = data.Map(data.Symbol, data.Type)
             map.attrs.update(out['attrs'])
             self.globals.set(data.Symbol(name.split('/')[-1]), map)
         except FileNotFoundError:
             errors.error('File not found')
コード例 #4
0
ファイル: gocheck.py プロジェクト: nicolas11258/Compilers
 def visit_IfStatement(self, node):
     self.visit(node.condition)
     if not node.condition.type == gotype.boolean_type:
         error(node.lineno,"Error, expresión booleana no válida")
     self.visit(node.then_b)
     if node.else_b:
         self.visit(node.else_b)
コード例 #5
0
def tokenize(text):
    index = 0  # Posición actual
    lineno = 1

    while index < len(text):  #condicion para comparar la longitud del texto
        # Produce un token
        if text[index] in ' \t':
            index += 1
            continue

        elif text[index] == '\n':
            lineno += 1
            index += 1
            continue
        #print('sebas')

        # Comentarios Largos

        # Coincidencia de simbolos a traves de expresiones regulares

        value, type_token = find_match(text, index)

        if value:
            if type_token not in ["COMMENTS"]:
                yield Token(type_token, value, lineno)
            index += len(value)
            continue
        else:
            error("caracter ilegal '%s'" % text[index], lineno)
            index += 1
コード例 #6
0
    def visitOnGoto(self, ongoto):
        """
        Connect the OnGoto to the first statement on each of the target lines
        if they exist. Error if they do not. Also connect to the first line of
        the out-of-range clause if present, and process each statement within
        that clause.
        """
        logger.debug("visitOnGoto")
        ongoto.targetStatements = [] # TODO: Fix this so it isn't a monkey patch!
        for targetLogicalLine in ongoto.targetLogicalLines:
            ongoto_target = self.line_mapper.statementOnLine(targetLogicalLine)
            if ongoto_target:
                connect(ongoto, ongoto_target)
                ongoto.targetStatements.append(ongoto_target)
            else:
                errors.error("No such line %s at line %s" % (targetLogicalLine.value, ongoto.lineNum))
        
        first_else_statement = None    
        if ongoto.outOfRangeClause is not None:
            if isinstance(ongoto.outOfRangeClause, list):
                if len(ongoto.outOfRangeClause) > 0:
                    # Connect to the beginning of the else clause
                    first_else_statement = ongoto.outOfRangeClause[0]
                    connect(ongoto, first_else_statement)
                    
                    for statement in ongoto.outOfRangeClause:
                        self.visit(statement)
            else:
                first_else_statement = ongoto.outOfRangeClause
                connect(ongoto, ongoto.outOfRangeClause)
                self.visit(ongoto.outOfRangeClause)
        ongoto.outOfRangeStatement = first_else_statement  # TODO: Fix this so it isn't a monkey patch!

        assert hasattr(ongoto, "targetStatements")
        assert hasattr(ongoto, "outOfRangeStatement")
コード例 #7
0
ファイル: req.py プロジェクト: vmitriaev/ReqResClient
    def send(self):
        '''Отправка запроса'''
        s_meth = str(self.meth).lower()
        s_url = str(self.url).lower()
        f_url = str(self.d_url + s_url).lower()
        s_body = str(self.body).lower()

        if s_meth == 'get':
            i = requests.get(url=f_url)
            return Res(i)

        elif s_meth == 'post':
            i = requests.post(url=f_url, data=s_body)
            return Res(i)

        elif s_meth == 'put':
            i = requests.put(url=f_url, data=s_body)
            return Res(i)

        elif s_meth == 'patch':
            i = requests.patch(url=f_url, data=s_body)
            return Res(i)

        elif s_meth == 'delete':
            i = requests.delete(url=f_url)
            c = i.status_code
            if c == 204:
                return '\nStatus: NO CONTENT' + '\nCode: ' + str(c) + '\n'

            else:
                return error('unknown status code ' + str(c))

        else:
            return error('unknown method ' + s_meth.upper())
コード例 #8
0
ファイル: mpascheck.py プロジェクト: alsuga/mpascal
 def visit_Cast(self,node):
   self.visit(node.expression)
   if node.typename == "int" or node.typename=="float":
     node.type = self.symtab.lookup(node.typename)
   else:
     error(node.lineno,"Cast invalido")
     node.type = self.symtab.lookup("void")
コード例 #9
0
ファイル: codeinterpret.py プロジェクト: simonkosina/IPP
    def parseName(self, name):
        """
        Z názvu premennej odvodí rámec a skontroluje dostupnosť.

        Parametre:
            name (string): názov premennej vo formáte ramec@meno
        
        Výstup:
            (Name, Frame): meno premmenej, rámec premennej
        """

        parts = name.partition("@")
        frame_str = parts[0]
        name = parts[-1]

        if frame_str == "GF":
            frame = self.gf
        elif frame_str == "TF":
            if self.tf is None:
                errors.error("Dočasný rámec neexistuje.", errors.NO_FRAME)

            frame = self.tf
        elif frame_str == "LF":
            if not self.lf_stack:
                errors.error("Lokálny rámec neexistuje.", errors.NO_FRAME)

            frame = self.lf_stack[-1]

        return (name, frame)
コード例 #10
0
ファイル: codeinterpret.py プロジェクト: simonkosina/IPP
    def STRI2INTS(self):
        """
        Zásobníková verzia inštrukcie STRI2INT.
        """

        try:
            symb2_o = self.getVariable(self.stack.pop())
            symb1_o = self.getVariable(self.stack.pop())
        except IndexError:
            errors.error("Chýbajúca hodnota na dátovom zásobníku.",
                         errors.MISSING_VALUE)

        if not symb2_o.isInt():
            errors.error("Chybný typ 2. operandu v inštrukcii STR2INTS.",
                         errors.OP_TYPE)

        if symb2_o.getValue() < 0:
            errors.error(f"Indexácia mimo reťazec v inštrukcii STR2INTS.",
                         errors.BAD_STRING)

        if not symb1_o.isString():
            errors.error("Chybný typ 1. operandu v inštrukcii STR2INTS.",
                         errors.OP_TYPE)

        try:
            val = ord(symb1_o.getValue()[symb2_o.getValue()])
            self.stack.append(("int", val))
        except IndexError:
            errors.error(f"Indexácia mimo reťazec v inštrukcii STR2INTS.",
                         errors.BAD_STRING)
コード例 #11
0
ファイル: handleData.py プロジェクト: mvhdi/Weather-Station
    def build_file_for_dash(self):
        index = 1  #WRITE DATA FOR	DASHBOARD:
        errors.debug("Building converted data file for dash.")
        try:  #this file will be read using pysftp by the dashboard application whenever it loads
            with open("data_for_dash",
                      'a') as fordash:  #open format file and data file
                with open("dashformat.txt", 'r') as dashformat:
                    for line in dashformat:  #for each line in format file
                        if line[:
                                4] == "STR:":  #if the line is a string tag, copy it over
                            fordash.write("CVT\t" + line[4:].strip() + '\n')
                        else:  #if it's a label, copy it over with data appended
                            fordash.write(line.strip() + '\t' +
                                          self.data_list[index] + '\n')
                            index += 1
        except IndexError:
            if not self.for_dash_error:
                errors.error(
                    "Error in parsing dashformat.txt; file may have been " +
                    "corrupted. Dashboard may not display data properly or correctly."
                    + " Error message: " +
                    traceback.format_exc(Config.TRACEBACK_LIMIT))
            else:
                errors.debug(
                    "Error in writing data_for_dash again, don't trust dashboard."
                )
            self.for_dash_error = True

        self.data_list = []
コード例 #12
0
ファイル: handleData.py プロジェクト: mvhdi/Weather-Station
    def send_commands(self):
        """
		Reads files holding all commands for the PIC and sends them.
		Command file should be formatted as <cmd><tab><source>, with
		one command per line.
		"""
        errors.debug("Preparing to send commands to PIC.")
        try:
            with open(Config.COMMAND_FILE_PATH, 'r') as command_file:
                for line in command_file:
                    command = line.split('\t')
                    errors.debug(str(command))
                    if len(command) > 2:
                        self.port.write(command[0].strip())
                        if command[1].strip() == "DASH":
                            errors.info("TS-4200 sent command " + command[0] +
                                        " from source " + command[1].strip() +
                                        " to PIC via serial.")
                        else:
                            errors.debug("Sent command " + command[0] +
                                         " from source " + command[1].strip())
        except:
            if not self.command_error:
                self.command_error = True
                errors.error(
                    "Error in reading and sending commands. Error message: " +
                    traceback.format_exc(Config.TRACEBACK_LIMIT))
        else:
            open(Config.COMMAND_FILE_PATH, 'w').close()
コード例 #13
0
 def pro_comparison_op(self):
     if self.accept('<'):
         return '<'
     elif self.accept('='):
         return '='
     else:
         error(self.token[2], 'Unexpected symbol.', 'comparison_op')
コード例 #14
0
ファイル: check.py プロジェクト: leiverandres/Compiler
 def visit_Program(self, node):
     self.local_symtab = self.global_symtab
     # 1. Visita todas las funciones
     # 2. Registra la tabla de simbolos asociada
     self.visit(node.funList)
     if not self.symtab_lookup('main'):
         error(0, "main function missing")
コード例 #15
0
 def visit_SubTypeDeclaration(self,node):
     print 'SubType'
     print node.name
     print self.environment.scope_level()
     if self.environment.look(node.name) is not None:
         error(node.lineno, "Attempted to redefine var '{}', not allowed".format(node.name))
     else :
         p=self.environment.lookup(node.typename.name)
         if isinstance(p,TypeDeclaration) :
             node.expr = p.expr
             node.typename = p.typename
             self.visit(node.typename)
             if node.length is not None :
                 self.visit(node.length)
             if node.expr is not None :
                 self.visit(node.expr)
             self.environment.add_local(node.name, node)
             if hasattr(node.typename, "check_type"):
                 node.check_type = node.typename.check_type
         else :
             error(node.lineno, "Type is not valid")
         '''if node.expr is None:
             default = node.check_type.default
             node.expr = Literal(default)
             node.expr.check_type = node.check_type'''
     node.scope_level = self.environment.scope_level()
コード例 #16
0
ファイル: check.py プロジェクト: leiverandres/Compiler
    def visit_FunCall(self, node):
        # 1.Revisar que la funcion exista
        # 2.Comparar cantidad de paramentros y sus tipos
        # por ahora
        #si no tiene tipo aun, es por que esta definida despues o es un llamado recursivo
        #entonces buscamos el tipo en los statements de la instancia
        sym = self.symtab_lookup(node.id)
        if not sym:
            error(node.lineno, "Function '%s' is not defined" % node.id)
        else:
            if sym['datatype'] == None:
                datatype = self.find_fun_type(sym['fun_instance'])
                self.update_datatype(node.id, datatype)
                sym = self.symtab_lookup(node.id) #update

            if not node.id == 'main':
                node.datatype = sym['datatype']
                if sym['cant_argms'] == len(node.params.expressions):
                    type_params = self.visit(node.params)
                    type_argms = sym['type_argms']

                    for i in xrange(0, sym['cant_argms']):
                        if not type_argms[i] == type_params[i]:
                            error(node.lineno, "Arguments must have same type")
                            break
                else:
                    if sym['type_argms'][0] == None:
                        error(node.lineno, "Function '%s' takes no arguments %d given" \
                              % (node.id, len(node.params.expressions)))
                    else:
                        error(node.lineno, "Function '%s' takes exactly %d arguments %d given" \
                              % (node.id, sym['cant_argms'], len(node.params.expressions)))
            else:
                error(node.lineno, "You cannot call main function")
コード例 #17
0
 def visit_Location(self,node):
     print 'Location'
     print self.environment.scope_level()
     sym = self.environment.lookup(node.name)
     if not sym:
         error(node.lineno, "name '{}' not found".format(node.name))
     node.check_type = sym.check_type
コード例 #18
0
ファイル: lexer.py プロジェクト: c-mori/blaze-core
def _escape_token(t):
    try:
        t.value = _escape_pat.sub(escape_token, t.value)
    except Unescaped as e:
        escape_code = e.args[0]
        error(t.lexer.lineno,"Syntax Error: Unescaped sequence '%s'" % escape_code)
        return escape_code
コード例 #19
0
def _replace_escape_codes(t):
    r'''
    *** YOU MUST IMPLEMENT ***
    
    Replace all of the valid escape codes \.. in a string with
    their raw character code equivalents.   Suggest doing this
    with re.sub()
    '''
    literals = {
        r"\\n": "\n",
        r"\\r": "\r",
        r"\\t": "\t",
        r"\\\\": r"\\",
        r'\\"': r'"'
    }
    re_byte = r".*\\b(?P<val>[0-9a-fA-F]{2}).*"
    byte_pat = re.compile(re_byte)
    for pattern, repl in literals.items():
        t.value = re.sub(pattern, repl, t.value)
    matcher = byte_pat.match(t.value)
    if matcher:
        val = matcher.groupdict()["val"]
        val = chr(int(val, 16))
        # chomping first 2 and last 2 chars of pattern to eliminate .*
        # yes, this is a bit hacky
        t.value = re.sub(re_byte[2:-2], val, t.value)
    # Error to use for reporting a bad escape code
    if False:
        error(t.lexer.lineno, "Bad string escape code '%s'" % escape_code)
コード例 #20
0
ファイル: exprcheck.py プロジェクト: Davesco/mpascal
 def visit_Typename(self,node):
     # 1. Make sure the typename is valid and that it's actually a type
     sym = self.symtab.lookup(node.name)
     if not isinstance(sym, MpasType):
         error(node.lineno, "{} is not a valid type".format(node.name))
         return
     node.type = sym
コード例 #21
0
 def visit_Typename(self, node):
     # 1. Make sure the typename is valid and that it's actually a type
     sym = self.environment.lookup(node.name)
     if not isinstance(sym, ExprType):
         error(node.lineno, "{} is not a valid type".format(node.name))
         return
     node.check_type = sym
コード例 #22
0
ファイル: exprlex.py プロジェクト: Hydex/compiler-1
def _replace_escape_codes(t):
    r'''
    *** YOU MUST IMPLEMENT ***
    
    Replace all of the valid escape codes \.. in a string with
    their raw character code equivalents.   Suggest doing this
    with re.sub()
    '''
    literals = {
        r"\\n": "\n",
        r"\\r": "\r",
        r"\\t": "\t",
        r"\\\\": r"\\",
        r'\\"': r'"'
    }
    re_byte = r".*\\b(?P<val>[0-9a-fA-F]{2}).*"
    byte_pat = re.compile(re_byte)
    for pattern, repl in literals.items():
        t.value = re.sub(pattern, repl, t.value)
    matcher = byte_pat.match(t.value)
    if matcher:
        val = matcher.groupdict()["val"]
        val = chr(int(val, 16))
        # chomping first 2 and last 2 chars of pattern to eliminate .*
        # yes, this is a bit hacky
        t.value = re.sub(re_byte[2:-2], val, t.value)
    # Error to use for reporting a bad escape code
    if False:
        error(t.lexer.lineno,"Bad string escape code '%s'" % escape_code)
コード例 #23
0
 def visit_Location(self, node):
     # 1. Make sure the location is a valid variable or constant value
     sym = self.environment.lookup(node.name)
     if not sym:
         error(node.lineno, "name '{}' not found".format(node.name))
     # 2. Assign the type of the location to the node
     node.check_type = sym.check_type
コード例 #24
0
ファイル: codeparser.py プロジェクト: simonkosina/IPP
    def readInput(self):
        """
        Metóda číta vstup. Do self.xml_root uloží koreň XML stromu.
        """

        xml_string = ""

        # Nacitanie vstupu
        if not self.src_file:
            xml_string = sys.stdin.read()
        else:
            try:
                with open(self.src_file, "r") as f:
                    xml_string = f.read()
            except IOError as err:
                errors.error("Chyba pri práci so vstupným súborom.",
                             errors.INPUT_FILE)

        # Vytvorenie XML stromu
        try:
            self.xml_root = ET.fromstring(xml_string)
        except ET.ParseError as err:
            errors.error(
                f"Chybný XML formát vstupného súboru.\nRiadok: {err.position[0]}, Stĺpec: {err.position[1]}",
                errors.XML_FORMAT)
コード例 #25
0
 def visit_Literal(self, node):
     # Attach an appropriate type to the literal
     valtype = type(node.value)
     check_type = self.typemap.get(valtype, None)
     if check_type is None:
         error(node.lineno, "Using unrecognized type {}".format(valtype))
     node.check_type = check_type
コード例 #26
0
ファイル: gocheck.py プロジェクト: nicolas11258/Compilers
 def visit_ParamDecl(self, node):
     if not node.id in self.current.symtab: # consultar primero que un parámetro todavía no está en la tabla de símbolos
         self.visit(node.typename) # comprobar que el tipo fue escrito correctamente y es nativo de go
         node.type = node.typename.type # si no hubo problemas, definir el tipo nativo de go para el parámetro
         self.current.add(node.id,node) # finalmente registrar en la tabla de símbolos de la función el parámetro
     else:
         error(node.lineno,"Error, el parámetro ya fue declarado")
コード例 #27
0
    def visit_VarDeclaration(self, node):

        node.type = self.current.lookup(node.typename.typename)
        assert (node.type)
        #print("node.value:",node.value.value.value)
        #print("node.value:",dir(node.value))
        #print("node.value.type:",node.value.type)
        #print("node.typename.typename:",node.typename.typename)
        #muestra la __repr__
        # 1. Revise que el nombre de la variable no se ha definido
        if self.current.lookup(node.id):
            error(node.lineno, "Símbol %s ya definido" % node.id)
        # 2. Agrege la entrada a la tabla de símbolos
        else:
            self.current.add(node.id, node.type)

        # 2. Revise que el tipo de la expresión (si lo hay) es el mismo

        if node.value:
            self.visit(node.value)

            if isinstance(node.value.type, str):
                a = self.current.tipodato(node.value.type)

                assert (node.typename.typename == a.name)
        # assert(node.typename == node.value.type.name)
        # 4. Si no hay expresión, establecer un valor inicial para el valor
        else:
            node.value = None
コード例 #28
0
 def visit_LocationIndexed(self, node):
     sym = self.current.lookup(node.id)
     if sym is None:
         error(node.lineno, node.id + " Unknow symbol")
     if not self.visit(node.expr)['type'] is int_type:
         error(node.lineno, "Only integer can be used to declare index")
     return sym
コード例 #29
0
    def visit_Typename(self, node):
        # 1. Revisar que el nombre de   tipo es válido que es actualmente un tipo

        if (node.type not in self.tipos):
            error(node.lineno, "%s Tipo Invalido" % node.type)
        else:
            self.visit(node.type)
コード例 #30
0
ファイル: hoccheck.py プロジェクト: MauroCG/compilador_hoc
 def visit_UnaryOp(self, node):
     # 1. Asegúrese que la operación es compatible con el tipo
     # 2. Ajuste el tipo resultante al mismo del operando
     self.visit(node.left)
     if not hoclex.operators[node.op] in node.left.type.un_ops:
         error(node.lineno, "Operación no soportada con este tipo")
     node.type = node.left.type
コード例 #31
0
 def visit_Location(self, node):
     # 1. Revisar que la localización es una variable válida o un valor constante
     # 2. Asigne el tipo de la localización al nodo
     if (self.current.lookup(node.location) not in self.tipos):
         error(node.lineno, "La localizacion no es una variable valida")
     else:
         node.type = self.current.lookup(node.location)
コード例 #32
0
ファイル: check.py プロジェクト: leiverandres/Compiler
 def visit_UnaryOp(self, node):
     # 1. Asegúrese que la operación es compatible con el tipo
     # 2. Ajuste el tipo resultante al mismo del operando
     self.visit(node.right)
     if not node.op in node.right.datatype.un_ops:
         error(node.lineno, "Operación no soportada con este tipo")
     node.datatype = node.right.datatype
コード例 #33
0
 def visit_Opper(self, node):
     print("nodepér", node)
     if not self.current.lookup(node.ID.location):
         error(node.lineno,
               "La variable %s no ha sido declarada" % node.ID.location)
     node.type = gotype.int_type
     node.value = node
コード例 #34
0
ファイル: gonecheck.py プロジェクト: geraldstanje/gone
    def visit_WhileStatement(self, node):
        self.visit(node.relation)
        self.visit(node.while_body)

        if node.relation.type != types.BoolType:
            error(node.lineno, 'If statement must use bool test')
            node.type = TypeError
コード例 #35
0
ファイル: rigidBodyRefine.py プロジェクト: charliebury/RIDL
    def __init__(
        self, inputFile='untitled.txt', makeNewRIDLfile=True,
            numCycles=10):

        self.inputFile = inputFile
        self.printPurpose()
        self.parseInputFile()

        newPDBs = []
        for mtz, cols in zip(self.mtzList, self.mtzCols):
            self.runREFMAC(
                pdbIn=self.initialPDB, mtzIn=mtz,
                mtzCols=cols, rFree=self.rFree,
                numCycles=numCycles)

            newPDBs.append(self.refmacPDBout)

            # check the output log indicates success
            with open(self.outputLogfile, 'r') as log:
                for ln in log.readlines():
                    if 'Refmac:  Error' in ln:
                        error(text='refmac did not run to completion. ' +
                                   'Please refer to the log file for ' +
                                   'refmac "{}"'.format(self.outputLogfile))

            # check if required files from refinement are present
            self.checkFileExists(self.refmacPDBout)

        if makeNewRIDLfile:
            self.createNewRIDLfile(newPDBs)
コード例 #36
0
ファイル: mpascheck.py プロジェクト: Davesco/mpascal
	def visit_Location(self,node):
		 # 1. Make sure the location is a valid variable or constant value
		sym = self.symtab.lookup(node.name)
		if not sym:
			error(node.lineno, "nombre '%s' no fue encontrado" % node.id)
        # 2. Assign the type of the location to the node
		node.type = sym.type
コード例 #37
0
 def visit_UnaryOp(self, node):
     # 1. Asegúrese que la operación es compatible con el tipo
     # 2. Ajuste el tipo resultante al mismo del operando
     sym = self.visit(node.left)
     if sym['type'] is str_type:
         error(node.lineno, "No supported operation")
     return sym
コード例 #38
0
 def pro_mul_op(self):
     if self.accept('*'):
         return '*'
     elif self.accept('/'):
         return '/'
     else:
         error(self.token[2], 'Unexpected symbol.', 'mul_op')
コード例 #39
0
ファイル: makeMapsFromMTZs.py プロジェクト: charliebury/RIDL
    def cropMapToAtomTaggedMap(self,
                               densMap='untitled.map'):

        # crop the density map to exact same dimensions
        # as SFALL atom-tagged map

        # run MAPMASK job to crop fft density map to asym unit
        mapmask2 = MAPMASKjob(mapFile1=densMap, outputDir=self.outputDir,
                              runLog=self.runLog)
        success = mapmask2.crop2AsymUnit()
        if not success:
            return False

        # run MAPMASK job to crop fft density map to same
        # grid sampling dimensions as SFALL atom map
        mapmask3 = MAPMASKjob(mapFile1=mapmask2.outputMapFile,
                              mapFile2=self.atomTaggedMap,
                              outputDir=self.outputDir, runLog=self.runLog)
        success = mapmask3.cropMap2Map()
        croppedDensityMap = mapmask3.outputMapFile

        if not success:
            error(text='Failure to successfully crop atom map',
                  log=self.runLog)
        else:
            return croppedDensityMap
コード例 #40
0
ファイル: makeMapsFromMTZs.py プロジェクト: charliebury/RIDL
    def generateNewFOMcolumn(self):

        # run SIGMAA job if required to generate a new FOM weight column

        self.printStepNumber()

        if self.densMapType == '2FOFC':
            mtzLbls_in = self.Mtz2LabelName
            mtzLbls_out = self.Mtz2LabelRename

        else:
            mtzLbls_in = self.Mtz1LabelName
            mtzLbls_out = self.Mtz1LabelName

        sigmaa = SIGMAAjob(inputMtz=self.SIGMAAinputMtz,
                           MtzLabelNameIn=mtzLbls_in,
                           MtzLabelNameOut=mtzLbls_out,
                           RfreeFlag=self.RfreeFlag1,
                           inputPDB=self.inputPDBfile,
                           outputDir=self.outputDir,
                           runLog=self.runLog)
        success = sigmaa.run()
        self.CADinputMtz1 = sigmaa.outputMtz

        if not success:
            error(text='Failure to successfully generate new FOM column',
                  log=self.runLog)
コード例 #41
0
ファイル: makeMapsFromMTZs.py プロジェクト: charliebury/RIDL
    def combineMTZcolumns(self):

        # run CAD to combine necessary columns from input mtz files

        self.printStepNumber()

        cad = CADjob(inputMtz2=self.CADinputMtz2,
                     inputMtz3=self.CADinputMtz3,
                     Mtz2FPlabel=self.Mtz2LabelName,
                     Mtz2SIGFPlabel=self.Mtz2SIGFPlabel,
                     Mtz2LabelName=self.Mtz2LabelName,
                     Mtz3phaseLabel=self.Mtz3phaseLabel,
                     Mtz3FcalcLabel=self.Mtz3FcalcLabel,
                     Mtz2LabelRename=self.Mtz2LabelRename,
                     Mtz3LabelRename=self.Mtz3LabelRename,
                     outputMtz=self.CADoutputMtz,
                     outputDir=self.outputDir,
                     runLog=self.runLog,
                     FOMWeight=self.FOMweight,
                     ignoreSIGFs=self.ignoreSIGFs)

        if self.densMapType != 'HIGHONLY':
            cad.inputMtz1 = self.CADinputMtz1
            cad.Mtz1FPlabel = self.Mtz1LabelName
            cad.Mtz1SIGFPlabel = self.Mtz1SIGFPlabel
            cad.Mtz1LabelRename = self.Mtz1LabelRename
        else:
            cad.ignoreDset1 = True

        success = cad.run()

        if not success:
            error(text='Failure to successfully combine mtz files',
                  log=self.runLog)
コード例 #42
0
ファイル: mpascheck.py プロジェクト: Davesco/mpascal-1
 def visit_UnaryOp(self, node):
   # 1. Asegúrese que la operación es compatible con el tipo
   # 2. Ajuste el tipo resultante al mismo del operando
   self.visit(node.right)
   if not mpaslex.operators[node.op] in node.right.type.un_ops:
     error(node.lineno, "Operación no soportada con este tipo")
   node.type = node.right.type
コード例 #43
0
ファイル: ccp4Job.py プロジェクト: charliebury/RIDL
    def checkJobSuccess(self, runLog):

        # job success checked, based on:
        # (a) the program log file has completed
        # (b) whether output files exist

        fIn = open(self.outputDir+self.outputLogfile, 'r')
        logFinished = False
        for l in fIn.readlines():
            if 'normal termination' in l.lower():
                logFinished = True
                break
        fIn.close()

        if not logFinished:
            error(
                text='{} did not proceed to completion'.format(self.jobName),
                log=runLog)
            return False

        if not os.path.isfile(self.outputFile):
            error(
                text='{} did not proceed to completion'.format(self.jobName),
                log=runLog)
            return False
        else:
            return True
コード例 #44
0
ファイル: exprlex.py プロジェクト: DrOriam/pycompile12
def _replace_escape_codes(t):
    r'''
    *** YOU MUST IMPLEMENT ***
    
    Replace all of the valid escape codes \.. in a string with
    their raw character code equivalents.  
    '''
    newval = []
    ostring = iter(t.value)
    olen = len(t.value)
    for c in ostring:
        if c=='"':
            error("Premature end of string")
        elif c=='\\':
            c1=ostring.next()
            #if c1 not in escapes_not_b:
            if c1 not in escapes:
                error(t.lexer.lineno,"Bad string escape code '%s'" % escape_code)
            else:
                if c1=='n':
                    c='\n'
                elif c1=='r':
                    c='\r'
                elif c1=='t':
                    c='\t'
                elif c1=='\\':
                    c='\\'
                elif c1=='"':
                    c='"'
        newval.append(c)
    else:
        t.value = ''.join(newval)
コード例 #45
0
    def calculateWeights(self,
                         metric='loss'):

        # calculate the normalisation weights here

        # don't run function if no list of atoms included
        if len(self.atomList) == 0:
            print('Need to add list of atoms first')
            return

        # collect the atoms to normalise to for each dataset
        normSet = []
        for a in self.atomList:
            for n in self.normaliseTo:
                if a.atomtype == n[1] and (a.basetype == n[0] or n[0] == ''):
                    normSet.append(a)

        # check if a non empty set of atoms found
        if len(normSet) == 0:
            sys.exit('No suitable atoms found for metric normalisation! ' +
                     '\nCheck they exist')
            error(text='Failed to find the specified set of ' +
                       'atoms to normalise metrics', log=self.logFile)

        # calculate the weighting for each dataset and
        # for each density metric individually here
        vals = [a.densMetric[metric]['Standard']['values'] for a in normSet]
        self.meanweight[metric] = np.nanmean(vals, 0)
        self.stdweight[metric] = np.nanstd(vals, 0)
コード例 #46
0
ファイル: exprcheck.py プロジェクト: amontalenti/compiler
 def visit_AssignmentStatement(self, node):
     if not self.inside_function():
         error(node.lineno, "Cannot assign variable '{}' outside function body".format(node.location.name))
         return
     # 1. Make sure the location of the assignment is defined
     sym = self.environment.lookup(node.location.name)
     if not sym:
         error(node.lineno, "name '{}' not defined".format(node.location.name))
     # 2. Check that assignment is allowed
     self.visit(node.expr)
     if isinstance(sym, VarDeclaration):
         # empty var declaration, so check against the declared type name
         if hasattr(sym, "check_type") and hasattr(node.expr, "check_type"):
             declared_type = sym.check_type
             value_type = node.expr.check_type
             if declared_type != value_type:
                 error(node.lineno, "Cannot assign {} to {}".format(value_type, declared_type))
                 return
     if isinstance(sym, ConstDeclaration):
         error(node.lineno, "Cannot assign to constant {}".format(sym.name))
         return
     # 3. Check that the types match
     if hasattr(node.location, "check_type") and hasattr(node.expr, "check_type"):
         declared_type = node.location.check_type
         value_type = node.expr.check_type
         if declared_type != value_type:
             error(node.lineno, "Cannot assign {} to {}".format(value_type, declared_type))
コード例 #47
0
ファイル: exprcheck.py プロジェクト: thron7/pycompile12
 def visit_UnaryOp(self, node):
     # 1. Make sure that the operation is supported by the type
     # 2. Set the result type to the same as the operand
     self.visit(node.left)
     if not exprlex.operators[node.op] in node.left.type.un_ops:
         error(node.lineno, "Operation not supported with this type")
     self.type = node.left.type
コード例 #48
0
 def visit_VarDeclaration(self,node):
     if not self.inside_function():
         error(node.lineno, "Cannot do variable declaration outside function body")
         return
     if self.environment.look(node.name) is not None:
         error(node.lineno, "Attempted to redefine var '{}', not allowed".format(node.name))
     else :
         p=self.environment.lookup(node.typename.name)
         if isinstance(p,TypeDeclaration) :
             node.expr = p.expr
             node.length = p.length
             node.typename = p.typename
         else :
             if node.length is not None :
                 self.visit(node.length)
             if node.expr is not None :
                 self.visit(node.expr)
         self.visit(node.typename)
         self.environment.add_local(node.name, node)
         if hasattr(node.typename, "check_type"):
             node.check_type = node.typename.check_type
         '''if node.expr is None:
             default = node.check_type.default
             node.expr = Literal(default)
             node.expr.check_type = node.check_type'''
     node.scope_level = self.environment.scope_level()
コード例 #49
0
ファイル: exprcheck.py プロジェクト: amontalenti/compiler
 def visit_FuncCall(self, node):
     if not self.inside_function():
         error(node.lineno, "Cannot call function from outside function body; see main() for entry point")
         return
     sym = self.environment.lookup(node.name)
     if not sym:
         self.environment.print()
         error(node.lineno, "Function name '{}' not found".format(node.name))
         return
     if not isinstance(sym, FuncStatement):
         error(node.lineno, "Tried to call non-function '{}'".format(node.name))
         return
     if len(sym.parameters) != len(node.arguments):
         error(
             node.lineno,
             "Number of arguments for call to function '{}' do not match function parameter declaration on line {}".format(
                 node.name, sym.lineno
             ),
         )
     self.visit(node.arguments)
     argerrors = False
     for arg, parm in zip(node.arguments.arguments, sym.parameters.parameters):
         if arg.check_type != parm.check_type:
             error(
                 node.lineno,
                 "Argument type '{}' does not match parameter type '{}' in function call to '{}'".format(
                     arg.check_type.typename, parm.check_type.typename, node.name
                 ),
             )
             argerrors = True
         if argerrors:
             return
         arg.parm = parm
コード例 #50
0
ファイル: views.py プロジェクト: TimmyKing/Face
def register():
    form = RegisterForm()
    if form.validate_on_submit():
        role = form.role.data
        if role == 'student':
            try:
                Student.objects.get(pk=form.user_id.data)
            except:
                student = Student(student_id=form.user_id.data, name=form.name.data, gender=form.gender.data,
                                  class_name=form.class_name.data, password=form.password.data)
            try:
                student.save()
            except:
                return error('Save Error. User exsit.')
        else:
            try:
                Teacher.objects.get(pk=form.user_id.data)
            except:
                teacher = Teacher(teacher_id=form.user_id.data, name=form.name.data, gender=form.gender.data,
                                  class_name=form.class_name.data, password=form.password.data)
            try:
                teacher.save()
            except:
                return error('Save Error')
        # person = session['user'].student_id

        return redirect(url_for('main.test'))

    else:
        return render_template('register.html', form=form)
コード例 #51
0
 def visit_WhileStatement(self,node):
     global counter
     if not self.inside_function():
         error(node.lineno, "Cannot define a while outside function body")
         return
     if not self.inside_function():
         error(node.lineno, "Cannot use while statement outside function body")
     flag = 1
     if node.label ==  None :
         while self.environment.lookup(counter) is not None :
             counter+=1
         node.label = counter
         counter+=1
     else:
         if self.environment.lookup(node.label) is not None:
             error(node.lineno, "Attempted to redefine label, not allowed".format(node.label))
             flag = 0
         else:
             if node.id!=None and node.label != node.id :
                 error(node.lineno, "Label does not match".format(node.label))
     if flag != 0 :
         self.environment.add_local(node.label, node)
     self.environment.push(node)
     self.visit(node.expr)
     if node.expr != None :
         if node.expr.check_type != BoolType:
             error(node.lineno, "Expression in while statement must evaluate to bool")
     self.visit(node.truebranch)
     self.environment.pop()
コード例 #52
0
ファイル: exprcheck.py プロジェクト: amontalenti/compiler
 def visit_Literal(self, node):
     # Attach an appropriate type to the literal
     valtype = type(node.value)
     check_type = self.typemap.get(valtype, None)
     if check_type is None:
         error(node.lineno, "Using unrecognized type {}".format(valtype))
     node.check_type = check_type
コード例 #53
0
ファイル: exprcheck.py プロジェクト: amontalenti/compiler
 def visit_Location(self, node):
     # 1. Make sure the location is a valid variable or constant value
     sym = self.environment.lookup(node.name)
     if not sym:
         error(node.lineno, "name '{}' not found".format(node.name))
     # 2. Assign the type of the location to the node
     node.check_type = sym.check_type
コード例 #54
0
ファイル: exprcheck.py プロジェクト: amontalenti/compiler
 def visit_Typename(self, node):
     # 1. Make sure the typename is valid and that it's actually a type
     sym = self.environment.lookup(node.name)
     if not isinstance(sym, ExprType):
         error(node.lineno, "{} is not a valid type".format(node.name))
         return
     node.check_type = sym
コード例 #55
0
 def visit_VarExpr(self, node):
     # Associate a type name such as "int" with a Type object
     self.visit(node.name)
     if node.name in self.symbols:
         node.type = self.symbols[node.name].type
     else:
         node.type = None
         error(node.lineno, f"Name '{node.name}' was not defined")
コード例 #56
0
ファイル: typecheck.py プロジェクト: renjiec/blaze-core
 def visit_WhileStatement(self, node):
     if self.scope is GLOBAL:
         error(node.lineno, "Syntax Error: while loop outside of function")
     else:
         self.visit(node.condition)
         if node.condition.type != btypes.bool_type:
             error(node.lineno, "Value Error: Conditional expression must evaluate to bool")
         self.visit(node.statements)
コード例 #57
0
ファイル: typecheck.py プロジェクト: renjiec/blaze-core
    def visit_Range(self, node):
        self.visit(node.start)
        self.visit(node.stop)

        if node.start.type != btypes.int_type:
            error(node.lineno, "Type Error: Bounds to range statement must be integers")
        if node.stop.type != btypes.int_type:
            error(node.lineno, "Type Error: Bounds to range statement must be integers")
コード例 #58
0
ファイル: conprint.py プロジェクト: Siyet/favr_converter
def get_sign_list():
    slp = os.path.join(CONPRINT_PATH, 'signatures.json')
    if os.path.exists(slp):
        with open(slp) as data_file:
            data = json.load(data_file)
            return data['signatures']
    else:
        error(99)