Esempio n. 1
0
def main():

    if len(sys.argv) != 3:
        print('EXPECTING AS ARGV: SOURCE_CODE DATATESTSET ')
        exit()
    text_source_original = open(sys.argv[1], 'r').read()
    text_datatestset = open(sys.argv[2], 'r').read()

    dts = DatatestSet(text_datatestset)
    dts.parse()
    i = 1
    visited = []
    for dt in dts.datatests:
        """ Evaluate program for each datatest """
        print('====================================')
        print('-------Datatest ' + str(i) + '--------')
        print('====================================')
        """ Add assigments to program """
        dt.parse()
        text_source = dt.ini_source + text_source_original
        print('/------- Evaluating with initial assigments:  -------/ ')
        print(dt.ini_source)
        """ Now Interpret program """
        lexer = Lexer(text_source)
        parser = Parser(lexer)
        interpreter = Interpreter(parser)
        interpreter.interpret()
        print('/------- Labels ASSIGN visited -------/ ')
        i_visited = [
            l.value for l in interpreter.visited if l.type == 'ASSIGN'
        ]
        print(i_visited)
        visited = set(list(visited) + i_visited)
        print('/------- Variables final evaluation -------/ ')
        for k, v in sorted(interpreter.GLOBAL_SCOPE.items()):
            print('%s = %s' % (k, v))
        i += 1
    print('====================================')
    print('------- Result of datatest set (jeu de donnee) --------')
    print('====================================')
    print('/------- All labels ASSIGN-------/')
    assigns_label = [
        l.value for l in interpreter.parser.labels if l.type == 'ASSIGN'
    ]
    print(assigns_label)
    print('/------- Labels ASSIGN not visited -------/ ')
    not_visited = [
        u.value for u in interpreter.parser.labels
        if u.value not in visited and u.type == 'ASSIGN'
    ]
    print(not_visited)
    if not_visited == []:
        print()
        print('>> Critere TA TRUE')
    else:
        print()
        print('>> Critere TA FALSE')
    coverage_rate = round(1 - len(not_visited) / len(assigns_label), 2) * 100
    print('>> Taux de couverture : {}%'.format(coverage_rate))
Esempio n. 2
0
 def __init__(self, cfgparser):
     self.cfgparser = cfgparser
     self.cfg = cfgparser.cfg
     self.node_labels = nx.get_node_attributes(self.cfg, 'label')
     self.edge_labels = nx.get_edge_attributes(self.cfg, 'label')
     lexer = Lexer(" ")
     parser = Parser(lexer)
     self.interpreter = Interpreter(parser)
     self.visited = []
Esempio n. 3
0
    def test_empty_call(self):
        canvas_mock = {'reset': MagicMock()}

        script = """
                   reset()
                """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)
        canvas_mock['reset'].assert_called_once()
Esempio n. 4
0
    def test_native_call(self):
        canvas_mock = {'fw': MagicMock()}

        script = """
                   fw(100)
                """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)
        canvas_mock['fw'].assert_called_with(100)

        pass
Esempio n. 5
0
    def test_learn_call2(self):
        canvas_mock = {'reset': MagicMock(), 'fw': MagicMock()}
        script = """
                    reset()
            learn koch $a, $i {            
                fw($a)    
            }
            
            koch(50, 2)
        """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)
        canvas_mock['fw'].assert_called_with(50)
        canvas_mock['reset'].assert_called_once()
Esempio n. 6
0
    def test_param_passing(self):
        canvas_mock = {
            'print': MagicMock(),
        }
        script = """
                            
                learn koch $a, $i {            
                    print($a)    
                }

                koch(50, 2)
                """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)
        canvas_mock['print'].assert_called_with(50)
Esempio n. 7
0
    def test_loop(self):
        mock = MagicMock()

        canvas_mock = {'print': mock}

        script = """
            $i = 0
            while $i < 5 {
                $i = $i + 1
            }
            print($i)
        """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)
        mock.assert_called_with(5)
Esempio n. 8
0
    def test_learn_call(self):
        canvas_mock = {'print': MagicMock(), 'fw': MagicMock()}

        script = """
            learn add $a, $b {
                return $a + $b                  
            }

            $a = 1
            $b = 2
            print(add($a, $b))
            fw(100)
        """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)
        # print(interpreter.memory)
        canvas_mock['print'].assert_called_with(3)
        canvas_mock['fw'].assert_called_with(100)
