Пример #1
0
 def test_defining_lambda_with_error(self):
     """Tests that the lambda body is not being evaluated when the lambda
     is evaluated or defined. (It should first be evaluated when the function
     is later invoced.)"""
 
     ast = parse("""
         (define fn-with-error
             (lambda (x y)
                 (function body that would never work)))
     """)
     evaluate(ast, Environment())
Пример #2
0
 def test_parse_comments(self):
     program = """
     ;; this first line is a comment
     (define variable
         ; here is another comment
         (if #t 
             42 ; inline comment!
             (something else)))
     """
     expected_ast = ['define', 'variable', ['if', True, 42, ['something', 'else']]]
     assert_equals(expected_ast, parse(program))
Пример #3
0
def query_bc(kb, sentence):
    try:
        query_ask = ip.parse(sentence)
        answer = kb.ask(kb, query_ask)
        if answer is not None:
            if answer[0] != {}:
                print(answer)
            print("true.")
        else:
            print("false.")
    except Exception as e:
        print("Invalid query: {}".format(e))
Пример #4
0
        def run():
            self.textPanel.textBox.SetEditable(False)

            file_contents: str = self.textPanel.textBox.GetValue()
            state = interpreter.parse(self.fileName, file_contents, stackSize,
                                      startLabel)
            if state is not None:
                self.textPanel.setAddresses(state)
                wx.PostEvent(
                    self, UpdateGUIEvent(lambda: self.sidePanel.update(state)))

                lines = file_contents.split('\n')

                while not self.stopFlag:
                    node: nodes.InstructionNode = state.getInstructionFromMem(
                        state.getReg("PC"))
                    if node.line in breakpoints:
                        # breakpoint found - save state and enable the single-step and resume tools
                        self.debugState = state
                        self.runThread = None

                        wx.PostEvent(
                            self,
                            UpdateGUIEvent(lambda: [
                                self.sidePanel.update(state),
                                self.textPanel.markLine(node.line),
                                self.enableDebugTools(True)
                            ]))

                        return
                    state, success = interpreter.executeInstruction(
                        node, state, self.fileName, lines)
                    if not success:
                        break

                # program has exited
                wx.PostEvent(
                    self,
                    UpdateGUIEvent(
                        lambda:
                        [self.sidePanel.update(state),
                         self.resetTools()]))
            else:
                wx.PostEvent(self, UpdateGUIEvent(lambda: self.resetTools()))

            self.runThread = None
            self.stopFlag = False

            self.textPanel.textBox.MarkerDeleteAll(MARK_CURRENT_LINE)
            self.textPanel.textBox.SetEditable(True)
Пример #5
0
    def test_begin_form(self):
        """Testing evaluating expressions in sequence with the begin 
        special form"""

        env = Environment()
        result = evaluate(parse("""
            (begin 
                (define foo 1)
                (define bar 2)
                foo)
        """), env)

        assert_equals(1, result)
        assert_equals(Environment({"foo": 1, "bar": 2}), env)
Пример #6
0
def main():
    print('enter height width number_bombs')

    tokens = input().split(' ')
    tokens = [int(x) for x in tokens]
    HEIGHT, WIDTH, NUM_BOMBS = tokens

    game_state = gen.generation(HEIGHT, WIDTH, NUM_BOMBS)
    gen.render(game_state)
    # gen.render(game_state, show_bombs=True) # for debugging

    while True:
        print('input a command')
        command = input()
        inter.parse(game_state, command)
        gen.render(game_state)

        if ck.won(game_state):
            print('Congratulations! You won!')
            break
        if ck.lost(game_state):
            gen.render(game_state, show_bombs=True)
            print('Feels bad man, you lost!')
            break
Пример #7
0
def main():
    parser = argparse.ArgumentParser(description='pyconfig is a tool to generate xcconfig files from a simple DSL')
    parser.add_argument(
        'file', 
        help='Path to the pyconfig file to use to generate a xcconfig file',
        type=argparse.FileType('r')
    )
    parser.add_argument(
        '-o', '--output', 
        metavar='file', 
        help='Path to output xcconfig file to write', 
        type=openOutputFileToWrite
    )
    parser.add_argument(
        '-l', '--lint', 
        help='Validate the syntax of a pyconfig file', 
        action='store_true'
    )
    parser.add_argument(
        '-s', '--scheme', 
        metavar='name', 
        help='Optional argument to supply the scheme name'
    )
    parser.add_argument(
        '-v', '--version',
        help='Displays the version information',
        action='version',
        version=PYCONFIG_VERSION
    )
    args = parser.parse_args()
    	
    pyconfig_contents = args.file.read()
    
    parsed_contents = interpreter.parse(args.lint, pyconfig_contents)
    
    if args.lint == False:
        serializer.writeFile(parsed_contents, args.output, args.scheme)
    	
    args.file.close()
    	
    if args.output != None:
        args.output.close()
