def setUp(self):
     self.add = SignatureParser("add(real, vector) => vector")
     self.int_var = IntVariable("myint", 5)
     self.real_var1 = RealVariable("Rev", "myreal1", 0.5)
     self.real_var2 = RealVariable("Rev", "myreal2", 0.5)
     self.matrix_var = MatrixVariable("Rev", "mymatrix", "matrix", 2, 0.5)
     self.cg = CodeGenerator()
Ejemplo n.º 2
0
def main():
    inpt = Path(sys.argv[1])
    if inpt.is_dir():
        input_paths = inpt.glob("*.jack")

        for src in OS_LIB.glob("*.vm"):
            dst = inpt.joinpath(src.name)
            shutil.copy(src, dst)

        for src in EXTRA_OS_LIBS:
            dst = inpt.joinpath(src.name)
            shutil.copy(src, dst)
    else:
        input_paths = [inpt]

    for input_path in input_paths:
        output_path = input_path.parent.joinpath(f"{input_path.stem}.vm")
        lines = (line for line in input_path.read_text().split("\n"))
        # lines = print_gen(lines)
        tokens = gen_tokens_for_lines(lines=lines)
        parser = Parser(tokens)
        cls = parser.parse_class()
        code_generator = CodeGenerator()
        code = code_generator.generate(cls)
        output_path.write_text("\n".join(code))
Ejemplo n.º 3
0
def test_function_calls(vm):
    g = CodeGenerator()
    code = g.translate(commands=[
            (0,  'call', 'main', 0),
            (1,  'goto', 'end'),

            (2,  'function', 'main', 0),
            (3,  'push', 'constant', 10),
            (4,  'push', 'constant', 20),
            (5,  'call', 'double-sum', 2),
            (6,  'return'),

            (7,  'function', 'double-sum', 1),
            (8,  'push', 'argument', 0),
            (9,  'push', 'argument', 1),
            (10, 'add'),
            (11, 'pop', 'local', 0),
            (12, 'push', 'local', 0),
            (13, 'push', 'local', 0),
            (14, 'add'),
            (15, 'return'),

            (16, 'label', 'end'),
        ],
        filename='<input>',
    )
    vm.execute(code, 500)

    assert vm.ram[vm.symbols['SP']] == vm.stack_offset + 1
    assert vm.ram[vm.stack_offset] == 2 * (10 + 20)
Ejemplo n.º 4
0
    def save_point_to_tmp(self, sql, rdd, once_size=1000):
        '''
        批量数据库操作
        :param sql:要批量执行的语句
        :param rdd:数据源RDD,经过Map操作得到的tuple列表[(a,b,c),(d,e,f),(d.f.g)]
        :param once_size:每次执行的条数,默认每次一千条
        :return:
        '''
        cg = CodeGenerator()
        current_args = list()
        args = rdd.collect()

        for i in range(len(args)):
            if len(args) != 0:
                full_arg = [
                    cg.get_sequence('point'),
                ]
                full_arg.extend(args.pop())
                current_args.append(full_arg)

            # 但前参数长度达到批量值 或者 剩余参数已为0
            if len(current_args) >= once_size or len(args) == 0:
                if len(current_args) > 0:
                    try:
                        self.executemany_without_commit(sql, current_args)
                    except Exception as e:
                        return e, current_args
                    current_args.clear()
                    self.cnn.commit()
Ejemplo n.º 5
0
def main(filename, execute):
    try:
        print "filename=", filename
        prefix= filename.split(".")[0]
        output_file_name = prefix + ".py"
        output = open(output_file_name, 'w')    
        f = open(filename, "r")
        data = simplejson.load(f)
        data = byteify(data)
        
        codegen = CodeGenerator()
        #name the testcase
        codegen = identify_imports(data, codegen)
        codegen += ""
        codegen += ""
        codegen += "class Test7777777(%s):" % (IdentifyParentClasses(data))
        codegen.indent()
        codegen += "test_id = 7777777"
        codegen = identify_resources(data, codegen)
        codegen = createSetupMethod(data, codegen)
        codegen = createRunMethod(data, codegen)
    
        output.write(str(codegen))
        return str(codegen)
    except:
        raise 
