在语法文件中增加关键字的定义,例如:
grammar Sample;
@SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class Sample extends Parser { // 定义关键字 public static final int T__0 = 1; public static final int T__1 = 2; public static final int T__2 = 3; public static final int T__3 = 4; public static final int T__4 = 5; public static final int INT = 6; public static final int ID = 7; // ...
// 定义规则
expr: ID | INT;
// ...
// 识别关键字
ID: [a-zA-Z] [a-zA-Z0-9]* {
if(getText().equals("if")) {
setType(T__0); // 将if关键字的类型设为T__0
}
else if(getText().equals("else")) {
setType(T__1); // 将else关键字的类型设为T__1
}
else {
setType(ID); // 其他标识符类型为ID
}
};
// ...
// 定义词法规则
INT: [0-9]+;
WS: [ \r\t\n]+ -> skip; // 跳过空格、回车、制表符
// ...
}
在ID规则中设定关键字的类型,以便正确识别和分类。其他语法规则和词法规则按照正常方式定义即可。