编译原理(四)之解析语言翻译成三地址代码

选择部分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;}#endregionint 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;}
}

输出:

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/323788.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

[北京微软技术直通车]前端 Visual Studio Code 开发 Angular 与亿级 SQL Servern

微软技术直通车第一期将于2017年9月9日与大家见面&#xff0c;本次邀请华北区微软技术专家和大家一起交流前端工具与技术&#xff0c; Visual Studio Code&#xff0c;TypeScript 与 Anuglar 项目开发和亿级数据库运维的最佳实践&#xff0c;分享相关技术的发展前景和从业经验&…

vue中如何实现全全全屏和退出全屏?

“大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂”最近总有人给我说ta有社恐&#xff0c;明明是有社牛好不好……前言在做大屏界面的时候&#xff0c;客户有个要求&#xff0c;一进去登录成功之后&#xff0c;要有全屏的功能&#xff0c;…

【深圳】掌通宝科技有限公司技术总监(兼架构师),约吗

技术总监&#xff08;兼架构师&#xff09; 岗位职责&#xff1a; 1、主持研发中心日常管理工作&#xff0c;负责公司O2O平台,SaaS平台管理&#xff1b; 2、负责公司.net后台&#xff0c;Android客户端、IOS客户端、WEB平台等架构设计&#xff1b; 4、解决开发中的技术问题…

树层级处理上万条数据优化!

“大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂。”前言项目中&#xff0c;部门数超万&#xff0c;导致页面加载价卡顿怎么办&#xff1f;使用若依自带解析树的方法在本地运行没有任何问题&#xff0c;但是一发布到服务器上就显示加载超…

Orleans解决并发之痛(三):集群

Orleans本身的设计是一个分布式的框架&#xff0c;多个Silo构成集群&#xff0c;Grains分布在多个Silo中。一旦一个Silo挂了&#xff0c;原来归属这个Silo的Grains会自动在其他Silo中激活。生产环境下还是需要以集群方式来部署。 cluster 在Orleans解决并发之痛&#xff08;二…

avue中实现消息的实时展示

“大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂。”前言一个功能写了大半天&#xff0c;主要是数据表设计的有点复杂&#xff0c;且这个项目是10月份就写的放那的&#xff0c;里面有些东西都忘记了……先看数据库结构&#xff0c;然后理…

发达国家与发展中国家编程语言技术的分布差异性

近日&#xff0c;Stack Overflow在官方博客上发布了一组统计数据&#xff0c;表明发达国家与发展中国家在编程语言技术的采用上存在较大的差异。Stack Overflow对2017年1月至8月期间的访问数据进行了分析&#xff0c;选取了64个技术标签&#xff0c;每个标签所包含问题的访问次…

两个map中的数据,按照相同键,将所对应的值相加方法

“大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂”前言最近写代码的时候遇到了个需求&#xff0c;刚开始想的时候&#xff0c;感觉不难&#xff0c;挺简单的&#xff0c;结果写的时候&#xff0c;各种思考、各种费脑&#xff0c;耗费了点…

publiccms中将推荐页的内容显示在页面片段中

遍历的代码如下&#xff1a; <#list page.list><ul><#items as a><li><figure><!-- ${a.itemType!} : ${a.itemId!} ,place/redirect:count and 301 jump to a.url,place/click:count and 302 jump to a.url--><a href"${site.dyn…

ASP.NET Core 运行原理解剖[3]:Middleware-请求管道的构成

在 ASP.NET 中&#xff0c;我们知道&#xff0c;它有一个面向切面的请求管道&#xff0c;有19个主要的事件构成&#xff0c;能够让我们进行灵活的扩展。通常是在 web.config 中通过注册 HttpModule 来实现对请求管道事件监听&#xff0c;并通过 HttpHandler 进入到我们的应用程…

publiccms实现首页菜单栏下拉的方法

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂。 今天接到了个需求&#xff0c;使用publiccms实现首页导航栏下拉的效果&#xff0c;效果如下&#xff1a; 目前我的思路如下&#xff1a; 采用分类的方法实现将左侧的项作为二级分类右边…

2017(深圳) .NET技术分享交流会(第二期)网络直播活动

.NET Core 2.0 已于2017年8月14日正式发布&#xff0c;2017(深圳) .NET技术分享交流会在公众号中发出2个小时后就被抢光了&#xff0c;受限于场地无法增加人数&#xff0c;这次如鹏网杨中科老师提供VIP级的网络直播支持&#xff0c;为了保证网络直播效果&#xff0c;另外开启网…

publiccms实现多层级选项卡效果

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 距离上次更新已经好久了~最近心有余而力不足。。 最近在学习freammarker标签&#xff0c;算是比较老的技术了&#xff0c;白天写&#xff0c;晚上做梦都在写&#xff0c;不吐槽了&am…

“雪花”项目:Microsoft探索在.NET中实现手工内存管理

来自Microsoft研究院、剑桥大学和普林斯顿大学的一些研究人员构建了一个.NET的分支&#xff0c;实现了在运行时中添加支持手工内存管理的API。研究方法的细节及所获得的性能提升发表在名为“Project Snowflake: Non-blocking Safe Manual Memory Management in .NET”&#xff…

publiccms按照指定显示的日期格式,格式化日期的写法

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 现在是2021年12月30日20:21:37&#xff0c;距离2021年结束仅仅不到2天的时间了&#xff0c;时间恍如白驹过隙&#xff01; 今天还是搞的publiccms,分享个简单的语法吧&#xff1a;在…

Orleans解决并发之痛(四):Streams

Orleans 提供了 Stream扩展编程模型。此模型提供了一套API&#xff0c;使处理流更简单和更健壮。Stream默认提供了两种Provider&#xff0c;不同的流类型可能使用不同的Provider来处理&#xff0c;Simple Message Stream Provider 和 Azure Queue Stream Provider。Stream Prov…

如何编写更好的SQL查询:终极指南-第二部分

上一篇文章《如何编写更好的SQL查询&#xff1a;终极指南-第一部分》中&#xff0c;我们学习了 SQL 查询是如何执行的以及在编写 SQL 查询语句时需要注意的地方。 下面&#xff0c;我进一步学习查询方法以及查询优化。 基于集合和程序的方法进行查询 反向模型中隐含的事实是…

publiccms实现遍历多级分类下的不同样式内容

大家好&#xff0c;我是雄雄&#xff0c;欢迎关注微信公众号&#xff1a;雄雄的小课堂 前言 现在是2022年1月2日17:06:51,假期这两天都在做publiccms。 上篇文章遗留的问题&#xff0c;最终还是没有按照富文本去做&#xff0c;后期在看吧&#xff1b; 今天遇到了个问题&…

四张图带你了解Tomcat系统架构--让面试官颤抖的Tomcat回答系列

转载自 四张图带你了解Tomcat系统架构--让面试官颤抖的Tomcat回答系列 俗话说&#xff0c;站在巨人的肩膀上看世界&#xff0c;一般学习的时候也是先总览一下整体&#xff0c;然后逐个部分个个击破&#xff0c;最后形成思路&#xff0c;了解具体细节&#xff0c;Tomcat的结构…

.NET Core 2.0应用程序大小减少50%

.NET Core 2.0应用程序减小体积瘦身官方工具 IL Linker。 IL Linker 来源于mono的linker https://github.com/mono/linker&#xff0c;目前还是预览版本。 在一般的情况下&#xff0c;链接器可以将应用程序的大小减少50&#xff05;&#xff0c;大型应用程序的大小可能更有利…