Ejemplo n.º 6
0
 def __init__(self, file_name):
     self.file_name = file_name
     self.stack = Stack()
     self.stack.push("EOF")
     self.stack.push("Source")
     self.parser_table = PARSER_TABLE
     self.symbol_table = OOPSymbolTable()
     self.semantic_stack = Stack()
     self.memory_manager = MemoryManager(1000, 2000)
     self.scanner = Scanner(file_name, self.symbol_table)
     self.next_token = self.scanner.get_next_token()
     self.top_stack = self.stack.top()
     self.rule_number = None
     self.rule = ""
     self.grammar = GRAMMAR
     self.error_handler = ErrorHandler(self.scanner)
     self.symbol_table.set_error_handler(self.error_handler)
     self.semantic_analyzer = SemanticAnalyzer(self.symbol_table,
                                               self.memory_manager,
                                               self.semantic_stack,
                                               self.error_handler)
     self.code_generator = CodeGenerator(self.symbol_table,
                                         self.semantic_stack,
                                         self.memory_manager)
     self.current_identifier = None
     self.follow = FOLLOW
     self.non_terminal = 0
     self.must_get = False
Ejemplo n.º 7
0
def test_return_statement(vm):
    n_args = 3
    frame_offset = 512
    current_sp = frame_offset + 100
    arg1 = 111
    arg2 = 222
    arg3 = 333
    caller_arg = 254
    caller_lcl = caller_arg + 5
    caller_this = 1234
    caller_that = 2345
    return_addr = 6000
    return_value = 42

    vm.ram[frame_offset + 0] = arg1
    vm.ram[frame_offset + 1] = arg2
    vm.ram[frame_offset + 2] = arg3
    vm.ram[frame_offset + 3] = return_addr
    vm.ram[frame_offset + 4] = caller_lcl
    vm.ram[frame_offset + 5] = caller_arg
    vm.ram[frame_offset + 6] = caller_this
    vm.ram[frame_offset + 7] = caller_that
    vm.ram[current_sp - 1] = return_value

    vm.ram[vm.symbols['LCL']] = frame_offset + n_args + 5
    vm.ram[vm.symbols['ARG']] = frame_offset
    vm.ram[vm.symbols['THIS']] = 5555
    vm.ram[vm.symbols['THAT']] = 6666
    vm.ram[vm.symbols['SP']] = current_sp

    g = CodeGenerator()
    g.translate(commands=[
            (0, 'function', 'fn', 0),
        ],
        filename='<input>',
    )
    code = g.translate(commands=[
            (0, 'return'),
        ],
        filename='<input>',
    )
    vm.execute(code, 100)

    assert vm.ram == {
        vm.symbols['SP']: frame_offset + 1,
        vm.symbols['LCL']: caller_lcl,
        vm.symbols['ARG']: caller_arg,
        vm.symbols['THIS']: caller_this,
        vm.symbols['THAT']: caller_that,

        frame_offset + 0: return_value,
        frame_offset + 1: arg2,
        frame_offset + 2: arg3,
        frame_offset + 3: return_addr,
        frame_offset + 4: caller_lcl,
        frame_offset + 5: caller_arg,
        frame_offset + 6: caller_this,
        frame_offset + 7: caller_that,
        current_sp - 1: return_value,
    }
Ejemplo n.º 8
0
    def take_action(self, parsed_args):

        config_parser = ConfigurationParser()
        config = config_parser.parse(parsed_args.config_file)
        code_generator = CodeGenerator(config)
        code_generator.generate()
        setup_script_generator = SetupScriptGenerator()
        setup_script_generator.generate(config)
Ejemplo n.º 9
0
 def take_action(self, parsed_args):
     
     config_parser = ConfigurationParser()
     config = config_parser.parse(parsed_args.config_file)
     code_generator = CodeGenerator(config)
     code_generator.generate()
     setup_script_generator = SetupScriptGenerator()
     setup_script_generator.generate(config)
