beanshell的语法分析

最近在做一个b/s开发平台,其中使用了beanshell作为内嵌脚本编辑器。但写完代码的语法检查一直是个问题,今天突然发现了beanshell本身的parser类已经做了这方面工作,我们的实现就简单多了。

This is the BeanShell parser. It is used internally by the Interpreter
class (which is probably what you are looking for). The parser knows
only how to parse the structure of the language, it does not understand
names, commands, etc.

You can use the Parser from the command line to do basic structural
validation of BeanShell files without actually executing them. e.g.

[code]java bsh.Parser [ -p ] file [ file ] [ ... ][/code]
The -p option causes the abstract syntax to be printed.

From code you'd use the Parser like this:
  Parser parser = new Parser(in);
while( !(eof=parser.Line()) ) {
SimpleNode node = parser.popNode();
// use the node, etc. (See bsh.BSH* classes)
}


做过试验后,发现“The parser knows
only how to parse the structure of the language, it does not understand names, commands, etc.”这句话的具体含义是只做语法方面的检查,保证你写的内容符合java本身的语法规范,如关键字for写成for1、有个左括号缺丢失右括号、缺少分号结束等等。

但不包含语义方面的检查,如你定义了变量a,但使用的时候写成a1了,或者没有import某个类,却直接调用。这类检查不在beanshell parser能力范围内。

具体测试代码如下:

package com.mycompany.test.sample.test;

import java.io.FileInputStream;
import bsh.ParseException;
import bsh.Parser;

public class testBSHParser {
public static void main(String [] args) throws Exception{
FileInputStream in = new FileInputStream("E:/test.bsh");
Parser parser = new Parser(in);
try{
while( !(parser.Line()) ) {
// use the node, etc. (See bsh.BSH* classes)
}
}catch(ParseException e){
System.out.println(e.getErrorSourceFile());
System.out.println(e.getErrorLineNumber());
System.out.println(e.getErrorText());
}
}
}


被测试的脚本放到一个文件中,如上面代码中的E:/test.bsh
int i = 0;

for(i=0;i<100;i++)
{
i++
System.out.println((i++)--);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值