编译原理:LL(1)预测分析表程序

说明

  1. 本程序仅基于最小语法测试集,源代码本身不具有泛化能力
  2. 使用python作为编程语言,应用了少量面向对象思想
  3. 自觉变量名称设计规范,源代码易读,再此不做多余解释,有问题请留言
TEST_STRING = ["eadeaa", "edeaeaadabacae", "edeaebd"]


class Rules(object):
    def __init__(self):
        self.state = "E"

    def error(self, position, content):
        print("Position %d ,Error !!" % position, content[position])
        exit(-1)

    def log(self):
        print("Stack:  %s" % self.state)

    def reduce(self, present_state, char, point):
        temp = self.state[:-1]
        if present_state == 'a' and char == 'a':
            self.state = temp
        elif present_state == 'b' and char == 'b':
            self.state = temp
        elif present_state == 'c' and char == 'c':
            self.state = temp
        elif present_state == 'd' and char == 'd':
            self.state = temp
        elif present_state == 'e' and char == 'e':
            self.state = temp
        else:
            self.error(point, content)

    def analyze(self, content, point):
        char = content[point]
        present_state = self.state[-1]
        temp_state = self.state[0:-1]

        if present_state == 'E' and char == 'e':
            self.state = temp_state
            self.state += "AaBe"
        elif present_state == 'A':
            if char == 'a':
                self.state = temp_state
                self.state += 'a'
            elif char == 'b':
                self.state = temp_state
                self.state += 'BcAb'
        elif present_state == 'B':
            if char == 'd':
                self.state = temp_state
                self.state += 'dEd'
            elif char == 'a':
                self.state = temp_state
                self.state += 'Ca'
        elif present_state == 'C':
            if char == 'e':
                self.state = temp_state
                self.state += 'e'
            elif char == 'd':
                self.state = temp_state
                self.state += 'Cd'
        self.reduce(self.state[-1], char, point)
        point += 1
        return point


class Tools(object):
    @staticmethod
    def process(content):
        anaylzer = Rules()
        point = 0
        while point < len(content):
            point = anaylzer.analyze(content, point)
            anaylzer.log()


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

你可能感兴趣的:(编译原理:LL(1)预测分析表程序)