Esempio n. 9
0
    def test_recursion(self):
        canvas_mock = {'print': MagicMock()}

        script = """
                learn fac $i {
                    if $i < 2 {
                        return 1
                    }
                    return $i * fac($i - 1)
                }
                
                $v = fac(7)
                print($v)
                """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)
        canvas_mock['print'].assert_called_with(5040)
        pass
Esempio n. 10
0
    def test_branching(self):
        mock = MagicMock()

        canvas_mock = {'print': mock}

        script = """
            $a = 4
            if $a < 4 {
                $a = 9
            } elif $a < 5 {
                $a = 10
            } else {
                $a = 11
            }
            
            print($a)
        """

        interpreter = Interpreter(canvas_mock)
        interpreter.start(script)

        mock.assert_called_with(10)
Esempio n. 11
0
 def findCode(this):
     sr = ScriptReader()
     #Percorre a lista de scripts
     for s in sr.getScripts():
         Interpreter(s.script)
Esempio n. 12
0
def run(event):
    interpreter = Interpreter(canvas.library)
    interpreter.start(editor.get_text())
    pass
Esempio n. 13
0
import ply.yacc as yacc
from Cparser import Cparser
# import TreePrinter    # -- Parser --
from interpreter.Interpreter import Interpreter
from semantics.TypeChecker import TypeChecker
# from interpreter.Interpreter import Interpreter

if __name__ == '__main__':
    try:
        filename = sys.argv[1] if len(sys.argv) > 1 else "example.txt"
        file = open(filename, "r")
    except IOError:
        print("Cannot open {0} file".format(filename))
        sys.exit(0)

    # -- Parser --
    Cparser = Cparser()
    parser = yacc.yacc(module=Cparser)
    text = file.read()
    ast = parser.parse(text, lexer=Cparser.scanner)
    #  print(ast)

    # -- Type Checker --
    typeChecker = TypeChecker()
    if ast is not None:
        typeChecker.visit(ast)
        for err in typeChecker.errors:
            print(err)
        if len(typeChecker.errors) == 0:
            ast.accept(Interpreter())
