Skip to content
Permalink
Browse files

识别分界符

  • Loading branch information
VincentBel committed Jan 10, 2015
1 parent 7d2cb7d commit a74684ff271cfa169e8d6b7891ff305e58f86cbc
Showing with 64 additions and 2 deletions.
  1. +64 −2 src/com/vincentbel/compiler/LexicalAnalyzer.java
@@ -20,6 +20,11 @@
private int currentLineStringLength = 0; // 当前读取的一行源代码的的长度
private int currentLineStringIndex = 0; // 读取到的某个具体字符下标

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


/**
* Constructor
*
@@ -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;
}

/**
@@ -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;
}

0 comments on commit a74684f

Please sign in to comment.
You can’t perform that action at this time.