추상 구문 트리
라고 하는데,import org.eclipse.jdt.core.dom.*;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.core.runtime.NullProgressMonitor;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Map;
public class ASTGenerator {
public static CompilationUnit generateAST(String filePath) throws Exception {
// 1. 파일 내용 읽기
String source = readFileToString(filePath);
// 2. AST 파서 설정
ASTParser parser = ASTParser.newParser(AST.JLS14); // Java 14 문법 사용
이런식으로 AST 파서를 통해
package com.example;
public class HelloWorld {
private String message;
public HelloWorld(String message) {
this.message = message;
}
public void sayHello() {
System.out.println(message);
}
}
이런 클래스 파일을 파서를 통해
CompilationUnit
PackageDeclaration
SimpleName: com
SimpleName: example
TypeDeclaration: HelloWorld
Modifier: public
SimpleName: HelloWorld
FieldDeclaration
Modifier: private
SimpleType
SimpleName: String
VariableDeclarationFragment
SimpleName: message
MethodDeclaration: HelloWorld
Modifier: public
SimpleName: HelloWorld
SingleVariableDeclaration
SimpleType
SimpleName: String
SimpleName: message
Block
ExpressionStatement
Assignment
FieldAccess
ThisExpression
SimpleName: message
SimpleName: message
MethodDeclaration: sayHello
Modifier: public
SimpleName: sayHello
Block
ExpressionStatement
MethodInvocation
QualifiedName
SimpleName: System
SimpleName: out
SimpleName: println
SimpleName: message
위와 같은 구조로 만든다고 함.
public class Main {
public static void main(String[] args) {
ASTParser parser = ASTParser.newParser(AST.JLS20);
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("src/main/java/com/cor/practice/Calculator.java")));) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line).append("\n");
line = br.readLine();
}
parser.setSource(sb.toString().toCharArray());
parser.setKind(ASTParser.K_COMPILATION_UNIT); // 파싱 종류 설정 (전체 컴파일 유닛)
parser.setResolveBindings(true); // 바인딩 정보 해석 활성화
parser.setBindingsRecovery(true); // 바인딩 복구 활성화
Map<String, String> options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_17, options);
parser.setCompilerOptions(options);
CompilationUnit compilationUnit = (CompilationUnit) parser.createAST(null);
compilationUnit.accept(new ASTVisitor() {
@Override
public boolean visit(MethodDeclaration node) {
System.out.println("Method name: " + node.getName().getIdentifier());
return true;
}
});
String output = compilationUnit.toString();
System.out.println(output);
} catch (IOException e) {
e.printStackTrace();
}
}
}
라이브러리 추가해야함.
implementation 'org.eclipse.jdt:org.eclipse.jdt.core:3.38.0'