Calculator.py 文件源码

python
阅读 37 收藏 0 点赞 0 评论 0

项目:PyValentina 作者: FabriceSalvaire 项目源码 文件源码
def _compile(self):

        expression = self._expression
        self._logger.info("expression '{}'".format(expression))

        # Python don't accept identifier starting with @
        # https://docs.python.org/3.5/reference/lexical_analysis.html#identifiers
        if '@' in expression:
            custom_measurements = []
            start = 0
            while True:
                name, start = self._find_name('@', start)
                if name is None:
                    break
                else:
                    custom_measurements.append(name)
            for measurement in custom_measurements:
                expression = self.expression.replace(measurement, self._calculator.measurements[measurement].name)

        functions = []
        for function in (
                'Angle1Spl_',
                'Angle2Spl_',
                'AngleLine_',
                'CurrentLength',
                'C1LengthSpl_',
                'C2LengthSpl_',
                'Line_',
                'Spl_',
        ):
            start = 0
            while True:
                name, start = self._find_name(function, start)
                if name is None:
                    break
                else:
                    functions.append(name)
        # self._logger.info('Functions ' + str(functions))
        for function_call in functions:
            parts = function_call.split('_')
            function = parts[0]
            args = parts[1:]
            pythonised_function = '__calculator__._function_' + function + '(' + ', '.join(["'{}'".format(x) for x in args]) + ')'
            # self._logger.info('Function {} {} -> {}'.format(function, args, pythonised_function))
            expression = expression.replace(function_call, pythonised_function)

        self._logger.info("Pythonised expression '{}'".format(expression))

        # Fixme: What is the (supported) grammar ?
        # http://beltoforion.de/article.php?a=muparser
        # http://beltoforion.de/article.php?a=muparserx
        self._ast = ast.parse(expression, mode='eval')
        node_visitor = NodeVisitor(self._calculator)
        node_visitor.generic_visit(self._ast)
        self._dependencies = node_visitor.dependencies
        self._code = compile(self._ast, '<string>', mode='eval')
        # print('AST', astunparse.dump(self._ast))
        # print('AST -> Python', astunparse.unparse(self._ast))
        ## print('AST -> Python', astor.to_source(self._ast.body))

    ##############################################
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号