Пример #8
0
    def test_calling_function_recursively(self):
        """Tests that a named function is included in the environment
        where it is evaluated"""

        # Starting env out with some "standard functions" this time
        import operator
        env = Environment({
            '-': operator.sub, 
            '>': operator.gt
        })
        
        # Meaningless (albeit recursive) function
        program = """
            (define fn 
                (lambda (x) 
                    (if (> x 0) 
                        (fn (- x 1))
                        1000)))
        """
        evaluate(parse(program), env)
        assert_equals(1000, evaluate(["fn", 10], env))
Пример #9
0
    def create(self, filepath):
        f = open(filepath, 'r')
        for line in f.readlines():
            line = line.strip()

            if line.startswith('%') or len(line) == 0:
                # TODO: ^: only support comment is first char of line
                continue

            result = ip.parse(line)

            if isinstance(result, ip.Rule):
                self.add_rule(result)
            elif isinstance(result, ip.Functor):
                if result.is_fact():
                    self.add_fact(result)
                else:
                    raise SyntaxError('Fact cannot contain variable')
            elif isinstance(result, ip.Atom):
                self.add_fact(result)
            else:
                raise KBError("Unknow parsed")
Пример #10
0
        def run():
            self.textPanel.textBox.SetEditable(False)

            file_contents: str = self.textPanel.textBox.GetValue()
            state = interpreter.parse(self.fileName, file_contents, stackSize,
                                      startLabel)

            if state is not None:
                self.textPanel.setAddresses(state)
                wx.PostEvent(
                    self, UpdateGUIEvent(lambda: self.sidePanel.update(state)))

                lines = file_contents.split('\n')

                while True:
                    if self.stopFlag:
                        break
                    state, success = interpreter.executeInstruction(
                        state.getInstructionFromMem(state.getReg("PC")), state,
                        self.fileName, lines)
                    if not success:
                        break

                # program has exited
                wx.PostEvent(
                    self,
                    UpdateGUIEvent(
                        lambda:
                        [self.sidePanel.update(state),
                         self.resetTools()]))
            else:
                wx.PostEvent(self, UpdateGUIEvent(lambda: self.resetTools()))

            self.runThread = None
            self.stopFlag = False

            self.textPanel.textBox.MarkerDeleteAll(MARK_CURRENT_LINE)
            self.textPanel.textBox.SetEditable(True)
Пример #11
0
def query_fc(kb, sentence):
    try:
        query_ask = ip.parse(sentence)
        answer_generator = kb.ask(kb, query_ask)
        try:
            while True:
                answer = next(answer_generator)
                if answer is not None:
                    if len(answer.keys()) == 0:
                        print("true.")
                        break
                    else:
                        print(answer)
                        if input('Enter ; to continue: ') != ';':
                            break
                else:
                    print("false.")

        except StopIteration:
            print("false.")

    except Exception as e:
        print("Invalid query: {}".format(e))
Пример #12
0
def check(prog, ins, outs):
    mins = ins
    ins = list(ins)
    nout = b""

    def puts(s):
        nonlocal nout
        nout += s

    def getc():
        nonlocal ins
        if len(ins) > 0:
            res = ins[0]
            ins = ins[1:]
            return res
        else:
            return -1

    def ungetc(c):
        nonlocal ins
        ins = [c] + ins

    interpreter.puts = puts
    interpreter.getc = getc
    interpreter.ungetc = ungetc

    program, rem = interpreter.parse(interpreter.tokenize(prog))
    if len(rem) != 0:
        eexit('parse failure: token remains', rem)
    interpreter.interpret(program)

    if nout != outs:
        sys.stderr.buffer.write(
            b'test failed\nprogram: %s\ninput: %s\noutput: %s\nexpect: %s\n' %
            (bytes(map(ord, prog)), mins, nout, outs))
        exit(-1)
Пример #13
0
from functools import reduce

import interpreter

fileName = "decompress.asm"
useGUI = True
stackSize = 1024
startLabel = "_start"


if useGUI:
    import visualizer

    visualizer.startLabel = startLabel
    visualizer.stackSize = stackSize

    visualizer.app.MainLoop()
