Skip to content

Commit

Permalink
识别分界符
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentbel committed Jan 10, 2015
1 parent 7d2cb7d commit a74684f
Showing 1 changed file with 64 additions and 2 deletions.
66 changes: 64 additions & 2 deletions src/com/vincentbel/compiler/LexicalAnalyzer.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ public class LexicalAnalyzer {
private int currentLineStringLength = 0; // 当前读取的一行源代码的的长度
private int currentLineStringIndex = 0; // 读取到的某个具体字符下标

// 简单的操作符,读取到一个字符后就能确定类型的字符
// 也就是 . , ; = + - ( ) * /
private int[] simpleOperators;


/**
* Constructor
*
Expand All @@ -32,6 +37,20 @@ public LexicalAnalyzer(String filePath) {
e.printStackTrace();
System.out.println("错误! 文件不存在");
}

// 初始化简单操作符
simpleOperators = new int[256]; // 因为char的范围是[0, 255],所以数组大小最大只需256
Arrays.fill(simpleOperators, Symbol.NUL); // 对于其他不可识别的字符,全都设置为[NULL]
simpleOperators['.'] = Symbol.PERIOD;
simpleOperators[','] = Symbol.COMMA;
simpleOperators[';'] = Symbol.SEMICOLON;
simpleOperators['='] = Symbol.EQUAL;
simpleOperators['+'] = Symbol.PLUS;
simpleOperators['-'] = Symbol.MINUS;
simpleOperators['('] = Symbol.LEFT_PARENTHESIS;
simpleOperators[')'] = Symbol.RIGHT_PARENTHESIS;
simpleOperators['*'] = Symbol.MULTIPLY;
simpleOperators['/'] = Symbol.DIVIDE;
}

/**
Expand Down Expand Up @@ -183,9 +202,52 @@ private Symbol getNumber() {
* @return Symbol
*/
private Symbol getOperator() {
Symbol symbol;

Symbol symbol = null;
// TODO 实现
switch (currentChar) {
case ':':
getChar();
if (currentChar == '=') { // 赋值符号 :=
symbol = new Symbol(Symbol.BECOMES);
getChar();
} else {
// ERROR,设置symbol为null
symbol = new Symbol(Symbol.NUL);
}
break;
case '<':
getChar();
switch (currentChar) {
case '>': // 不等于 <>
symbol = new Symbol(Symbol.NOT_EQUAL);
getChar();
break;
case '=': // 小于等于 <=
symbol = new Symbol(Symbol.LESS_OR_EQUAL);
getChar();
break;
default: // 小于
symbol = new Symbol(Symbol.LESS);
break;
}
break;
case '>':
getChar();
if (currentChar == '=') { // 大于等于 >=
symbol = new Symbol(Symbol.GREATER_OR_EQUAL);
getChar();
} else { // 大于
symbol = new Symbol(Symbol.GREATER);
}
break;
default:
// 直接利用simpleOperators[]数组填充即可
symbol = new Symbol(simpleOperators[currentChar]);

// 提前读取下一个字符
getChar();
break;
}

return symbol;
}
Expand Down

0 comments on commit a74684f

Please sign in to comment.