1. 何为词法分析器?
将一段源程序转换为一个一个的单词符号.
2. 关于单词符号及其分类?
1> 关键字(保留字):是一类具有特殊意义的标识符.如java中的if,else...
2> 标识符:自己规定的具有特定含义的词。如变量名,数组名,类名称,方法名.
3> 常数:一般包括整型,实型,布尔类型,文字类型。如100,3.1415,true,’simple’...
4> 运算符:+,-,*,/等等.
5> 界符:如逗号,分号,括号,/* */等等.
3. 关于词法分析器的输出格式?
常用该二元式表示:(单词类别,单词符号的属性值).
* 单词类别:通常用整数进行编码,用来区分单词类型。
* 单词符号的属性:在上述中如果一个单词类别只包含一个单词,那么只需单词类别就可以表示自身,但如果含有多个单词的话,那么除了单词类别,还需要该单词符号的特有信息,称为单词符号的属性.
不同的单词的单词符号属性值:
* 标识符:常用存放它有关信息符号的指针作为其值。
* 常数:常数类似,用存放常数的指针来表示.
对于一符一种的,只给出种别编码.
下面是代码实现:
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Online {
public static char ch = ' ';
public static String strToken = "";
public static int flag = 0;
public static Map<String, Integer> map = new HashMap<String, Integer>();
public static String[] Id = new String[200];
public static int f1 = 0;
public static String[] Const = new String[200];
public static int f2 = 0;
public void start() {
map.put("if", 1);
map.put("else", 2);
map.put("int", 3);
map.put("char", 4);
map.put("float", 5);
}
public void GetChar(String str) {
ch = str.charAt(flag);
flag++;
}
public void GetBC(String str) {
while (Character.isSpaceChar(ch)) {
GetChar(str);
}
}
public void Concat() {
strToken += ch;
}
public boolean IsLetter() // 是否为字母
{
if (Character.isLetter(ch)) {
return true;
}
return false;
}
public boolean IsDigit()
{
if (Character.isDigit(ch)) {
return true;
}
return false;
}
public int Reserve() {
start();
Set<String> set = map.keySet();
for (String str : set) {
if (str.equals(strToken)) {
return map.get(strToken);
}
}
return 0;
}
public void Retract() {
flag--;
ch = ' ';
}
public int InsertId() {
Id[f1] = strToken;
f1++;
return f1 - 1;
}
public int InsertConst() {
Const[f2] = strToken;
strToken = "";
f2++;
return f2 - 1;
}
public static void myPrint(String code, String value) {
System.out.println("<" + code + "," + value + ">");
}
public void test(String str) {
int code;
int value;
while (flag < str.length()) {
GetChar(str);
GetBC(str);
if (IsLetter()) {
while (IsDigit() || IsLetter()) {
Concat();
if (flag < str.length()) {
GetChar(str);
} else {
break;
}
}
System.out.println(strToken);
code = Reserve();
if (!IsDigit() && !IsLetter()) {
Retract();
}
if (code == 0) {
value = InsertId();
myPrint("id", "" + value);
} else {
myPrint("key", "" + code);
}
strToken = "";
} else if (IsDigit()) {
while (IsDigit()) {
Concat();
GetChar(str);
}
value = InsertConst();
Retract();
myPrint("number", "" + value);
} else {
switch (ch) {
case '=':
myPrint("=", "-");
break;
case '(':
myPrint("(", "-");
break;
case ')':
myPrint(")", "-");
break;
case '{':
myPrint("{", "-");
break;
case '}':
myPrint("}", "-");
break;
default:
System.out.println("ERROR!");
}
}
}
}
public static void main(String[] args) {
System.out.println("please input :");
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
Online on=new Online();
on.test(str);
}
}
本代码只实现了一行代码的分析,可以根据IO操作从文件中每次读取一行进行处理,从而实现文件的词法分析处理。