else:
    file = open(fileName, "r")
    lines = file.readlines()

    file_contents: str = reduce(lambda X, Y: X + Y, lines)

    state = interpreter.parse(fileName, file_contents, stackSize, startLabel)
    if state is None:
        exit(-1)
    interpreter.runProgram(state, fileName, lines)
Пример #14
0
 def test_parse_on_tested_list(self):
     program = '(foo (bar x y) (baz x))'
     ast = ['foo', 
             ['bar', 'x', 'y'], 
             ['baz', 'x']]
     assert_equals(ast, parse(program))
Пример #15
0
 def test_parse_exception_missing_paren(self):
     with assert_raises_regexp(LispSyntaxError, 'Unexpected EOF'):
         parse('(foo (bar x y)')
Пример #16
0
 def test_parse_exception_extra_paren(self):
     with assert_raises_regexp(LispSyntaxError, 'Expected EOF'):
         parse('(foo (bar x y)))')
Пример #17
0
 def testParsingComplexAddition(self):
     result = parse('+ 1 + + 2 3 4'.split())
     expected = [add, 1, add, add, 2, 3, 4]
     self.assertEqual(result, expected)
Пример #18
0
 def testParsingSimpleAddition(self):
     result = parse(['+', '1', '2'])
     expected = [add, 1, 2]
     self.assertEqual(result, expected)
Пример #19
0
#!/usr/bin/python3

import sys
import os

with open(sys.argv[1]) as file:
	position, pointer = map(int, file)

position = 1

if len(sys.argv) == 4:
	import interpreter

	with open(sys.argv[3]) as file:
		instructions, loops, IO = interpreter.parse(file, os.stat(sys.argv[3]).st_size)

	with open(sys.argv[2], "r+b") as file:
		posts = []

		for i in range(pointer - 43, -1, -48):
			file.seek(i)
			chunk = file.read(48)

			if chunk[-9: -6] == b"\x00\x00\x00":
				break

			posts.append(chunk)

		posts.reverse()

		memory = bytearray(os.stat(sys.argv[2]).st_size)
Пример #20
0
 def test_parse_with_types(self):
     program = '(if #f (* 42 x) 100)'
     ast = ['if', False, ['*', 42, 'x'], 100]
     assert_equals(ast, parse(program))
Пример #21
0
 def test_parse_quote_tick_on_symbol(self):
     assert_equals(["quote", "foo"], parse("'foo"))
Пример #22
0
 def test_parse_on_simple_list(self):
     program = '(foo bar)'
     assert_equals(['foo', 'bar'], parse(program))
Пример #23
0
 def test_parse_quote_tick_on_list(self):
     assert_equals(["quote", ["foo", "bar"]], parse("'(foo bar)"))
     assert_equals(["quote", []], parse("'()"))
Пример #24
0
    argument_parser.add_argument("--no-seccomp", "-n", action="store_true")
    argument_parser.add_argument("--dumpable", "-d", action="store_true")
    argument_parser.add_argument("code", type=str)

    arguments = argument_parser.parse_args()

    if arguments.maximum_code_length < 0:
        raise Exception("Invalid maximum code length")

    if arguments.maximum_loop_depth < 0:
        raise Exception("Invalid maximum loop depth")

    if arguments.maximum_io_instructions < 0:
        raise Exception("Invalid maximum IO instructions count")

    if arguments.memory_length < 1:
        raise Exception("Invalid memory length")

    import interpreter

    with open(arguments.code, "r") as file:
        instructions, loops, IOs = interpreter.parse(
            file, arguments.maximum_code_length, arguments.maximum_loop_depth)

    sys.stdout.write(
        translate(instructions, arguments.maximum_io_instructions,
                  arguments.memory_length, arguments.dumpable) +
        (main_no_seccomp_template if arguments.no_seccomp else main_template
         ).substitute(initialize=initialize_template.substitute() if arguments.
                      dumpable else ""))
Пример #25
0
wakeup = True

def handler(signum, stack):
    global wakeup
    wakeup = True
    
def interative_hook():
    environment.current_bindings.dump()
    sys.stdout.write('END\n')
    sys.stdout.flush()
    sys.stderr.write('# ' + str(environment.lastlineno) + '\n')
    sys.stderr.write('END\n')
    sys.stderr.flush()
    global wakeup
    wakeup = False
    while not wakeup:
        time.sleep(5)

if __name__ == '__main__':
    environment.tracehook = interative_hook
    signal.signal(signal.SIGUSR1, handler)
    
    interpret()
    parse()
    
    sys.stdout.write('TERMINATED\n')
    sys.stdout.flush()
    sys.stderr.write('TERMINATED\n')
    sys.stderr.flush()