2017-11-26 3 views
0

beanhell로 작성된 코드에 대한 기본 정적 코드 분석 도구를 작성하려고합니다.이 도구는 사용되지 않는 변수, 방법 및 가능한 경우 true로 평가되지 않는 조건과 같은 몇 가지 기본 검사를 수행합니다.Beanshell 코드 구문 분석

나는 다음과 같은 몇 가지 예에 표시된 방법으로으로 Beanshell 소스 배포판과 함께 제공되는 파서 사용하여 시도했다 :

import java.io.FileInputStream; 
import java.io.IOException; 

import bsh.ParseException; 
import bsh.Parser; 
import bsh.SimpleNode; 

public class FindUnusedVariablesTask { 

    String sourseFilePath; 

    public FindUnusedVariablesTask(String sourseFilePath) {    
     this.sourseFilePath = sourseFilePath; 
    } 


    public String perform() throws ParseException, IOException { 
     FileInputStream sourceStream = new FileInputStream(sourseFilePath); 
     Parser p = new Parser(sourceStream); 

     while (!p.Line()) { 
      SimpleNode node = p.popNode(); 
      System.out.println(node.getText()); 
      for (int i=0; i<node.jjtGetNumChildren(); i++) 
       System.out.println(node.getChild(i).getText()); 
     } 
     sourceStream.close(); 
     return ""; 
    } 
} 

다음으로 Beanshell 코드 :

f1() { 
    return 1; 
} 

String f2(String x) { 
    return x + f1() + " OK"; 
} 

출력을

f1 () { 
() 
{ 

String f2 (String x) { 
String 
(String x) 
{ 

기본적으로 나는 구문 분석 된 m ethod 선언. 내에서 구문 분석 된 문에 액세스하는 방법을 찾을 수 없습니다. 어떻게 할 수 있습니까?

답변

2

BeanShell 파서가 AST를 생성합니다. 일반적으로 AST는 구조가 상당히 깊을 수 있습니다. 위 코드는 AST 깊숙이 1 층 밖에 보이지 않습니다.

는 (필자는 devkit, 그래서 의사로 이것을 고려하지 않는다) 재귀 적 탐색을 시도

import bsh.Node; //you need this as well 

public String perform() throws ParseException, IOException { 
    FileInputStream sourceStream = new FileInputStream(sourseFilePath); 
    Parser p = new Parser(sourceStream); 

    while (!p.Line()) { 
     recursive_print(p.popNode(), ""); 
    } 

    sourceStream.close(); 
    return ""; 
} 

public void recursive_print(Node node, String prefix) 
{ 
    System.out.println(prefix + node.getText()); 
    for (int i=0; i<node.jjtGetNumChildren(); i++) 
     recursive_print(node.getChild(i), prefix+" "); 
}  
+0

나는 절대적으로 내가 노드에 재귀한다는 것을 잊어 버렸습니다. 고마워요! – DebD