Ejemplo n.º 10
0
class Translator:
    def __init__(self):
        self.__parser = None
        self.__generator = None


    @contextlib.contextmanager
    def __init_resorces(self):
        self.__parser = Parser()
        self.__generator = CodeGenerator()
        yield
        self.__parser = None
        self.__generator = None


    def translate(self, path, dry_run=False):
        with self.__init_resorces():
            blocks = self.__translate(path)

            if dry_run:
                for _ in blocks:
                    pass
            else:
                output = self.__make_output_name(path)
                with open(output, 'w') as f:
                    for block in blocks:
                        f.write(block)
                        f.write('\n')


    def __translate(self, path):
        if os.path.isdir(path):
            yield from self.__translate_project(path)
        else:
            yield from self.__translate_file(path)


    def __translate_project(self, path):
        yield self.__generator.gen_initializer()
        for fname in glob.iglob(os.path.join(path, '*.vm')):
            yield from self.__translate_file(fname)


    def __translate_file(self, path):
        filename = os.path.splitext(os.path.basename(path))[0]
        commands = self.__parser.parse_file(path)
        yield from self.__generator.itranslate(filename, commands)


    def __make_output_name(self, input_name):
        if os.path.isdir(input_name):
            dirname = os.path.basename(os.path.abspath(input_name))
            fname = os.path.join(input_name, dirname)
        else:
            fname, _ = os.path.splitext(input_name)
        return fname + '.asm'
Ejemplo n.º 11
0
    def __init__(self, tree: Program, symbol_table: SymbolTable,
                 source_file: str) -> None:
        llvm.initialize()
        llvm.initialize_all_targets()
        llvm.initialize_all_asmprinters()

        self.tree = tree
        self.codegen = CodeGenerator(symbol_table)
        self.source_file = source_file
        self.target = llvm.Target.from_triple(llvm.get_default_triple())
Ejemplo n.º 12
0
def test_expression_with_ops():
    toks = gen_tokens_for_lines(lines=["1 * 2 + 3;"])
    parsed = Parser(toks).parse_expression()
    code_gen = CodeGenerator()
    code = code_gen.generate_expression(parsed)
    assert code == [
        "push constant 1",
        "push constant 2",
        "push constant 3",
        "add",
        "call Math.multiply 2",
    ]
Ejemplo n.º 13
0
def test_label(vm):
    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'label', 'name1'),
            (1, 'label', 'name2'),
        ],
        filename='<input>',
    )
    vm.execute(code, 100)

    assert vm.symbols['<input>$name1'] == 0
    assert vm.symbols['<input>$name2'] == 1
 def __init__(self, functionDefinitionTable, classTable):
     self.localSymbolTable = SymbolTable()
     self.functionTable: SymbolTable() = functionDefinitionTable
     self.preemptiveFunctionCallTable = SymbolTable()
     self.semanticsChecker = SemanticsChecker()
     self.codeGenerator = CodeGenerator()
     self.expressionStack = deque()
     self.currentFunctionId = ''
     self.currentFunction = None
     self.classTable = classTable
     self.checkClassDefinitionsSemantics()
     self.currentClass = None
     self.currentFunctionReturn = False
     self.functionCallStack = list()
Ejemplo n.º 15
0
def test_goto(vm):
    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'push', 'constant', 10),
            (1, 'goto', 'end'),
            (2, 'push', 'constant', 20),
            (3, 'label', 'end'),
        ],
        filename='<input>',
    )
    vm.execute(code, 100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 1,
        vm.stack_offset + 0: 10,
    }
