精华内容
下载资源
问答
  • 1.把下列语句翻译三地址代码 while a > 10 do      if b = 100 then          while a < 20 do        ...

    题目

    1.把下列语句翻译成三地址代码
    while a > 10 do
         if b = 100 then
             while a < 20 do
                 a := a + b – 1

    解:
    (1) if a>10 goto (3)
    (2) goto -
    (3) if b==100 goto (5) M3.stat
    (4) goto (1) M1.stat
    (5) if a<20 goto (7) M5.stat
    (6) goto (1) M1.stat
    (7) t1 := a+b
    (8) t2 := t1-1
    (9) a := t2
    (10) goto (5) M4.stat
    (11) goto (1) M1.stat

    注释分析树:
    在这里插入图片描述
    2.把下列语句翻译成三地址代码
    if a>10 and c>d then
             if b=100 then a := a / b
             else a := a * b

    解:
    (1) if a>10 goto (3)
    (2) goto –
    (3) if c>d goto (5) M1.stat
    (4) goto –
    (5) if b==100 goto (7) M2.stat
    (6) goto (10) M3.stat
    (7) t1 := a/b
    (8) a := t1
    (9) goto -
    (10) t2 := a*b
    (11) a := t2

    注释分析树:
    在这里插入图片描述

    展开全文
  • 设计并实现一个一遍扫描的词法语法语义分析程序,将部分C语言的语法成分翻译三地址代码,要求有一定的出错提示和错误恢复功能。 例如简单赋值语句: area=3.14*a*a; s= 2*3.1416*r*(h+r); 翻译成后缀式: ...

    选择部分C语言的语法成分,设计其词法语法语义分析程序。

    设计并实现一个一遍扫描的词法语法语义分析程序,将部分C语言的语法成分翻译成三地址代码,要求有一定的出错提示和错误恢复功能。

    例如简单赋值语句:

    area=3.14*a*a;
    s= 2*3.1416*r*(h+r);

    翻译成后缀式: 

    area 3.14 a * a * =
    s 2 3.1416 *r*h r +*=

    翻译成三地址代码: 

    t1=3.14*a;
    t2=t1*a;
    area=t2;
    t3=2*3.1416;
    t4=t3*r;
    t5=h+r;
    t6=t4*t5;
    s=t6;

    源程序:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CLanguage {
    
    
        class CLanguage {
            WordStream wordStream = new WordStream("text.txt");
    
            // List<Error> errors = new List<Error>();
    
            static void Main(string[] args) {
                CLanguage syntax = new CLanguage();
                syntax.SemanticsParser();
                Console.ReadKey();
            }
    
            /// <summary>
            /// 语义分析
            /// </summary>
            public void SemanticsParser() {
                do {
                    functionParser();
                } while(wordStream.ReadNextWord().typeNum != WordPicker.endTypeNumber);
    
                if(success) {
                    // Console.WriteLine("成功");
                    foreach(FourFormula f in list) {
                        Console.WriteLine(f);
                    }
                    Console.WriteLine("---finish---");
                }
    
            }
    
            /// <summary>
            /// 函数
            /// </summary>
            private void functionParser() {
    
                Word word = wordStream.ReadNextWord();
                //返回类型
                if(!KeyWords.isReturnType(word)) {
                    addError(word, "返回值错误");
                }
                word = wordStream.ReadNextWord();
                //函数名
                if(!isIdentifier(word)) {
                    addError(word, "函数名错误");
                }
                //(参数){
                word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.left_bracket.typeNum) {
                    addError(word, "(缺失");
                    wordStream.retractWord();
                }
                arguments();
                word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.right_bracket.typeNum) {
                    addError(word, ")缺失");
                    wordStream.retractWord();
                }
                word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.left_curly_bracket.typeNum) {
                    addError(word, "{缺失");
                    wordStream.retractWord();
                }
                //语句串
                statementSequence();
                //}
                word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.right_curly_bracket.typeNum) {
                    addError(word, "}缺失");
                    wordStream.retractWord();
                }
    
            }
    
            /// <summary>
            /// 参数
            /// </summary>
            private void arguments() {
                Word word = wordStream.ReadNextWord();
                if(!KeyWords.isType(word)) {
                    if(isIdentifier(word))
                        addBeforeError(word, "参数类型缺失");
                    else {
                        if(wordStream.LastWord().typeNum == Symbols.comma.typeNum)
                            addBeforeError(word, ",多余");
                        wordStream.retractWord();
                        return;
                    }
                }
                word = wordStream.ReadNextWord();
                if(!isIdentifier(word)) {
                    addBeforeError(word, "参数标识符错误");
                    if(word.typeNum == Symbols.right_bracket.typeNum) {
                        wordStream.retractWord();
                        return;
                    }
                }
                //逗号
                word = wordStream.ReadNextWord();
                if(word.typeNum == Symbols.comma.typeNum) {
                    arguments();
                }
                else if(word.typeNum == Symbols.right_bracket.typeNum) {
                    wordStream.retractWord();
                    return;
                }
    
            }
    
            /// <summary>
            /// 判断是否是标识符
            /// </summary>
            /// <param name="word"></param>
            /// <returns></returns>
            private bool isIdentifier(Word word) {
                return word.typeNum == WordPicker.identifierTypeNumber;
            }
    
    
            /// <summary>
            /// 语串
            /// </summary>
            private void statementSequence() {
                Word word = wordStream.ReadNextWord();
                while(word.typeNum != Symbols.right_curly_bracket.typeNum && word.typeNum != WordPicker.endTypeNumber) {
                    statement(word);
                    word = wordStream.ReadNextWord();
                }
                wordStream.retractWord();
            }
    
            /// <summary>
            /// 语句
            /// </summary>
            /// <param name="word"></param>
            private void statement(Word word) {
                if(KeyWords.isType(word)) {
                    defineStatement();
                }
                else if(isIdentifier(word)) {
                    assignStatement();
                }
                else if(KeyWords.isIfCondition(word)) {
                    ifCondition();
                }
                /*else if(KeyWords.isForLoop(word)) {
                    forLoop();
                }*/
                else if(KeyWords.isWhileLoop(word)) {
                    whileLoop();
                }
                else {
                    addError(word, "多余");
                }
            }
    
            #region IF语句块
            /// <summary>
            /// if条件语句
            /// </summary>
            private void ifCondition() {
                //(
                Word word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.left_bracket.typeNum) {
                    addError(word, "(缺失");
                    wordStream.retractWord();
                }
    
                List<FourFormula> trueList = new List<FourFormula>();
                List<FourFormula> falseList = new List<FourFormula>();
                condition(trueList, falseList);
                //)
                word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.right_bracket.typeNum) {
                    addError(word, ")缺失");
                    wordStream.retractWord();
                }
    
                backPatch(trueList, getNextCodeLine());//回填true分支地址
    
                word = wordStream.ReadNextWord();
                if(word.typeNum == Symbols.left_curly_bracket.typeNum) {//语句块
                    statementSequence();
                    word = wordStream.ReadNextWord();
                    if(word.typeNum != Symbols.right_curly_bracket.typeNum) {
                        addBeforeError(word, "缺少右花括号");
                        wordStream.retractWord();
                    }
                }
                else {
                    statement(word);
                }
                FourFormula f=addFourFormula();//true分支结束跳转
                backPatch(falseList, getNextCodeLine());//回填false分支地址
                elseCondition();//else语句
                backPatch(f, getNextCodeLine());
            }
    
            
    
            /// <summary>
            /// else语句
            /// </summary>
            private void elseCondition() {
                Word word = wordStream.ReadNextWord();
                if(word.typeNum != KeyWords.ELSE.typeNum) {
    
                    wordStream.retractWord();
                    return;
                }
                word = wordStream.ReadNextWord();
                if(word.typeNum == Symbols.left_curly_bracket.typeNum) {
                    statementSequence();
                    word = wordStream.ReadNextWord();
                    if(word.typeNum != Symbols.right_curly_bracket.typeNum) {
                        addBeforeError(word, "缺少右花括号");
                        wordStream.retractWord();
                    }
                }
                else {
                    statement(word);
                }
            }
            #endregion
    
            /// <summary>
            /// for循环
            /// </summary>
            private void forLoop() {
    
            }
    
            /// <summary>
            /// while循环
            /// </summary>
            private void whileLoop() {
                //(
                Word word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.left_bracket.typeNum) {
                    addError(word, "(缺失");
                    wordStream.retractWord();
                }
    
                int startCode = getNextCodeLine();
    
                List<FourFormula> trueList = new List<FourFormula>();
                List<FourFormula> falseList = new List<FourFormula>();
                condition(trueList, falseList);
    
                //)
                word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.right_bracket.typeNum) {
                    addError(word, ")缺失");
                    wordStream.retractWord();
                }
    
                backPatch(trueList, getNextCodeLine());//回填true分支地址
                
                word = wordStream.ReadNextWord();
                if(word.typeNum == Symbols.left_curly_bracket.typeNum) {//语句块
                    statementSequence();
                    word = wordStream.ReadNextWord();
                    if(word.typeNum != Symbols.right_curly_bracket.typeNum) {
                        addBeforeError(word, "缺少右花括号");
                        wordStream.retractWord();
                    }
                }
                else {
                    statement(word);
                }
                Word w = new Word();
                w.word = "" + startCode;
                addFourFormula(w, null, null, null);
                backPatch(falseList, getNextCodeLine());
            }
    
            /// <summary>
            /// 条件语句
            /// </summary>
            private void condition(List<FourFormula> trueList, List<FourFormula> falseList) {
                boolExpressStatement(trueList, falseList);
                
            }
    
            /// <summary>
            /// 获取下一行地址编号
            /// </summary>
            /// <returns></returns>
            private int getNextCodeLine() {
                return list.Count;
            }
    
            /// <summary>
            /// 回填跳转位置
            /// </summary>
            /// <param name="size"></param>
            private void backPatch(List<FourFormula> indexs, int row) {
                foreach(FourFormula f in indexs) {
                    f.result = new Word();
                    f.result.word = "" + row;
                    // getNextLine();
                }
                indexs.Clear();
            }
    
            private void backPatch(FourFormula f, int row) {
                f.result = new Word();
                f.result.word = "" + row;
            }
    
            /// <summary>
            /// 定义语句
            /// </summary>
            private void defineStatement() {
                Word word = wordStream.ReadNextWord();
                if(!isIdentifier(word)) {
                    addBeforeError(word, "变量名缺失");
                    wordStream.retractWord();
                }
                word = wordStream.ReadNextWord();
                if(word.typeNum == Symbols.assign.typeNum) {
    
                    addFourFormula(wordStream.LastWord(), expressStatement(), null, null);
                    word = wordStream.ReadNextWord();
                }
    
                if(word.typeNum == Symbols.comma.typeNum) {
                    defineStatement();
                }
                else if(word.typeNum != Symbols.semicolon.typeNum) {
                    addBeforeError(word, ";缺失");
                    wordStream.retractWord();
                }
    
            }
    
            /// <summary>
            /// 赋值语句
            /// </summary>
            private void assignStatement() {
    
                Word result = wordStream.NowWord();
                Word word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.assign.typeNum) {
                    addBeforeError(word, "=缺失");
                    wordStream.retractWord();
                }
                Word arg1 = expressStatement();
                addFourFormula(result, arg1, null, null);
                word = wordStream.ReadNextWord();
                if(word.typeNum != Symbols.semicolon.typeNum) {
                    addBeforeError(word, ";缺失");
                    wordStream.retractWord();
                }
    
            }
    
            #region 表达式解析
            /// <summary>
            /// 表达式
            /// </summary>
            private Word expressStatement() {
                Word express, arg1, arg2;       
                arg1 = express = term();          
                Word word = wordStream.ReadNextWord();
                while(word.typeNum == Symbols.add.typeNum
                    || word.typeNum == Symbols.sub.typeNum) {
                    arg2 = term();
                    express = createTempVar();
                    express = createTempVar();
                    addFourFormula(express, arg1, arg2, word);
                    arg1 = express;
                    word = wordStream.ReadNextWord();
                }
                wordStream.retractWord();
    
                return express;
            }
            /// <summary>
            /// 项
            /// </summary>
            /// <returns></returns>
            private Word term() {
                Word term, arg1, arg2;       
                term = factor();
                arg1 = term;
                Word word = wordStream.ReadNextWord();
                while(word.typeNum == Symbols.mul.typeNum
                    || word.typeNum == Symbols.except.typeNum
                    || word.typeNum == Symbols.remain.typeNum) {
                    arg2 = factor();
                    term = createTempVar();
                    addFourFormula(term, arg1, arg2, word);
                    arg1 = term;
                    word = wordStream.ReadNextWord();
                }
                wordStream.retractWord();
                return term;
            }
    
            /// <summary>
            /// 表达式因子
            /// </summary>
            private Word factor() {
                Word factor = null;
                Word word = wordStream.ReadNextWord();
                if(isValue(word)) {
                    factor = word;
                }
                else if(word.typeNum == Symbols.left_bracket.typeNum) {
                    factor = expressStatement();
                    word = wordStream.ReadNextWord();
                    if(word.typeNum != Symbols.right_bracket.typeNum) {
                        addBeforeError(word, ")缺失");
                        wordStream.retractWord();
                    }
                }
                else {
                    addBeforeError(word, "表达式错误");
                    wordStream.retractWord();
                    //throw new Exception(); 
                }
    
                return factor;
            }
            #endregion
    
            #region 布尔表达式
            /// <summary>
            /// 表达式
            /// </summary>
            private void boolExpressStatement(List<FourFormula> trueList, List<FourFormula> falseList) {
                boolTerm(trueList, falseList);
                Word word = wordStream.ReadNextWord();
                while(word.typeNum == Symbols.logic_or.typeNum) {
                    backPatch(falseList, getNextCodeLine());
                    boolTerm(trueList, falseList);                               
                    word = wordStream.ReadNextWord();
                }
                wordStream.retractWord();
    
            }
            /// <summary>
            /// 项
            /// </summary>
            /// <returns></returns>
            private void boolTerm(List<FourFormula> trueList, List<FourFormula> falseList) {
                    
                boolFactor(trueList, falseList);
               
                Word word = wordStream.ReadNextWord();
                while(word.typeNum == Symbols.logic_and.typeNum) {
                    backPatch(trueList, getNextCodeLine());
                    boolFactor(trueList, falseList);
                    word = wordStream.ReadNextWord();
                }
                wordStream.retractWord();
               
            }
    
            /// <summary>
            /// 表达式因子
            /// </summary>
            private void boolFactor(List<FourFormula> trueList, List<FourFormula> falseList) {
    
                Word word = wordStream.ReadNextWord();
                if(isValue(word)) {
                    wordStream.retractWord();
                    boolRelation(trueList,falseList);             
                }
                else if(word.typeNum == Symbols.left_bracket.typeNum) {
                    if(isExpress()) {
                        wordStream.retractWord();
                        boolRelation(trueList, falseList);
                    }
                    else {
                        boolExpressStatement(trueList, falseList);
                        word = wordStream.ReadNextWord();
                        if(word.typeNum != Symbols.right_bracket.typeNum) {
                            addBeforeError(word, ")缺失");
                            wordStream.retractWord();
                        }
                    }
                    
                }
                else if(word.typeNum == Symbols.logic_not.typeNum) {
                    boolExpressStatement(falseList,trueList);
                }
                else{
                    addBeforeError(word, "布尔表达式错误");
                    wordStream.retractWord();
                    //throw new Exception(); 
                }
    
               
            }
    
            private bool isExpress() {
                int left = 1;
                int right = 0;
                int words = 1;
                Word word = wordStream.ReadNextWord();
                while(Symbols.isExpressSymbol(word)) {
                    if(word.typeNum == Symbols.left_bracket.typeNum) {
                        left++;
                    }
                    else if(word.typeNum == Symbols.right_bracket.typeNum) {
                        right++;
                    }
                    word = wordStream.ReadNextWord();
                    words++;
                }
                wordStream.retractWord(words);
                return left==right;
            }
    
            /// <summary>
            /// 关系表达式或布尔值
            /// </summary>
            /// <param name="trueList"></param>
            /// <param name="falseList"></param>
            private void boolRelation(List<FourFormula> trueList, List<FourFormula> falseList) {
                Word word = expressStatement();
                Word word2 = null;
                Word op = wordStream.ReadNextWord();
                if(Symbols.isCompareOperator(op)) {
                    word2 = expressStatement();
                    if(word2 == null) {
                        return ;
                    }
                }
                else{
                    wordStream.retractWord();
                     op = new Word();
                }            
                
                FourFormula f = addFourFormula(null, word, word2, op);
                trueList.Add(f);
                f = addFourFormula();
                falseList.Add(f);
                
            }
    
    
            #endregion
    
            /// <summary>
            /// 判断是否是数值变量类型
            /// </summary>
            /// <param name="word"></param>
            /// <returns></returns>
            private bool isValue(Word word) {
                return word.typeNum == WordPicker.numberTypeNumber
                    || word.typeNum == WordPicker.identifierTypeNumber
                    || word.typeNum == WordPicker.charTypeNumber
                    || word.typeNum == WordPicker.stringTypeNumber;
            }
    
            #region 添加四元式
            List<FourFormula> list = new List<FourFormula>();
            /// <summary>
            /// 保存四元式
            /// </summary>
            private FourFormula addFourFormula(Word result, Word arg1, Word arg2, Word op) {
                FourFormula fourFormula = new FourFormula();
                fourFormula.result = result;
                fourFormula.arg1 = arg1;
                fourFormula.arg2 = arg2;
                fourFormula.operate = op;
                fourFormula.codeRow = list.Count;
                list.Add(fourFormula);
                return fourFormula;
            }
            private FourFormula addFourFormula() {
                FourFormula fourFormula = new FourFormula();
                fourFormula.codeRow = list.Count;
                list.Add(fourFormula);
                return fourFormula;
            }
            #endregion
    
            int idNameCount = 0;
            /// <summary>
            /// 创建临时变量
            /// </summary>
            /// <returns></returns>
            public Word createTempVar() {
                Word word = new Word();
                word.word = "$T" + idNameCount++;
                word.typeNum =WordPicker.tempValTypeNumber;
                return word;
            }
             
    
            #region 输出错误
            bool success = true;//语法解析结果
            /// <summary>
            /// 输出在特定之前的错误
            /// </summary>
            /// <param name="word"></param>
            /// <param name="v"></param>
            private void addBeforeError(Word word, string v) {
                success = false;
                Console.WriteLine("error:" + word.ToPositionInfo() + "\t在该字之前" + v);
            }
            /// <summary>
            /// 输出错误
            /// </summary>
            /// <param name="word"></param>
            /// <param name="v"></param>
            private void addError(Word word, string v) {
                success = false;
                Console.WriteLine("error:" + word.ToPositionInfo() + "\t" + v);
            }
            #endregion
    
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CLanguage {
        /// <summary>
        /// 四元式
        /// </summary>
        class FourFormula {
    
            public int codeRow;
            public Word result;
            public Word arg1;
            public Word operate;
            public Word arg2;
    
            public override string ToString() {
                string s = "(" + codeRow + ") ";
                //赋值
                if(result.typeNum>0) {
                    s = s + result.word + " = " + arg1.word;
                    if(operate != null) {
                        s +=" "+ operate.word;
                    }
                    if(arg2 != null) {
                        s += " " + arg2.word;
                    }
                }
                else if(operate == null) {//直接跳转
                    s += "goto (" + result.word + ")";
                }
                else {//条件跳转
                    s = s + "if " + arg1.word;
                   if(operate.word!=null) {
                     s += " " + operate.word + " " + arg2.word;
                   }
                    s += "  goto (" + result.word + ")";
                }
    
    
                return s;
            }
        }
    
    }
    
    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Threading.Tasks;
    
    namespace CLanguage {
        /// <summary>
        /// 词
        /// </summary>
        class Word {
            public int typeNum=0;
            public string word;
            public int col=0;
            public int row=0;
            public override string ToString() {
                return "(" + typeNum + "," + word + ")";
            }
            public string ToPositionInfo() {
                return "行:"+(row+1)+"\t列:"+col+"\t码:"+typeNum + "\t字:" + word;
            }
        }
        
    
        class WordPicker {
       
            string[] input;
            //int input_index = 0;
            int row = 0;
            int col = 0;
            char character;
           
            /// <summary>
            /// 操作符表
            /// </summary>    
            string[] operatorSort = null;
    
            public static int identifierTypeNumber;    //变量名类型
            public static int numberTypeNumber;        //数值类型
            public static int charTypeNumber;          //字符类型
            public static int stringTypeNumber;        //字符串类型
            public static int endTypeNumber = -1;      //结束符类型
            public static int errorTypeNumber = -2;    //出错类型
            public static int noDefine = -3;           //未定义类型
            public static char nullChar = '\0';
            public static int tempValTypeNumber;      //临时变量类型
            public WordPicker(string file) {
                input= File.ReadAllLines(file);           
                identifierTypeNumber = KeyWords.keyWordTable.Length+1;
                numberTypeNumber = KeyWords.keyWordTable.Length + 2;
                charTypeNumber = KeyWords.keyWordTable.Length + 3;
                stringTypeNumber = KeyWords.keyWordTable.Length + 4;
                tempValTypeNumber= KeyWords.keyWordTable.Length + 5;
    
                operatorSort = new string[Symbols.operatorTable.Length];
                Array.Copy(Symbols.operatorTable, operatorSort, Symbols.operatorTable.Length);
                Array.Sort(operatorSort);
                Array.Reverse(operatorSort);
            }
    
    
    
            /// <summary>
            /// 读词
            /// </summary>
            /// <returns></returns>
            public Word Scanner() {
                Word myWord;          
                read();
                readValidChar();
                //标识符
                if(char.IsLetter(character)) {
                    myWord=readWord();
                }//数值
                else if(char.IsDigit(character)) {
                    myWord = readDigit();
                }//字符常量
                else if(character == '\'') {
                    myWord = readConstChar();
                }//字符串
                else if(character == '\"') {
                    myWord = readConstString();
                }/*//结束符
                else if(character == endChar) {
                    myWord.word = "" + endChar;
                    myWord.typeNum = endTypeNumber;
                }*///空值
                else if(character == nullChar) {
                    myWord = new Word();
                    myWord.row = row;
                    myWord.col = col;
                    myWord.word = "Ending";
                    myWord.typeNum = endTypeNumber;
                }//其他字符
                else {
                    myWord = readOtherChar();
                }
                return myWord;
    
            }
    
            /// <summary>
            /// 标识符
            /// </summary>
            /// <param name="myWord"></param>
            private Word readWord() {
                Word myWord = new Word();
                myWord.row = row;
                myWord.col = col;
                while(char.IsLetter(character) || char.IsDigit(character)) {
                    myWord.word += character;
                    read();
                }
                retract();
                myWord.typeNum = KeyWords.getTypeNumber(myWord.word);
                return myWord;
            }
    
            /// <summary>
            /// 其他字符
            /// </summary>
            /// <param name="myWord"></param>
            private Word readOtherChar() {
                Word myWord = new Word();
                myWord.row = row;
                myWord.col = col;
                string s = "" + character;
                for(int i = 0; i < 2; i++) {
                    read();
                    if(character == nullChar) {
                        break;
                    }
                    s += character;
                }
                foreach(string op in operatorSort) {
                    if(s.StartsWith(op)) {
                        retract(s.Length - op.Length);
                        s = op;
                        break;
                    }
                }
                myWord.word = s;
                myWord.typeNum = Symbols.getTypeNumber(myWord.word);
                return myWord;
            }
    
            /// <summary>
            /// 识别数字常量
            /// </summary>
            /// <param name="myWord"></param>
            private Word readDigit() {
                Word myWord = new Word();
                myWord.row = row;
                myWord.col = col;
                while(char.IsDigit(character)) {
                    myWord.word += character;
                    read();
                }
                if(character == '.') {
                    myWord.word += character;
                    read();
                    while(char.IsDigit(character)) {
                        myWord.word += character;
                        read();
                    }
                }
                retract();
                myWord.typeNum = numberTypeNumber;
                 return myWord;
            }
    
            /// <summary>
            /// 识别字符常量
            /// </summary>
            /// <param name="myWord"></param>
            private Word readConstChar() {
                Word myWord = new Word();
                myWord.row = row;
                myWord.col = col;
                // myWord.word = "" + character;
                read();
                //读取直到'\''结束
                while(character != '\'') {
                    myWord.word += character;
                    read();
                    //读到空字符或结束字符
                    if(character == nullChar /*|| character == endChar*/|| char.IsControl(character)) {
                        /* if(character == endChar) {
                             myWord.word +=endChar;
                         } */
                        myWord.typeNum = errorTypeNumber;
                        return myWord;
                    }
                }
                // myWord.word += character;
                Match r = Regex.Match(myWord.word, "^(\\\\([0-7]{1,3}|x[0-9a-fA-F]+|[abfnrtv\\\\\'\"?])|[^\\\\])$");
                //转义字符模式匹配
                if(!r.Success) {
                    myWord.typeNum = errorTypeNumber;
                    return myWord;
                }
                myWord.typeNum = charTypeNumber;
                return myWord;
    
            }
            /// <summary>
            /// 识别常量字符串
            /// </summary>
            /// <param name="myWord"></param>
            private Word readConstString() {
                Word myWord = new Word();
                myWord.row = row;
                myWord.col = col;
                // myWord.word = "" + character;
                read();
                while(character != '\"') {
                    myWord.word += character;
                    read();
                    //读到空字符或结束字符
                    if(character == nullChar || char.IsControl(character)) {
                        // myWord.word += "0";
                        myWord.typeNum = errorTypeNumber;
                        return myWord;
                    }
                }
                // myWord.word += character;
    
                //转义字符模式匹配
                if(!isLegalString(myWord.word)) {
                    myWord.typeNum = errorTypeNumber;
                    return myWord;
                }
                myWord.typeNum = stringTypeNumber;
                return myWord;
            }
    
            /// <summary>
            /// 合法字符串书写
            /// </summary>
            /// <param name="word"></param>
            /// <returns></returns>
            private bool isLegalString(string word) {
    
                int i = 0;
                while(i < word.Length) {
                    if(word[i] == '\\') {
                        if(++i == word.Length)
                            return false;
                        foreach(char c in translateChar) {
                            if(c == word[i]) {
                                goto aLabel;
                            }
                        }
                        return false;
                    }
                aLabel:
                    i++;
                }
    
                return true;
            }
    
            const string translateChar = "abfnrtv\\\'\"?";
            const string realChar = "\a\b\f\n\r\t\v\\\'\"?";
    
           
    
            /// <summary>
            /// 转换为真实字符串
            /// </summary>
            /// <param name="word"></param>
            /// <returns></returns>
            private string toRealString(string word) {
                string res = "";
                int index;
                for(int i = 0; i < word.Length; i++) {
                    if(word[i] == '\\') {
                        if(++i == word.Length)
                            throw new Exception("字符串以\\结尾异常");
    
                        index = translateChar.IndexOf(word[i]);
                        if(index == -1)
                            throw new Exception("\\" + word[i] + "解析异常");
                        res += realChar[index];
                    }
                    else {
                        res += word[i];
                    }
                }
                return res;
            }
    
            /// <summary>
            /// 读一个字符
            /// </summary>
            void read() {
                if(input.Length <= row|| input.Length == row+1 && input[input.Length-1].Length<=col) {
                    character = '\0';
                }
                else {
                    if(col >= input[row].Length) {
                        col = 0;
                        row++;
                    }
                    character = input[row][col];
                    col++;
                }
                    
            }
    
            /// <summary>
            /// 去除无效字符
            /// </summary>
            void readValidChar() {
    
                while(char.IsWhiteSpace(character)) {
                    if(character == '\0') {
                        return;
                    }
                    read();              
                }
                //判断注释
                if(character == '/' && input[row].Length > col) {
                    ignoreNote();
                }
            }
    
            /// <summary>
            /// 忽视注解
            /// </summary>
            private void ignoreNote() {
                read();
                //注释‘//’
                if(character == '/') {
                    row++;
                    col = 0;                              
                    read();
                    readValidChar();
                }//注释‘/*。。。*/’
                else if(character == '*') {
                   
                    read();
                    if(character == '\0') {
                        return;
                    }
                    char c;
                    while(true) {
                        
                        c = character;
                        read();
                        if('*' == c && '/' == character) {
                            read();
                            readValidChar();
                            return;
                        }
                        if(character == '\0') {
                            return;
                        }                
                    }
                }
                else {
                    retract();
                }
            }
     
            /// <summary>
            /// 回退一个字符
            /// </summary>
            void retract() {            
                col=col-2;
                checkCol();
                read();
            }
    
            /// <summary>
            /// 回退v个字符
            /// </summary>
            /// <param name="v"></param>
            private void retract(int v) {
                if(v == 0)
                    return;
                col = col - v - 1;
                checkCol();
                read();
            }
    
            /// <summary>
            /// 检查col是否合法
            /// </summary>
            void checkCol() {
                if(col < 0) {
                    row--;
                    col = input[row].Length + col;
                    checkCol();
                }
            }
    
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Reflection;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CLanguage {
        class KeyWords {
            /// <summary>
            /// 关键字表
            /// </summary>
            public static string[] keyWordTable = {
                "auto","break","case", "char","const",
                "continue","default","do","double",
                "else","enum","extern","float","for",
                "goto","if", "int","long", "register",
                "return","short","signed","sizeof","static",
                "struct","switch","typedef","union","unsigned",
                "void","volatile","while"};
    
            public static Word AUTO, BREAK, CASE, CHAR, CONST,
            CONTINUE, DEFAULT, DO, DOUBLE,
            ELSE, ENUM, EXTERN, FLOAT, FOR,
            GOTO, IF, INT, LONG, REGISTER,
            RETURN, SHORT, SIGNED, SIZEOF, STATIC,
            STRUCT, SWITCH, TYPEDEF, UNION, UNSIGNED,
            VOID, VOLATILE, WHILE;
    
            static KeyWords() {
                Type t = typeof(KeyWords);
    
                FieldInfo[] fields = t.GetFields();
                Word word;
                foreach(FieldInfo f in fields)
                    if(f.FieldType.Equals(typeof(Word))) {
                        word = new Word();
                        word.word = f.Name.ToLower();
                        word.typeNum = getTypeNumber(word.word);
                        f.SetValue(t, word);
                    }
            }
            /// <summary>
            /// 获取关键字编码
            /// </summary>
            /// <returns></returns>
            public static int getTypeNumber(string s) {
                for(int i = 0; i < keyWordTable.Length; i++) {
                    if(keyWordTable[i] == s) {
                        return i+1;
                    }
                }
    
                return WordPicker.identifierTypeNumber;
            }
    
            public static bool isPrefType(Word w) {
                return SIGNED.typeNum == w.typeNum
                   || UNSIGNED.typeNum == w.typeNum;
            }
            public static bool isType(Word w) {
                return INT.typeNum == w.typeNum
                    || CHAR.typeNum == w.typeNum
                    || DOUBLE.typeNum == w.typeNum
                    || FLOAT.typeNum == w.typeNum
                    || SHORT.typeNum == w.typeNum;               
            }
    
            public static bool isReturnType(Word w) {
                return isType(w) || VOID.typeNum == w.typeNum;
            }
    
            internal static bool isIfCondition(Word word) {
                return word.typeNum == IF.typeNum;
            }
    
            internal static bool isForLoop(Word word) {
                return word.typeNum == FOR.typeNum;
            }
    
            internal static bool isWhileLoop(Word word) {
                return word.typeNum == WHILE.typeNum;
            }
    
            internal static bool isDoLoop(Word word) {
                return  word.typeNum == DO.typeNum;
            }
    
            internal static bool isKeyWord(Word word) {
                return word.typeNum > 0 && word.typeNum <= keyWordTable.Length;
            }
    
           
        }
        class Symbols {
            public static string[] operatorTable = {
                "{","}","[","]","(",")","->",".",
                "++","--",
                "!","&&","||",
                "~","&","|","^",
                "+","-","*","/","%",
                "<<",">>",
                "<",">",">=","<=",
                "==","!=","?",":",",",";",
                "=","+=","-=","*=","/=","%=",
                "&=","^=","|=","<<=",">>="
            };
    
            public static Word left_curly_bracket, right_curly_bracket,
                left_square_bracket, right_square_bracket,
                left_bracket, right_bracket,
                arrow, point, two_add, two_sub,
                logic_not, logic_and, logic_or,
                bitwise_not, bitwise_and, bitwise_or, bitwise_xor,
                add, sub, mul, except, remain,
                left_move, right_move,
                less, greater, greater_equal, less_equal,
                equal, not_equal, question_mark, colon, comma, semicolon,
                assign, add_assign, sub_assign, mul_assign, except_assign, remain_assign,
                and_assign, xor_assign, or_assign, left_move_assign, right_move_assign;
    
            internal static bool isSemicolo(Word word) {
                return word .typeNum == semicolon.typeNum;
            }
    
            static Symbols() {
                Type t = typeof(Symbols);
    
                FieldInfo[] fields = t.GetFields();
                Word word;
                int index = 0;
                foreach(FieldInfo f in fields)
                    if(f.FieldType.Equals(typeof(Word))) {
                        word = new Word();
                        word.word = operatorTable[index++];
                        word.typeNum = getTypeNumber(word.word);
                        f.SetValue(t, word);
                    }
            }
    
            public static int getTypeNumber(string s) {
                int start = 100;
                for(int i = 0; i < operatorTable.Length; i++) {
                    if(operatorTable[i] == s) {
                        return start + i;
                    }
                }
                return WordPicker.noDefine;
            }
            internal static bool isArithmeticOperator(Word w) {
                return w.typeNum == mul.typeNum || w.typeNum == except.typeNum
                    || w.typeNum == remain.typeNum
                    || w.typeNum == add.typeNum || w.typeNum == sub.typeNum;
            }
    
            internal static bool isCompareOperator(Word w) {
                return w.typeNum == less.typeNum || w.typeNum == greater.typeNum ||
                    w.typeNum == less_equal.typeNum || w.typeNum == greater_equal.typeNum ||
                    w.typeNum == equal.typeNum || w.typeNum == not_equal.typeNum;
            }
    
            internal static bool isExpressSymbol(Word w) {
                return w.typeNum == add.typeNum || w.typeNum == sub.typeNum
                    || w.typeNum == mul.typeNum || w.typeNum == except.typeNum|| w.typeNum == remain.typeNum 
                    || w.typeNum == left_bracket.typeNum || w.typeNum == right_bracket.typeNum
                    || w.typeNum == WordPicker.identifierTypeNumber|| w.typeNum == WordPicker.numberTypeNumber;
            }
        }
    }
    
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace CLanguage {
        /// <summary>
        /// 读词缓存流
        /// </summary>
        class WordStream {
            WordPicker wordPicker;
            List<Word> words = new List<Word>();
            int index = -1;
    
            public WordStream(string file) {
                wordPicker = new WordPicker(file);
            }
    
            /// <summary>
            /// 读取下一个词
            /// </summary>
            /// <returns></returns>
            public Word ReadNextWord() {
                index++;
                if(words.Count <= index) {
                    Word w = wordPicker.Scanner();
                    if(words.Count == 0 || words[words.Count - 1].typeNum != WordPicker.endTypeNumber)
                        words.Add(w);
                    index = words.Count - 1;
                }
                return words[index];
            }
            /// <summary>
            /// 现在的词
            /// </summary>
            /// <returns></returns>
            public Word NowWord() {
    
                if(words.Count > index && index >= 0) {
                    return words[index];
                }
                return null;
            }
            /// <summary>
            /// 上一个词
            /// </summary>
            /// <returns></returns>
            public Word LastWord() {
    
                if(index > 0) {
    
                    return words[index - 1];
                }
                else {
                    return null;
                }
    
            }
            /// <summary>
            /// 回退一个词
            /// </summary>
            public void retractWord() {
    
                if(index >= 0) {
                    index--;
                }
    
            }
            public void retractWord(int n) {
    
                if(index >= 0) {
                    index-=n;
                }
    
            }
        }
    }
    

    输入:

    void main(){
    	int first=30;	
    	int second=first*20-5;
    	int three=second*3-20;
    	if(first-second>three){
    		three=23;
    	}
    }

    输出:

    展开全文
  • 原程序分为 .cpp文件 与.h文件 运行时请分开 源程序可直接运行 源程序 已经包含了词法分析与三地址代码生成程序源代码
  • 0121210340527 学 号 课内实践报告 课程名称 编译原理 FOR循环语句的翻译程序设计简 题 目 单优先法输出三地址码 学 院 计算机科学与技术 专 业 计算机科学与技术 班 级 1201 姓 名 李潇颖 指导教师 林泓 2014 年 12...
  • 这才是正宗的,网上本搜不到,吴鹏s、b,吴丰收s、b的都是错的。
  • 要求: ...本次的题目和之前的功能很类似,都是基于SLR文法的,所有代码与之前有很多共同之处。 #include #include #include using namespace std; /* E->E+T E->T T->T*F T->F F->(E) F->id */ /

    要求:

    输入:(b+c*d+c*d

    输出:

    t1= c*d

    t2=b+t1

    t3= c*d

    t4=t2+t3

    本次的题目和之前的功能很类似,都是基于SLR文法的,所有代码与之前有很多共同之处。

    #include <iostream>
    #include <string.h>
    #include<stack>
    using namespace std;
    /*
    E->E+T
    E->T
    T->T*F
    T->F
    F->(E)
    F->id
    */
    /*初始化分析表*/
    void Initial(string analysis[12][9]){
    	/*移进规约*/
    	analysis[0][0] = "s5"; analysis[0][3] = "s4"; analysis[0][6] = "1"; analysis[0][7] = "2"; analysis[0][8] = "3";
    	analysis[1][1] = "s6"; analysis[1][5] = "acc";
    	analysis[2][1] = "r2"; analysis[2][2] = "s7"; analysis[2][4] = "r2"; analysis[2][5] = "r2";
    	analysis[3][1] = "r4"; analysis[3][2] = "r4"; analysis[3][4] = "r4"; analysis[3][5] = "r4";
    	analysis[4][0] = "s5"; analysis[4][3] = "s4"; analysis[4][6] = "8"; analysis[4][7] = "2"; analysis[4][8] = "3";
    	analysis[5][1] = "r6"; analysis[5][2] = "r6"; analysis[5][4] = "r6"; analysis[5][5] = "r6";
    	analysis[6][0] = "s5"; analysis[6][3] = "s4"; analysis[6][7] = "9"; analysis[6][8] = "3";
    	analysis[7][0] = "s5"; analysis[7][3] = "s4"; analysis[7][8] = "10";
    	analysis[8][1] = "s6"; analysis[8][4] = "ss";//s11
    	analysis[9][1] = "r1"; analysis[9][2] = "s7"; analysis[9][4] = "r1"; analysis[9][5] = "r1";
    	analysis[10][1] = "r3"; analysis[10][2] = "r3"; analysis[10][4] = "r3"; analysis[10][5] = "r3";
    	analysis[11][1] = "r5"; analysis[11][2] = "r5"; analysis[11][4] = "r5"; analysis[11][5] = "r5";
    	/*出现错误*/
    	analysis[0][1] = analysis[0][2] = analysis[0][5] = analysis[4][1] = analysis[4][2] = analysis[4][5] = "e1";
    	analysis[6][1] = analysis[6][2] = analysis[6][5] = analysis[7][1] = analysis[7][2] = analysis[7][5] = "e1";
    	analysis[0][4] = analysis[1][4] = analysis[4][4] = analysis[6][4] = analysis[7][4] = "e2";
    	analysis[1][0] = analysis[1][2] = analysis[1][3] = analysis[8][0] = analysis[8][2] = analysis[8][3] = "e3";
    	analysis[8][5] = "e4";
    	analysis[2][0] = analysis[2][3] = "r2";
    	analysis[3][2] = analysis[3][3] = "r4";
    	analysis[5][0] = analysis[5][3] = "r6";
    	analysis[9][0] = analysis[9][3] = "r1";
    	analysis[10][0] = analysis[10][3] = "r3";
    	analysis[11][0] = analysis[11][3] = "r5";
    
    }
    /*输出移进还是规约,规约的话输出用到的产生式*/
    void print(int into)
    {
    	if (into == 0)
    	{
    		cout << "--移进--" << endl;
    		return;
    	}
    	cout << "--按";
    	switch (into)
    	{
    	case 1:cout << "E->E+T"; break;
    	case 2:cout << "E->T"; break;
    	case 3:cout << "T->T*F"; break;
    	case 4:cout << "T->F"; break;
    	case 5:cout << "F->(E)"; break;
    	case 6:cout << "F->id"; break;
    	}
    	cout << "规约--" << endl;
    }
    /*为终结符合非终结符编号*/
    int NumOfSymbols(char c){
    	/*switch (c){
    	case 'a':return 0;
    	case '+':return 1;
    	case '*':return 2;
    	case '(':return 3;
    	case ')':return 4;
    	case '#':return 5;
    	case 'E':return 6;
    	case 'T':return 7;
    	case 'F':return 8;
    	}*/
    	if (c == 'a'){ return 0; }
    	if (c == '+'){ return 1; }
    	if (c == '*'){ return 2; }
    	if (c == '('){ return 3; }
    	if (c == ')'){ return 4; }
    	if (c == '$'){ return 5; }
    	if (c == 'E'){ return 6; }
    	if (c == 'T'){ return 7; }
    	if (c == 'F'){ return 8; }
    }
    char GetSymbol(int num){
    	if (num == 0){ return 'a'; }
    	if (num == 1){ return '+'; }
    	if (num == 2){ return '*'; }
    	if (num == 3){ return '('; }
    	if (num == 4){ return ')'; }
    	if (num == 5){ return '$'; }
    	if (num == 6){ return 'E'; }
    	if (num == 7){ return 'T'; }
    	if (num == 8){ return 'F'; }
    }
    char sym[20];//把所有的符号,除了+*()$依顺序放进数组
    /*将表达式从(a+b*c)+d*e的形式转换到(a+a*a)+a*a的形式才能进行SLR分析*/
    char *Change(char* str){
    	int len = strlen(str);
    	int curr = 0;
    	char * change = new char [len];
    	for (int i = 0; i < len; i++){
    		if (str[i] != '(' && str[i] != ')' && str[i] != '+' && str[i] != '*' && str[i] != '$'){
    			change[i] = 'a';
    			sym[curr] = str[i];
    			curr++;
    		}
    		else{
    			change[i] = str[i];
    		}
    	}
    	return change;
    }
    void main(){
    	string analysis[12][9];
    	stack<int> s;
    	stack<char> symstack;
    	int curr = 0;
    	char t = 49;
    	char* input = "((a*c*d)+c*d)$";
    	int len = strlen(input);
    	cout << "输入表达式:" << input << endl;
    	char *str = new char[len];
    	str=Change(input);
    	//cout << "化成LR文法可识别的形式为:" << str << endl;	
    	Initial(analysis);
    	s.push(0);
    	/*循环中i表示当前处理得输入串中的角标*/
    	for (int i = 0; i < len;){
    		int stack_top = s.top();//记录栈顶状态
    		//cout << "此时栈定状态为:" << stack_top;
    		//cout << "  此时输入字符为:" << str[i] << endl;
    		int lookahead = NumOfSymbols(str[i]);//记录当前输入串中,正在被处理的字符的标号
    		/*移进*/
    		if (analysis[stack_top][lookahead][0] == 's'){
    			if (analysis[stack_top][lookahead][1] == 's'){
    				//print(0);
    				s.push(lookahead);
    				s.push(11);
    				//cout << "将状态11移进栈。" << endl;
    				i++;
    			}
    			else{
    				//print(0);
    				s.push(lookahead);
    				s.push(analysis[stack_top][lookahead][1] - '0');
    				//cout << "将状态" << analysis[stack_top][lookahead][1] - '0' << "移进栈。" << endl;
    				i++;//移进了一个后,就可以看下一个字符了  
    			}
    		}
    		/*规约*/
    		else if (analysis[stack_top][lookahead][0] == 'r'){
    			int times;//如需规约,弹栈的次数
    			int NumofNon_Terminal;//需要移进栈的终结符的编号
    			//print(analysis[stack_top][lookahead][1] - '0');//输出规约的式子
    			switch (analysis[stack_top][lookahead][1] - '0'){
    			case 1: times = 6; NumofNon_Terminal = NumOfSymbols('E'); break;
    			case 2: times = 2; NumofNon_Terminal = NumOfSymbols('E'); break;
    			case 3: times = 6; NumofNon_Terminal = NumOfSymbols('T'); break;
    			case 4: times = 2; NumofNon_Terminal = NumOfSymbols('T'); break;
    			case 5: times = 6; NumofNon_Terminal = NumOfSymbols('F'); break;
    			case 6: times = 2; NumofNon_Terminal = NumOfSymbols('F'); break;
    			}
    			for (int j = 0; j < times; j++){
    				s.pop();
    			}
    			int pre_top = s.top();//记录此时的栈顶
    			//cout << "弹栈" << times << "次后,栈顶状态为" << pre_top << endl;
    			s.push(NumofNon_Terminal);
    			char c = GetSymbol(NumofNon_Terminal);//为了输出字符,通过序号找到
    			//cout << "放入" << c << endl;
    			if (analysis[pre_top][NumofNon_Terminal].size() == 1){
    				s.push(analysis[pre_top][NumofNon_Terminal][0] - '0');
    				//cout << "将状态" << analysis[pre_top][NumofNon_Terminal][0] - '0' << "移进栈。" << endl;
    			}
    			else{
    				s.push(10);
    				//cout << "将状态10移进栈。" << endl;
    			}
    			/*为了能输出t1、t2这样的样式做了如下处理*/
    			if (analysis[stack_top][lookahead][1] - '0' == 1){
    				char temp1 = symstack.top();
    				symstack.pop();
    				char temp2 = symstack.top();
    				symstack.pop();
    				symstack.push(t);
    				if (temp1 > 58 && temp2 > 58){
    					cout << "t" << t << "=" << temp2 << "+" << temp1 << endl;
    					t++;
    				}
    				if (temp1 < 58 && temp2 > 58){
    					cout << "t" << t << "=" << temp2 << "+" << "t" << temp1 << endl;
    					t++;
    				}
    				if (temp1 > 58 && temp2 < 58){
    					cout << "t" << t << "=" << "t" << temp2 << "+" << temp1 << endl;
    					t++;
    				}
    				if (temp1 < 58 && temp2 < 58){
    					cout << "t" << t << "=" << "t" << temp2 << "+" << "t" << temp1 << endl;
    					t++;
    				}
    			}
    			if (analysis[stack_top][lookahead][1] - '0' == 3){
    				char temp1 = symstack.top();
    				symstack.pop();
    				char temp2 = symstack.top();
    				symstack.pop();
    				symstack.push(t);
    				if (temp1 > 58 && temp2 > 58){
    					cout << "t" << t << "=" << temp2 << "*" << temp1 << endl;
    					t++;
    				}
    				if (temp1 < 58 && temp2 > 58){
    					cout << "t" << t << "=" << temp2 << "*" << "t" << temp1 << endl;
    					t++;
    				}
    				if (temp1 > 58 && temp2 < 58){
    					cout << "t" << t << "=" << "t" << temp2 << "*" << temp1 << endl;
    					t++;
    				}
    				if (temp1 < 58 && temp2 < 58){
    					cout << "t" << t << "=" << "t" << temp2 << "*" << "t" << temp1 << endl;
    					t++;
    				}
    			}
    			if (analysis[stack_top][lookahead][1] - '0' == 6){
    				symstack.push(sym[curr]);
    				curr++;
    				//cout << "放入" << symstack.top() << endl;
    			}
    		}
    		/*错误恢复*/
    		else if (analysis[stack_top][lookahead][0] == 'e'){
    			cout << "出现错误" << endl;
    			switch (analysis[stack_top][lookahead][1]){
    			case '1':{   //期望遇到a,那就把a放进去
    						 s.push(0);
    						 s.push(5);
    						 cout << "缺少运算符,加入a" << endl;
    						 break;
    			}
    			case '2':{
    						 //遇见右括号,没有左括号,说明右括号错误
    						 i++;
    						 cout << "不匹配的右括号,将忽略该字符" << endl;
    						 break;
    			}
    			case '3':{
    						 //期望遇见运算符,加进+
    						 s.push(1);
    						 s.push(6);
    						 cout << "缺少运算符,加入a" << endl;
    						 break;
    			}
    			case '4':{
    						 //提前结束,但期望遇见右括号,那就加入有括号
    						 s.push(4);
    						 s.push(11);
    						 cout << "缺少右括号" << endl;
    						 break;
    			}
    			}
    		}
    		else{
    			if (analysis[stack_top][lookahead][0] == 'a'){
    				cout << "接受" << endl;
    				return;
    			}
    			else{
    				cout << "无法识别,完蛋了!" << endl;
    				return;
    			}
    		}
    
    		//cout << "--------------------------------------" << endl;
    	}
    }


    展开全文
  • while循环语句的翻译程序设计(简单优先 三地址)很强大的程序
  • 这是一个关于C语言的一个编译器设计的一部分,生成了三地址中间代码,C++实现。应该是不错的,您下了不后悔。
  • 包括代码及报告 输出三地址为goto语句那种,非三元式
  • 利用之前的词法和语法分析器的东西做的 具体要求见word文档 用turbo c3.0写的 别的应该都能打开
  • 三地址代码是由下面一般形式的语句构成的序列: x:=y op z 其中, x、y、z名字、常数或编译时产生的临时变量;op代表运算符号。 每个语句的右边只能有一个运算符。 三元式 三元式主要由三部分组成: (OP,arg...

    三地址语句的具体实现

    三地址代码是由下面一般形式的语句构成的序列:

    • x:=y op z

    其中, x、y、z为名字、常数或编译时产生的临时变量;op代表运算符号。

    每个语句的右边只能有一个运算符。(有重复的)

    在这里插入图片描述

    三元式

    三元式主要由三部分组成:(有重复的)

    • (OP,arg1,arg2)
      在这里插入图片描述

    间接三元式

    为了便于优化处理,作为中间代码,设一张指示器表(间接码表)
    (没有重复的)????????
    在这里插入图片描述

    四元式

    四元式主要由四部分组成:(有重复的)

    • (OP,arg1,arg2,result)

    其中,OP是运算符,argl、arg2分别是第一和第二个运算对象,result是编译程序为存放中间运算结果而引进的变量,常称为临时变量。当OP是一目运算时,常常将运算对象定义为arg1。
    在这里插入图片描述
    注意:最后一行

    • 四元式出现的顺序和语法成份的计值顺序相一致。
    • 四元式之间的联系是通过临时变量实现的,这样易于调整和变动四元式。
    • 便于优化处理。
    展开全文
  • 对编译原理中间代码生成的赋值语句的翻译,对中间代码的理解更有帮助
  • 1、问题描述 1 2、问题分析 1 3、词法分析 1 ...7.2主要的词法分析及三地址形式分析如下 6 8、软件测试方法和测试结果 10 8.1软件测试方法 10 8.2测试结果 10 9、收获与心得 13 10、参考文献 14 11、附源代码 14
  • (2) 完成题目要求的中间代码三地址表示的描述。 (3) 写出给定的语法分析方法的思想,完成语法分析和语义分析程序设计。 (4) 编制好分析程序后,设计若干用例,上机测试并通过所设计的分析程序。 (5) 设计...
  • WHILE循环语句的翻译程序设计(递归下降法、输出三地址表示 对循环语句: WHILE〈表达式〉DO〈赋值语句〉 (1) 按给定的题目写出符合自身语法分析方法要求的文法和属性文法描述。 (2) 按给定的题目给出语法分析...
  • WHILE循环语句的翻译程序设计(LL(1)法、输出三地址表示)
  • 第六章 中间代码生成 中间代码也叫中间语言(Intermediate code /...3、三地址代码 三元式、四元式、间接三元式 后缀式 6.1 声明语句的翻译 6.1.1 类型表达式 各类语句的翻译,包括声明语句、控制语句等。声明语...
  • DO-WHILE循环语句的翻译程序设计(简单优先法、输出三地址表示)
  • 即在原来语法分析的基础上插入相应的语义动作:将输入串翻译三地址代码序列。 E ® E1 + T E ® T T ® T1 * F T ® F F® (E) F ® digit F ® id 2.以词法分析和语法分析部分的上机结果基础,添加语义分析...
  • for循环语句翻译 for循环语句翻译递 归下降法 输出三地址码
  • 本文实例大家分享了C语言实现翻译功能的具体代码,供大家参考,具体内容如下 题目描述:编写一个程序,依次输入英文与汉语拼音,输入两个“ * ”表示输入结束,再输入一段英语句子,打印出其对应汉语拼音。 要求:...
  • 题目: WHILE循环语句的翻译程序设计(递归下降法、输出三地址表示) 代码格式良好,有充分的注释!!!
  • 该资源中包含了我设计的简单优先文法,以及根据文法构造的简单优先关系表,和相关的完整程序
  • 语法树AST、后缀表达式、DAG、三地址代码     抽象语法树的观点认为任何复杂的语句嵌套情况都可以借助于树的形式加以描述。确实,不得不承认应用抽象语法树可以使语句翻译变得相对容易,它很好地描述了语句、...
  • FOR循环语句的翻译程序设计(递归下降法、输出三地址表示)
  • 确定一个定义算术表达式的文法,其设计一个语法分析程序,每条产生式配备一个语义子程序,按照一遍扫描的语法制导翻译方法,实现翻译程序。对用户输入的任意一个正确的算术表达式,程序将其转换成三元式输出。
  • 包含程序和完整的实验报告,程序自己对着报告看就行

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 176,119
精华内容 70,447
关键字:

翻译为三地址代码