示例#1
0
def code_trace(code):
    statements = Parser(Lexer(code).lex()).parse()
    output = StringIO()
    with redirect_stdout(output):
        Interpreter().interpret(statements)
    output_lines = output.getvalue().split('\n')
    return list(filter(lambda s: len(s) > 0, output_lines))
示例#2
0
def unitary_test_template(code: str, unitary_expected: np.array):
    """Checks that the circuit produced by a code snippet matches a template
    numerically. The template is given as a unitary matrix."""
    interpreter = Interpreter()
    statements = Parser(Lexer(code).lex()).parse()
    interpreter.interpret(statements)
    circuit = interpreter.circuit.to_cirq()
    unitary = cirq.unitary(circuit)
    assert np.allclose(unitary, unitary_expected)
示例#3
0
        def loadAssets(self, path_to_folder=Globals.AssetsRootPath):
            # This dictionary will hold the contents of asset files in the format:
            #   key = the files path, e.g. "assets/readme.txt"
            #   value = the conents of the file
            assets = {}

            # Go through each file in the specified dir and add contents to the dictionary
            for root, subdirs, files in os.walk(path_to_folder):
                for file_name in files:
                    file_path = os.path.join(root,file_name)
                    # Normalize the given path
                    norm_path = os.path.normcase(os.path.normpath(file_path))
                    if '.DS_Store' in norm_path:
                        continue    # ignore .DS_Store
                    with open(norm_path) as f:
                        assets[norm_path] = f.read()

            # Do parsing of any custom scripts and yaml
            parser = Parser()  # instantiate parser on the fly
            for path in assets:
                if path[-len('.ignore'):] == '.ignore':
                    continue
                if os.path.normcase(os.path.normpath('assets/scripts')) in path:
                    # replace string with parsed (string, BodyNode)[]
                    assets[path] = parser.parseScript(assets[path])
                elif os.path.normcase(os.path.normpath('assets/config')) in path:
                    # replace string with parsed Python dict
                    assets[path] = yaml.load(assets[path])

            self.assets = assets

            # construct reverse item mapping
            itemsConfig = self.getConfig(Globals.ItemsConfigPath)
            for item in itemsConfig:
                self.reverseItem[itemsConfig[item]['name']] = item

            # construct reverse room mapping
            areasConfig = self.getConfig(Globals.AreasConfigPath)
            for area in areasConfig:
                self.reverseRoom[area] = {}
                roomsConfig = self.getConfig(areasConfig[area]['roomsConfig'])
                for room in roomsConfig:
                    self.reverseRoom[area][roomsConfig[room]['name']] = room
示例#4
0
def stmt_test_template(code, trace_expected, exception=None):
    """
    Here 'exception' is either None, or an expected exception type.
    """
    statements = Parser(Lexer(code).lex()).parse()
    output = StringIO()
    with redirect_stdout(output):
        if exception is None:
            Interpreter().interpret(statements)
        else:
            with pytest.raises(exception):
                Interpreter().interpret(statements)
    trace_actual = output.getvalue().split()
    assert trace_actual == trace_expected
示例#5
0
class Program:

    def __init__(self, source: str):
        lexer = Lexer(source)
        tokens = lexer.lex()
        if (errors := lexer.errors):
            for err in errors:
                # TODO this is temporarily here so I can see what’s in `errors`
                breakpoint()
        parser = Parser(tokens)
        #
        # parse the line as a statement
        self.stmts = parser.parse()
        if not self.stmts:
            for err in parser.errors:
                # TODO this is temporarily here so I can see what’s in `errors`
                breakpoint()
示例#6
0
def circuit_test_template(code: str,
                          gates_expected: List[Tuple[type, List[int]]],
                          exception=None):
    """Checks that the circuit produced by a code snippet matches a template
    exactly. The template is given"""
    interpreter = Interpreter()
    statements = Parser(Lexer(code).lex()).parse()
    if exception is None:
        interpreter.interpret(statements)
    else:
        with pytest.raises(exception):
            Interpreter().interpret(statements)
    gates = interpreter.circuit.gates
    assert len(gates) == len(gates_expected)
    for (gate, (type_expected, qubits_expected)) in zip(gates, gates_expected):
        assert type(gate) == type_expected
        assert list(gate.qubits) == qubits_expected