Ejemplo n.º 16
0
def main():
    prog = '''
        int g = 1 - 2 - 3;
        bool axx = true;
        int[] aaa = new int[10];
        aaa[0] = 10;
        string g3 = "kek";
        int t = 4 + 5;
        double wow = g + t;
        t = 10 * 12 - (g + g);
        double s = 90;
    
        
        for (int i = 0, j = 8; ((i <= 5)); i = i + 1)
            for(; t < g;)
                if (t > 7 + g) {
                    t = t + g * (2 - 1) + 0;  // comment 2
                    g3 = "98\tура";
                }
        for(;;);
        
        string[] arr = new string[10];
        int[] kek = new int[]{ 1, 2, 3, 4, 5 };
        
        
        public int[] what(int a, int b) 
        {
            int[] c = new int[]{5, 4, 6, 5, 1};
            string fff = "asd";
            return c;
        }
        
        
        public static void whatElse(int a, int b) 
        {
            int[] c = what(a, b);
            c[a + b] = 0;
            int e = c[3];
            while (true)
            {
                a = a + b;
                do
                {
                    b = a - b * b;
                }
                while (g + t > t)
            }
            return;
        }
    '''
    prog = mel_parser.parse(prog)
    # print(*prog.tree, sep=os.linesep)
    a = Analyzer()
    the_prog, _ = a.analyze(prog)
    gen = CodeGenerator(the_prog, '')
    # try:
    #     a.analyze(prog)
    # except ValueError as e:
    #     print(e)
    print(*the_prog.tree, sep=os.linesep)
Ejemplo n.º 17
0
def test_not(vm):
    vm.ram[vm.stack_offset + 0] = 22
    vm.ram[vm.symbols['SP']] += 1

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'not'),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 1,
        vm.stack_offset + 0: ~22,
    }
Ejemplo n.º 18
0
Archivo: job.py Proyecto: cpfair/sand
    def run(self):
        self._state = CompilationState.Downloading
        # Get the app metadata
        appstore_uuid = self._parameters["app"]["id"] # Passed from JS-land
        appstore_uuid = re.sub(r"[^a-f0-9]", "", appstore_uuid)
        assert len(appstore_uuid) == 24, "Bad app UUID specified"
        self.app_metadata = app_metadata = requests.get("https://api2.getpebble.com/v2/apps/id/%s" % appstore_uuid).json()["data"][0]
        # Fetch the app itself, if we need to
        cached_pbw_name = "%s-%s.pbw" % (appstore_uuid, app_metadata["latest_release"]["id"])
        cached_pbw_path = os.path.join(self._pbw_cache_dir, cached_pbw_name)
        # (this has a race condition if you start a bunch of jobs at once)
        if not os.path.exists(self._pbw_cache_dir):
            os.makedirs(self._pbw_cache_dir)
        # Also a race condition here if two jobs were using the same PBW at once
        if not os.path.exists(cached_pbw_path):
            pbw_data = requests.get(app_metadata["latest_release"]["pbw_file"]).content
            with open(cached_pbw_path, "wb") as pbwhnd:
                pbwhnd.write(pbw_data)
        else:
            os.utime(cached_pbw_path, None) # So I can invalidate the cache by file metadata

        self._state = CompilationState.GeneratingCode
        # Generate the required C code
        modules_dir = os.path.join(os.path.dirname(__file__), "modules")
        c_code = CodeGenerator.generate_c_code(modules_dir, self._parameters["configuration"])

        # Set up our scratch space (same race condition as earlier...)
        scratch_dir = os.path.join(self._scratch_dir, self.uuid)
        if not os.path.exists(scratch_dir):
            os.makedirs(scratch_dir)

        # Write out config for later perusal
        json.dump(self._parameters, open(os.path.join(scratch_dir, "parameters.json"), "w"))

        c_code_path = os.path.join(scratch_dir, "mods.c")
        open(c_code_path, "w").write(c_code)

        # We swap out the UUID so the app store doesn't auto-update it away
        # We use a hard-to-guess prefix so people can't upload remixed apps in the PAS - only we should be doing that
        sha1 = hashlib.sha1()
        sha1.update(app_metadata["uuid"].encode("ascii"))
        sha1.update(os.environ.get("REMIXED_UUID_KEY", "").encode("ascii"))
        new_uuid = uuid.UUID("5a4d" + sha1.hexdigest()[:4] + app_metadata["uuid"][8:])
        self.output_pbw_uuid = new_uuid

        # Create the patched PBW
        self._state = CompilationState.Patching
        pbw_output_name = re.sub("[^a-zA-Z0-9]", "", unidecode(app_metadata["title"])) + "-remixed.pbw"
        pbw_output_path = os.path.join(scratch_dir, pbw_output_name)
        # Create a one-off logger to record the carnage
        patch_logger = logging.getLogger("rockgarden")
        patch_logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler(os.path.join(scratch_dir, "patch.log"))
        patch_logger.addHandler(fh)
        Patcher(scratch_dir=os.path.join(scratch_dir, "patcher")).patch_pbw(cached_pbw_path, pbw_output_path, c_sources=[c_code_path], new_uuid=new_uuid, cflags=["-I%s" % modules_dir], ensure_platforms=["aplite", "basalt"])
        patch_logger.removeHandler(fh)
        fh.close()

        self._state = CompilationState.Done
        self._output_pbw = pbw_output_path
