Exemple #1
0
 def test_while(self):
     cpl_program = """
     a, b: float;
     {
         while (a < b) {
             if (b  > 100)
                 break;
             else {
                 a = a + 1;
                 continue;
             }
         }
     }
     """
     ast = build_ast(CPLTokenizer(cpl_program))
     sym = SymbolTable.build_form_ast(ast)
     code = [i.code for i in get_ir(ast, sym)]
     self.assertEqual(code, [
         'condition_label_2:', 'RLSS t1 a b', 'JMPZ end_while_label_3 t1',
         'ITOR t3 100', 'RGRT t2 b t3', 'JMPZ else_label_0 t2',
         'JUMP end_while_label_3', 'JUMP endif_label_1', 'else_label_0:',
         'ITOR t5 1', 'RADD t4 a t5', 'RASN a t4', 'JUMP condition_label_2',
         'endif_label_1:', 'JUMP condition_label_2', 'end_while_label_3:',
         'HALT'
     ])
Exemple #2
0
def compiler(cpl_string):
    """
    The function simulates a CPL compiler.

    :param cpl_string: String which represent the CPL program.
    :return pair of two lists (errors, quad).
    """
    quad = []
    errors, ast = build_ast(CPLTokenizer(cpl_string))
    if errors and not ast:
        return errors, []

    try:
        _errors, symbol_table = SymbolTable.build_form_ast(ast)
        errors.extend(_errors)
        quad = get_quad(get_ir(ast, symbol_table))
    except CPLCompoundException as exception:
        errors.extend(exception.exceptions)

    return errors, quad
Exemple #3
0
 def test_switch(self):
     cpl_program = """
     a, b: int;
     {
         switch(a) {
             case 1: {
                 write(1);
                 break;
             }
             case 2: write(2);
             case 3: {
                 switch(b) {
                     case 5: write(5);
                     default: break;
                 }
             }
             case 4: write(4);
             default: write(0);
         }
     }
     """
     ast = build_ast(CPLTokenizer(cpl_program))
     sym = SymbolTable.build_form_ast(ast)
     code = [i.code for i in get_ir(ast, sym)]
     self.assertEqual(code, [
         'case_1_label_3:', 'IEQL t2 a 1', 'JMPZ case_2_label_4 t2',
         'IPRT 1', 'JUMP end_switch_label_7', 'JUMP end_switch_label_7',
         'case_2_label_4:', 'IEQL t3 a 2', 'JMPZ case_3_label_5 t3',
         'IPRT 2', 'JUMP end_switch_label_7', 'case_3_label_5:',
         'IEQL t4 a 3', 'JMPZ case_4_label_6 t4', 'case_5_label_0:',
         'IEQL t1 b 5', 'JMPZ default_label_2 t1', 'IPRT 5',
         'JUMP end_switch_label_1', 'default_label_2:',
         'JUMP end_switch_label_1', 'end_switch_label_1:',
         'JUMP end_switch_label_7', 'case_4_label_6:', 'IEQL t5 a 4',
         'JMPZ default_label_8 t5', 'IPRT 4', 'JUMP end_switch_label_7',
         'default_label_8:', 'IPRT 0', 'end_switch_label_7:', 'HALT'
     ])