示例#7
0
        def loadAssets(self):
            # if assets already in memory do not reload
            if self.isLoaded:
                return

            # set root to assets for later reference
            self.root_path = Globals.AssetsRootPath

            # This dictionary will hold the contents of asset files in the format:
            #   key = the files path, e.g. "assets/readme.txt"
            #   value = the conents of the file
            assets = {}

            # Returns whether all files can read and parse successfully
            success_flag = True

            # recognized filename extensions
            whitelist_ext = ['.txt', '.wtxt', '.yml']
            # Go through each file in the specified dir and add contents to the dictionary
            for root, subdirs, files in os.walk(self.root_path):
                for file_name in files:
                    try:
                        # Normalize the given path
                        norm_path = joinAndNorm(root, file_name)
                        # Check that filename ends with recognized extension
                        ext_not_valid = True
                        for ext in whitelist_ext:
                            if len(norm_path) >= len(
                                    ext) and norm_path[-len(ext):] == ext:
                                ext_not_valid = False
                                break
                        if ext_not_valid:
                            continue
                        # Store file text into dictionary
                        with codecs.open(norm_path, "r", "utf-8") as f:
                            assets[norm_path] = f.read().replace(
                                '\r\n', '\n').replace('\r', '\n')
                    except:
                        success_flag = False

            # Do parsing of any custom scripts and yaml
            parser = Parser()  # instantiate parser on the fly
            for path in assets:
                try:
                    if joinAndNorm(self.root_path, 'scripts') in path:
                        if 'fragments' in path:
                            # replace string with parsed BodyNode
                            assets[path] = parser.parseScriptFragment(
                                assets[path])
                        else:
                            # replace string with parsed (string, BodyNode)[]
                            assets[path] = parser.parseScript(assets[path])
                    elif joinAndNorm(self.root_path, 'config') in path:
                        # replace string with parsed Python dict
                        assets[path] = yaml.load(assets[path])
                    elif joinAndNorm(self.root_path, 'maps') in path:
                        # replace string with split string
                        assets[path] = assets[path].split('\n')
                except:
                    success_flag = False
                    if Globals.IsDev:
                        print(path)
                        traceback.print_exc()

            self.assets = assets

            # construct reverse item mapping
            itemsConfig = self.getConfig(Globals.ItemsConfigPath)
            for item in itemsConfig:
                self.reverseItem[itemsConfig[item]['name'].lower()] = item

            # construct reverse room mapping
            areasConfig = self.getConfig(Globals.AreasConfigPath)
            for area in areasConfig:
                self.reverseRoom[area] = {}
                roomsConfig = self.getConfig(areasConfig[area]['roomsConfig'])
                for room in roomsConfig:
                    self.reverseRoom[area][roomsConfig[room]
                                           ['name'].lower()] = room

            self.isLoaded = True
            return success_flag
示例#8
0
                    if len(line_args) == 1:
                        breakpoint()
                    else:
                        env_values = self.interpreter.environment.values
                        values = [env_values[name] for name in line_args[1:]]
                        print(*values)
                    continue

                # now, eval the line
                lexer = Lexer(line)
                tokens = lexer.lex()
                if (errors := lexer.errors):
                    for err in errors:
                        pprint_lex_error(err)
                    continue
                parser = Parser(tokens)
                # parse the line as a statement
                stmt = parser.declaration()
                if not stmt:
                    for err in parser.errors:
                        pprint_parse_error(err)
                    continue
                self.interpreter.execute(stmt)

            except CavyRuntimeError as err:
                print(err)

            except KeyboardInterrupt:
                # This exception must be handled separately, as it should only
                # quit the repl. raise it to the very top.
                raise KeyboardInterrupt
示例#9
0
def code_to_s_expr(code):
    return s_expr(Parser(Lexer(code).lex()).expression())
示例#10
0
def interpret_script(script_path: str):
    with open(script_path, 'r') as f:
        script = f.read()
    tokens = Lexer(script).lex()
    statements = Parser(tokens).parse()
    Interpreter().interpret(statements)
示例#11
0
def expr_test_template(code, value_expected):
    """Generates a test case comparing the AST produced by the parser with a
    hand-written S-expression.
    """
    ast = Parser(Lexer(code).lex()).expression()
    assert Interpreter().evaluate(ast) == value_expected