Ejemplo n.º 19
0
def test_call_statement(vm):
    caller_arg = 254
    caller_lcl = caller_arg + 5
    caller_this = 1234
    caller_that = 2345
    caller_sp = 512

    n_args = 3
    arg1 = 111
    arg2 = 222
    arg3 = 333

    vm.symbols['fn'] = 8192
    vm.ram[vm.symbols['SP']] = caller_sp
    vm.ram[vm.symbols['LCL']] = caller_lcl
    vm.ram[vm.symbols['ARG']] = caller_arg
    vm.ram[vm.symbols['THIS']] = caller_this
    vm.ram[vm.symbols['THAT']] = caller_that

    vm.ram[caller_sp - 3] = arg1
    vm.ram[caller_sp - 2] = arg2
    vm.ram[caller_sp - 1] = arg3

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'call', 'fn', n_args),
        ],
        filename='<input>',
    )
    vm.execute(code, 100)

    assert vm.ram == {
        vm.symbols['SP']: caller_sp + 5,
        vm.symbols['LCL']: caller_sp + 5,
        vm.symbols['ARG']: caller_sp - n_args,
        vm.symbols['THIS']: caller_this,
        vm.symbols['THAT']: caller_that,

        caller_sp - 3: arg1,
        caller_sp - 2: arg2,
        caller_sp - 1: arg3,
        caller_sp + 0: vm.symbols['fn$ret.1'],
        caller_sp + 1: caller_lcl,
        caller_sp + 2: caller_arg,
        caller_sp + 3: caller_this,
        caller_sp + 4: caller_that,
    }
Ejemplo n.º 20
0
def test_push_constant(vm):
    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'push', 'constant', 1),
            (1, 'push', 'constant', 10),
            (2, 'push', 'constant', 100),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 3,
        vm.stack_offset + 0: 1,
        vm.stack_offset + 1: 10,
        vm.stack_offset + 2: 100,
    }
Ejemplo n.º 21
0
 def test_initialization(self):
     language = "python"
     cg = CodeGenerator(language)
     t = cg._env.get_template('examples_header.jinja')
     with open('./' + language + '/templates/examples_header.jinja',
               'r') as myfile:
         t2 = myfile.read().replace('\n', '')
     self.assertEqual(str(t.render()).replace('\n', ''), t2)
Ejemplo n.º 22
0
def test_program(vm):
    g = CodeGenerator()
    code = g.gen_initializer()
    code += '\n' + g.translate(commands=[
            (0, 'goto', 'end'),

            (1, 'function', 'Sys.init', 0),
            (2, 'push', 'constant', 0),
            (3, 'return'),

            (4, 'label', 'end')
        ],
        filename='<input>',
    )
    vm.execute(code, 500)

    assert vm.ram[vm.symbols['SP']] == vm.stack_offset + 1
Ejemplo n.º 23
0
def test_eq(vm, a, b, expected):
    vm.ram[vm.stack_offset + 0] = a
    vm.ram[vm.stack_offset + 1] = b
    vm.ram[vm.symbols['SP']] += 2

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'eq'),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 1,
        vm.stack_offset + 0: expected,
        vm.stack_offset + 1: b,
    }
Ejemplo n.º 24
0
def test_or(vm):
    vm.ram[vm.stack_offset + 0] = 22
    vm.ram[vm.stack_offset + 1] = 21
    vm.ram[vm.symbols['SP']] += 2

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'or'),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 1,
        vm.stack_offset + 0: 22|21,
        vm.stack_offset + 1: 21,
    }
