栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【编译原理 语法制导翻译 代码】

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【编译原理 语法制导翻译 代码】

前文重复语法分析程序代码:语法分析代码 1.semanticfunc.py
import parserfunc as pf
import scannerclass as sc
import numpy as np
import turtle
import sys
import matplotlib
import matplotlib.pyplot as plt

class semantic(pf.Parsef):
    def initPaint(self):    # 初始化画布
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111)

    def Errmsg(self):   #出错处理
        sys.exit(1)

    def CalcCoord(self,x,y):    # 计算点坐标   即比例旋转平移变换 x,y都是二元组
        x = x * self.Scale_x
        y = y * self.Scale_y     ## 进行比例变换
        tmp_x = x * np.cos(self.Rot_angle) + y * np.sin(self.Rot_angle)
        y = y * np.cos(self.Rot_angle) - x * np.sin(self.Rot_angle)
        x= tmp_x        ## 旋转变换
        x = x + self.Origin_x
        y = y + self.Origin_y   ## 进行平移变换
        return x,y


    def DrawLoop(self):
        x,y = self.CalcCoord(self.x_ptr,self.y_ptr)
        self.ax.scatter(x,y)


    def Statement(self):    ## 重写statement ,让每次ForStatement执行完毕后画图
        self.enter("Statement")
        if self.token.type == sc.Token_Type.ORIGIN:
            self.OriginStatement()
        elif self.token.type == sc.Token_Type.SCALE:
            self.ScaleStatement()
        elif self.token.type == sc.Token_Type.ROT:
            self.RotStatement()
        elif self.token.type == sc.Token_Type.FOR:
            self.ForStatement()
            self.DrawLoop()
        # elif self.token.type == sc.Token_Type.CONST_ID or self.token.type == sc.Token_Type.L_BRACKET or 
        #     self.Expression()
        else:   self.SyntaxError(2)
        self.back("Statement")

    # 绘图语言解释器入口(与主程序的外部接口)
    def Parser(self):  # 语法分析器的入口
        self.enter("Parser")
        if (self.scanner.fp == None):  # 初始化词法分析器
            print("Open Source File Error !n")
        else:
            self.FetchToken()  # 获取第一个记号
            self.Program()  # 递归下降分析
            plt.show()
            self.scanner.CloseScanner()  # 关闭词法分析器
            self.back("Parser")

2.semanticmain.py
import scannerfunc as sf
import parserfunc as pf
import semanticfunc as paint
import os

file_name = 'test.txt'
scanner = sf.scanner(file_name)
parser = pf.Parsef(scanner)
parser.Parser()
semantic = paint.semantic(parser)
semantic.initPaint()
semantic.Parser()
3.测试文本test.txt
ORIGIN IS (50, 50);
ROT IS 0;
SCALE IS (40, 40);
FOR T FROM 0 TO 2*PI STEP PI/50 DRAW (T, -SIN(T));
ORIGIN IS (50, 40);
FOR T FROM 0 TO 2*PI STEP PI/50 DRAW (T, -SIN(T));
ORIGIN IS (50, 80);
FOR T FROM 0 TO 2*PI STEP PI/50 DRAW (T, -SIN(T));
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/971935.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号