Ausführung Parser

This commit is contained in:
Maximilian Stahl 2024-05-02 15:22:29 +02:00
parent cd7aac282e
commit d270992858
6 changed files with 82 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package parser;
import parser.generated.SimpleJavaBaseVisitor;
import parser.generated.SimpleJavaParser;
public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
@Override
public ASTNode visitProgram(SimpleJavaParser.ProgramContext ctx) {
ProgramNode program = new ProgramNode();
for (SimpleJavaParser.ClassDeclarationContext classDeclCtx : ctx.classDeclaration()) {
program.addClass((ClassDeclarationNode) visit(classDeclCtx));
}
return program;
}
@Override
public ASTNode visitClassDeclaration(SimpleJavaParser.ClassDeclarationContext ctx) {
return new ClassDeclarationNode(ctx.IDENTIFIER().getText());
}
}

View File

@ -0,0 +1,8 @@
package parser;
import java.util.ArrayList;
import java.util.List;
public abstract class ASTNode { }

View File

@ -0,0 +1,11 @@
package parser;
import parser.ASTNode;
public class ClassDeclarationNode extends ASTNode {
public String identifier;
public ClassDeclarationNode(String identifier) {
this.identifier = identifier;
}
}

View File

@ -0,0 +1,27 @@
package parser;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.tree.ParseTree;
import parser.generated.SimpleJavaLexer;
import parser.generated.SimpleJavaParser;
public class Main {
public static void main(String[] args) throws Exception {
// Assuming args[0] contains the path to the input file
CharStream codeCharStream = CharStreams.fromString("class Test { }");
SimpleJavaLexer lexer = new SimpleJavaLexer(codeCharStream);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SimpleJavaParser parser = new SimpleJavaParser(tokens);
ParseTree tree = parser.program(); // parse the input
ASTBuilder builder = new ASTBuilder();
ProgramNode ast = (ProgramNode) builder.visit(tree); // build the AST
// Optionally print or process the AST
System.out.println("Parsed " + ast.classes.size() + " classes.");
System.out.println(ast.classes.get(0).identifier);
}
}

View File

@ -0,0 +1,15 @@
package parser;
import parser.ASTNode;
import parser.ClassDeclarationNode;
import java.util.ArrayList;
import java.util.List;
public class ProgramNode extends ASTNode {
public List<ClassDeclarationNode> classes = new ArrayList<>();
public void addClass(ClassDeclarationNode classNode) {
classes.add(classNode);
}
}

View File

@ -0,0 +1 @@
class Test { }