Ejemplo n.º 25
0
def test_expression_with_ops_and_fn_call():
    toks = gen_tokens_for_lines(lines=["x + Klass.g(2, y, -z) * 5;"])
    parsed = Parser(toks).parse_expression()
    code_gen = CodeGenerator()
    code_gen._symbol_tables.push_new()
    code_gen._symbol_tables.add("x", TypeInt(), Kind.ARGUMENT)
    code_gen._symbol_tables.add("y", TypeInt(), Kind.ARGUMENT)
    code_gen._symbol_tables.add("z", TypeInt(), Kind.ARGUMENT)
    code = code_gen.generate_expression(parsed)
    assert code == [
        "push argument 0",
        "push constant 2",
        "push argument 1",
        "push argument 2",
        "neg",
        "call Klass.g 3",
        "push constant 5",
        "call Math.multiply 2",
        "add",
    ]
Ejemplo n.º 26
0
def test_push_temp(vm):
    vm.ram[vm.symbols['R5'] + 1] = 33
    vm.ram[vm.symbols['R5'] + 3] = 22

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'push', 'temp', 1),
            (1, 'push', 'temp', 3),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 2,
        vm.symbols['R5'] + 1: 33,
        vm.symbols['R5'] + 3: 22,
        vm.stack_offset + 0: 33,
        vm.stack_offset + 1: 22,
    }
Ejemplo n.º 27
0
def test_push_pointer(vm):
    vm.ram[vm.symbols['R3']] = 33
    vm.ram[vm.symbols['R4']] = 22

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'push', 'pointer', 0),
            (1, 'push', 'pointer', 1),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 2,
        vm.symbols['R3']: 33,
        vm.symbols['R4']: 22,
        vm.stack_offset + 0: 33,
        vm.stack_offset + 1: 22,
    }
Ejemplo n.º 28
0
def test_push_static(vm):
    static_offset = vm.symbols['R15'] + 1
    vm.ram[static_offset + 0] = 33
    vm.ram[static_offset + 1] = 22

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'push', 'static', 1),
            (1, 'push', 'static', 10),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset + 2,
        static_offset + 0: 33,
        static_offset + 1: 22,
        vm.stack_offset + 0: 33,
        vm.stack_offset + 1: 22,
    }
Ejemplo n.º 29
0
def test_function_statement(vm):
    local_segment_size = 2
    initial_sp = 512
    vm.ram[vm.symbols['SP']] = initial_sp
    vm.ram[vm.symbols['LCL']] = vm.ram[vm.symbols['SP']]

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'function', 'fn', local_segment_size),
        ],
        filename='<input>',
    )
    vm.execute(code, 100)

    assert vm.symbols['fn'] == 0
    assert vm.ram == {
        vm.symbols['SP']: initial_sp + local_segment_size,
        vm.symbols['LCL']: initial_sp,
        initial_sp + 0: 0,
        initial_sp + 1: 0,
    }
Ejemplo n.º 30
0
def from_data(floc, fl):
    if not floc.endswith("/"):
        floc += "/"

    config_location = floc + "config"

    predict_references = False
    if "p" in fl:
        predict_references = True

    try:
        os.mkdir(config_location)
    except OSError as e:
        if e.errno != 17:
            print e
            sys.exit(-1)

    cdm_gen = CDMGenerator(floc, config_location, predict_references=predict_references)
    cdm_gen.generate()
    code_gen = CodeGenerator(config_location)
    code_gen.generate()
Ejemplo n.º 31
0
def test_label_within_function(vm):
    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'call', 'fn', 0),
            (1, 'goto', 'end'),
            (2, 'function', 'fn', 0),
            (5, 'push', 'constant', 0),
            (3, 'goto', 'end'),
            (4, 'label', 'label1'),
            (6, 'return'),
            (4, 'label', 'end'),
            (6, 'return'),
            (7, 'label', 'end'),
        ],
        filename='<input>',
    )
    vm.execute(code, 500)

    assert '<input>$end' in vm.symbols
    assert '<input>$fn$label1' in vm.symbols
    assert '<input>$fn$end' in vm.symbols
