编译原理:递归下降分析法

TEST_STRING = ["eadeaa", "edeaebd", "edeaeaadabacae"]


class Tools():
    '''
    @:parameter point
    Description : This is a point which holds the position being processed

    @:parameter content
    Description: It keeps the test string

    @:parameter temp
    Description: when an error occurs, using it to step back from last point position
    '''

    def __init__(self, content):
        self.content = content
        self.point = 0
        self.temp = 0  # 用于指针退回

    def parse_E(self):
        print('E', end=" ")
        if (
                self.is_e() and
                self.parse_B() and
                self.is_a() and
                self.parse_A()):
            return True
        else:
            return False

    def parse_A(self):
        print('A', end=" ")
        if self.is_a():
            return True
        if (
                self.is_b() and
                self.parse_A() and
                self.is_c() and
                self.parse_B()):
            return True
        else:
            return False

    def parse_B(self):
        self.temp = self.point
        print('B', end=" ")
        if (
                self.is_d() and
                self.parse_E() and
                self.is_e()
        ):
            return True
        self.point = self.temp
        if (
                self.is_a() and
                self.parse_C()
        ):
            return True
        else:
            return False

    def parse_C(self):
        print('C', end=" ")
        if self.is_e():
            return True
        if (
                self.is_d() and
                self.parse_C()
        ):
            return True
        else:
            return False

    def is_a(self):
        if self.content[self.point] == 'a':
            self.point += 1
            return True
        else:
            return False

    def is_b(self):
        if self.content[self.point] == 'b':
            self.point += 1
            return True

        else:
            return False

    def is_c(self):
        if self.content[self.point] == 'c':
            self.point += 1
            return True

        else:
            return False

    def is_d(self):
        if self.content[self.point] == 'd':
            self.point += 1
            return True

        else:
            return False

    def is_e(self):
        if self.content[self.point] == 'e':
            self.point += 1
            return True

        else:
            return False

    def process(self):
        if self.parse_E():
            print("\nOK")
        else:
            print("\nError")


if __name__ == "__main__":
    for content in TEST_STRING:
        print("Test String: %s" % content)
        Tools(content).process()
        print('')

你可能感兴趣的:(编译原理:递归下降分析法)