採用**確定性有限自動機 (DFA)** 識別單詞。核心數據結構:
- move[state][char_class]:狀態轉移表。
- final[state]:接受狀態集合。
- 字符分類函數 judge(char) 將字符映射為列索引。
int DFA(int start, const int* move, int width, const int* final, int flen, int (*classify)(char)) {
char buf[256]; int len = 0, state = start, ch = getchar(), cls;
while ((cls = classify(ch)) != -1) {
int nxt = move[state * width + cls];
if (nxt == -1) return -1; // 錯誤
buf[len++] = ch;
state = nxt;
ch = getchar();
}
ungetc(ch, stdin);
buf[len] = '\0';
for (int i = 0; i < flen; ++i)
if (state == final[i]) return i; // 返回接受狀態索引
return -1;
}
==, <=, &&),用前瞻一字符決定。/* ... */ 嵌套或不嵌套,直接跳過不產生 Token。
while ((ch = getchar()) != EOF) {
if (isspace(ch)) continue;
if (isalpha(ch) || ch=='_') { ungetc(ch,stdin); scanIdent(); }
else if (isdigit(ch)) { ungetc(ch,stdin); scanNumber(); }
else scanOperator(ch);
}
代碼包含:字符分類函數、DFA 通用引擎、各類掃描函數、關鍵字表、主函數讀取 in.txt 輸出二元式。編譯運行即可得到詞法分析結果。