Ejemplo n.º 32
0
def test_pop_temp(vm):
    temp_offset = vm.symbols[kw.special_segmnets['temp']]
    vm.ram[vm.stack_offset + 0] = 33
    vm.ram[vm.stack_offset + 1] = 22
    vm.ram[vm.symbols['SP']] += 2

    g = CodeGenerator()
    code = g.translate(commands=[
            (0, 'pop', 'temp', 1),
            (1, 'pop', 'temp', 3),
        ],
        filename='<input>',
    )
    vm.execute(code, max_steps=100)

    assert vm.ram == {
        vm.symbols['SP']: vm.stack_offset,
        temp_offset + 1: 22,
        temp_offset + 3: 33,
        vm.stack_offset + 0: 33,
        vm.stack_offset + 1: 22,
    }
Ejemplo n.º 33
0
 def __init__(self):
     self._subdirs = ['lib', 'include', 'python', 'swig',
                      'grc']  # List subdirs where stuff happens
     self._has_subdirs = {}
     self._skip_subdirs = {}
     self._info = {}
     for subdir in self._subdirs:
         self._has_subdirs[subdir] = False
         self._skip_subdirs[subdir] = False
     self.parser = self.setup_parser()
     self.tpl = CodeGenerator()
     self.args = None
     self.options = None
     self._dir = None
Ejemplo n.º 34
0
def from_data(floc, fl):
    if not floc.endswith("/"):
        floc += "/"

    config_location = floc + "config"

    predict_references = False
    if "p" in fl:
        predict_references = True

    try:
        os.mkdir(config_location)
    except OSError as e:
        if e.errno != 17:
            print e
            sys.exit(-1)

    cdm_gen = CDMGenerator(floc,
                           config_location,
                           predict_references=predict_references)
    cdm_gen.generate()
    code_gen = CodeGenerator(config_location)
    code_gen.generate()
Ejemplo n.º 35
0
from code_generator import CodeGenerator
from environment import Environment
from scanner import join_tokens, scan
from analyzer import Parser
#from environment import environment
import os

expr = raw_input('expression: ')
tokens = join_tokens(scan(expr))
print("STEP 1")
print("Generated token list: ")
print(tokens)
parser = Parser(tokens)
tree = parser.parse()
print("STEP 2")
print("Parsing token list to binary tree")
print (tree)
code_generator = CodeGenerator(orders_list=[])
code_generator.postorder(tree)
code_generator.orders_list.append('end')
print("STEP 3")
print("Postorder")
print(code_generator.orders_list)
environment = Environment(code_generator.orders_list)
result = environment.count()
print("RESULT: ")
print(result)
Ejemplo n.º 36
0
def from_config(floc, fl):
    code_gen = CodeGenerator(floc)
    code_gen.generate()
from code_parser import CodeParser
from code_generator import CodeGenerator

code_directory = "include/"
output_file = "data.conf"

codeParser = CodeParser()
ecosystem = codeParser.generate_data_structure(code_directory, output_file)

codeGenerator = CodeGenerator()
codeGenerator.generate_deserializers(ecosystem)
Ejemplo n.º 38
0
    def generate_unit_test(self):
        """
        Generate the CPP unit test for this function
        """
        utg = CodeGenerator()
        # Generate definition, rng setup, etc.
        self._unit_test_signature(utg)
        self._init_rng(utg)
        utg.add_line()
        self._find_default_impl(utg)
        utg.add_line()
        self._init_arguments(utg)
        utg.add_line()
        self._begin_implementation_loop(utg)
        self._begin_argument_loops(utg)
        self._argument_loop_body(utg)
        utg.add_line("for (YepSize length = 1024; length < 1088; length++) {").indent()
        self._argument_loop_body(utg)
        utg.dedent()

        indent_depth = len([ arg for arg in self.arguments if arg.is_pointer ])
        for i in range(indent_depth):
            utg.add_line("}").dedent()
        self._passed_or_skipped(utg)

        utg.add_line("next_descriptor:")
        utg.add_line("continue;")
        utg.dedent().add_line("}")
        utg.add_line("return -failedTests;")
        utg.dedent().add_line("}")
        return utg.get_code()