Esempio n. 14
0
class CfgInterpreter:

    """
    Interpret a CFG with more general interpreter interpreter.Interpreter
    Visit all nodes
    Show new attributes of data
    """
    def __init__(self, cfgparser):
        self.cfgparser = cfgparser
        self.cfg = cfgparser.cfg
        self.node_labels = nx.get_node_attributes(self.cfg, 'label')
        self.edge_labels = nx.get_edge_attributes(self.cfg, 'label')
        lexer = Lexer(" ")
        parser = Parser(lexer)
        self.interpreter = Interpreter(parser)
        self.visited = []

    def parseCondition(self, code):
        """
        Parse code to get AST nodes
        :param code (ex: ' X < 48 ')
        :return: condition_node
        """
        self.interpreter.parser.lexer.__init__(code)
        self.interpreter.parser.current_token = \
            self.interpreter.parser.lexer.get_next_token()
        return self.interpreter.parser.condition()

    def parseAssigments(self, code):
        """
        Parse code to get AST nodes
        :param code: (ex: ' X = 42 ; Y = X +3 ;')
        :return: list of assigment_node
        """
        self.interpreter.parser.lexer.__init__(code)
        self.interpreter.parser.current_token = \
            self.interpreter.parser.lexer.get_next_token()
        return self.interpreter.parser.statement_list()

    def interpretCondition(self, code):
        """
        Interpret a condition based on code
        :param code: code source (grammar: "[!] condition")
        :return: True | False (evaluation)
        """
        if "!" in code :
            code = code.replace('!', '')
            condition_node = self.parseCondition(code)
            return not self.interpreter.visit(condition_node)
        else:
            condition_node = self.parseCondition(code)
            return self.interpreter.visit(condition_node)

    def interpretAssigments(self, code):
        """
        Interpret an assigment based on code
        :param code: code source (grammer: "statements_list")
        :return: None
        """
        assigments_list = self.parseAssigments(code)
        for statement in assigments_list:
            self.interpreter.visit(statement)
        # print(self.interpreter.GLOBAL_SCOPE)

    def getPaths(self, k):
        """
        Interpret the full CFG
        """
        to_visit = deque()  # next_nodes is a stack of tuples (node, distance of node from START)
        to_visit.append((self.getSourceNode(), 0))

        # Holding current valid path
        local_path = list()

        while to_visit:
            node, node_k = to_visit.pop()
            local_path = local_path[:node_k] + [node]
            if local_path[-1] == self.getTargetNode():
                # we touched the last node
                yield local_path
            elif node_k + 1 <= k:
                succ = list(self.cfg.successors(node))
                if node in self.cfgparser.labelsIf :
                    succ.reverse()
                for s in succ:
                    to_visit.append((s, node_k + 1))

    def getSourceNode(self):
        for n, nbrsdict in self.cfg.adjacency():
            predecessors = [p for p in self.cfg.predecessors(n)]
            if not predecessors :
                # source node is node without predecessors
                return n

    def getTargetNode(self):
         for n, nbrsdict in self.cfg.adjacency():
            successors = [s for s in self.cfg.successors(n)]
            if not successors :
                # target node is node without successors
                return n

    def interpretCfgForIWhile(self):
        """
        :return dict with keys while_label and value: [iter, max]
        """
        while_dict = {}
        target_node = self.getTargetNode()
        current_node = self.getSourceNode()
        self.visited.append(current_node)
        while current_node != target_node:
            #print(current_node)
            # see if there is actually a decision to take when node is (if|while)
            if current_node in self.cfgparser.labelsIf or \
                    current_node in self.cfgparser.labelsWhile:
                decision_node = current_node
                succ = [s for s in self.cfg.successors(current_node)]
                # Modified part
                if current_node in self.cfgparser.labelsWhile:
                    if current_node not in while_dict.keys():
                        while_dict[current_node] = [0, 0]
                    else:
                        while_dict[current_node][0] += 1
                        if while_dict[current_node][0] > while_dict[current_node][1]:
                            while_dict[current_node][1] = while_dict[current_node][0]
                    # get the node executed when cond is not true for while anymore
                node_to_exit = max(succ)
                for s in succ:
                    label = self.cfg.edges[decision_node, s]['label']
                    if self.interpretCondition(label):
                        # rebooting compteur for node
                        if s == node_to_exit and current_node in self.cfgparser.labelsWhile:
                            while_dict[current_node][0] = 0
                        current_node = s
            # else the edge represents an assigment
            # however if the assigment has a while as successor, it means there is
            # a condition to evaluate
            elif current_node in self.cfgparser.labelsAssigns:
                succ = [s for s in self.cfg.successors(current_node)]
                if len(succ) == 1:
                    label = self.cfg.edges[current_node, succ[0]]['label']
                    self.interpretAssigments(label)
                    current_node = succ[0]
            # else finally the node must BE the empty label with no successfors
            else:
                succ = [s for s in self.cfg.successors(current_node)]
                if len(succ) == 0:
                    current_node = target_node
                else:
                    raise Exception('Target node could not be reached')
            self.visited.append(current_node)
        return while_dict

    def interpretCfg(self):
        """
        Interpret the full CFG
        """
        target_node = self.getTargetNode()
        current_node = self.getSourceNode()
        self.visited.append(current_node)
        while current_node != target_node:
            # see if there is actually a decision to take when node is (if|while)
            if current_node in self.cfgparser.labelsIf or \
               current_node in self.cfgparser.labelsWhile :
                decision_node = current_node
                succ = [s for s in self.cfg.successors(current_node)]
                for s in succ:
                    label = self.cfg.edges[decision_node, s]['label']
                    if self.interpretCondition(label):
                        current_node = s
            # else the edge represents an assigment
            # however if the assigment has a while as successor, it means there is
            # a condition to evaluate
            elif current_node in self.cfgparser.labelsAssigns:
                succ = [s for s in self.cfg.successors(current_node)]
                if len(succ) == 1:
                    label = self.cfg.edges[current_node, succ[0]]['label']
                    self.interpretAssigments(label)
                    current_node = succ[0]
            # else finally the node must BE the empty label with no successfors
            else:
                succ = [s for s in self.cfg.successors(current_node)]
                if len(succ) == 0 :
                    current_node = target_node
                else:
                    raise Exception('Target node could not be reached')
            self.visited.append(current_node)