词法分析器定义
- 关键字有if、else、while、continue、break、true、false、int、char、bool;
- if和while语句同c#;
- 四则运算、逻辑运算、关系运算同c#;
- 基本数据类型char、bool、int;
- 不支持注释。
DFA
Lexer
Token、TokenType、Integer、Char、Work、Type等class参考《词法分析器》。
public class DFALexer
{
public int LineNumber { get; set; }
private State state = State.START;
private StringReader reader;
private IDictionary<string, Word> reserveds = new Dictionary<string, Word>();
public DFALexer()
{
Reserve(new Word(TokenType.IF, "if"));
Reserve(new Word(TokenType.ELSE, "else"));
Reserve(new Word(TokenType.WHILE, "while"));
Reserve(new Word(TokenType.BREAK, "break"));
Reserve(new Word(TokenType.CONTINUE, "continue"));
Reserve(Word.TRUE);
Reserve(Word.FALSE);
Reserve(Word.NULL);
Reserve(Type.INT);
Reserve(Type.CHAR);
Reserve(Type.BOOL);
}
private void Reserve(Word word) => reserveds.Add(word.Lexeme, word);
public void LoadCode(string code)
{
if (reader != null)
reader.Dispose();
reader = new StringReader(code);
LineNumber = 1;
}
public Token Scan()
{
if (reader is null) throw new Exception("forget to call LoadCode function");
var curChar = (char)reader.Read();
//omit white space
for (; ; curChar = (char)reader.Read())
{
if (curChar == ' ' || curChar == '\t') continue;
else if (curChar == '\r')
{
curChar = (char)reader.Read();
if (curChar =