code-generator #8

Merged
i22007 merged 11 commits from code-generator into main 2024-05-14 13:34:52 +00:00
35 changed files with 388 additions and 189 deletions

View File

@ -5,9 +5,7 @@ public class Example {
public static int testMethod(char b){ public static int testMethod(char b){
int a; int a;
boolean b; int a;
char c;
b = 3;
} }

View File

@ -1,3 +1,4 @@
import ast.ASTNode;
import ast.ClassNode; import ast.ClassNode;
import ast.ProgramNode; import ast.ProgramNode;
import bytecode.ByteCodeGenerator; import bytecode.ByteCodeGenerator;
@ -17,14 +18,14 @@ public class Main {
public static void main(String[] args) throws Exception { public static void main(String[] args) throws Exception {
try { try {
CharStream codeCharStream = CharStreams.fromPath(Paths.get("src/main/java/CompilerInput.txt")); CharStream codeCharStream = CharStreams.fromPath(Paths.get("src/main/java/CompilerInput.txt"));
parsefile(codeCharStream); parseFile(codeCharStream);
} catch (IOException e) { } catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage()); System.err.println("Error reading the file: " + e.getMessage());
} }
} }
static void parsefile(CharStream codeCharStream){ static void parseFile(CharStream codeCharStream){
SimpleJavaLexer lexer = new SimpleJavaLexer(codeCharStream); SimpleJavaLexer lexer = new SimpleJavaLexer(codeCharStream);
CommonTokenStream tokens = new CommonTokenStream(lexer); CommonTokenStream tokens = new CommonTokenStream(lexer);
SimpleJavaParser parser = new SimpleJavaParser(tokens); SimpleJavaParser parser = new SimpleJavaParser(tokens);
@ -34,9 +35,9 @@ public class Main {
ASTBuilder builder = new ASTBuilder(); ASTBuilder builder = new ASTBuilder();
ProgramNode ast = (ProgramNode) builder.visit(tree); // build the AST ProgramNode ast = (ProgramNode) builder.visit(tree); // build the AST
SemanticAnalyzer.generateTast(ast); ProgramNode typedAst = (ProgramNode) SemanticAnalyzer.generateTast(ast);
ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator(); ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator();
byteCodeGenerator.visit(ast); byteCodeGenerator.visit(typedAst);
} }
} }

View File

@ -11,7 +11,7 @@ import java.util.List;
import bytecode.visitor.ClassVisitor; import bytecode.visitor.ClassVisitor;
import semantic.SemanticVisitor; import semantic.SemanticVisitor;
import typechecker.TypeCheckResult; import typechecker.TypeCheckResult;
import typechecker.Visitable; import visitor.Visitable;
public class ClassNode implements ASTNode, Visitable { public class ClassNode implements ASTNode, Visitable {
public String identifier; public String identifier;

View File

@ -1,8 +1,10 @@
package ast; package ast;
import ast.expression.ExpressionNode; import ast.expression.ExpressionNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public class LiteralNode extends ExpressionNode { public class LiteralNode implements ExpressionNode {
int value; int value;
private String type; private String type;
@ -20,4 +22,8 @@ public class LiteralNode extends ExpressionNode {
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return null;
}
} }

View File

@ -6,7 +6,7 @@ import java.util.List;
import bytecode.visitor.ProgramVisitor; import bytecode.visitor.ProgramVisitor;
import semantic.SemanticVisitor; import semantic.SemanticVisitor;
import typechecker.TypeCheckResult; import typechecker.TypeCheckResult;
import typechecker.Visitable; import visitor.Visitable;
public class ProgramNode implements ASTNode, Visitable{ public class ProgramNode implements ASTNode, Visitable{
public List<ClassNode> classes = new ArrayList<>(); public List<ClassNode> classes = new ArrayList<>();

View File

@ -1,6 +1,10 @@
package ast; package ast;
public class VarNode implements ASTNode{ import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
public class VarNode implements ASTNode, Visitable {
private String identifier; private String identifier;
private String type; private String type;
@ -18,4 +22,8 @@ public class VarNode implements ASTNode{
return identifier; return identifier;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -1,6 +1,10 @@
package ast.expression; package ast.expression;
public class BinaryExpressionNode extends ExpressionNode { import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
public class BinaryExpressionNode implements ExpressionNode, Visitable {
public ExpressionNode left; public ExpressionNode left;
public ExpressionNode right; public ExpressionNode right;
public String operator; // Stores the operator as a string (e.g., "+", "-", "&&") public String operator; // Stores the operator as a string (e.g., "+", "-", "&&")
@ -10,4 +14,9 @@ public class BinaryExpressionNode extends ExpressionNode {
this.right = right; this.right = right;
this.operator = operator; this.operator = operator;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -1,9 +1,8 @@
package ast.expression; package ast.expression;
import ast.ASTNode; import ast.ASTNode;
import visitor.Visitable;
public class ExpressionNode implements ASTNode { public interface ExpressionNode extends ASTNode, Visitable {
} }

View File

@ -1,9 +1,22 @@
package ast.expression; package ast.expression;
public class IdentifierExpressionNode extends ExpressionNode { import ast.type.TypeNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
public class IdentifierExpressionNode implements ExpressionNode, Visitable {
public String name; public String name;
public TypeNode type;
public IdentifierExpressionNode(String name) { public IdentifierExpressionNode(String name) {
this.name = name; this.name = name;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -1,6 +1,10 @@
package ast.expression; package ast.expression;
public class UnaryExpressionNode extends ExpressionNode { import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
public class UnaryExpressionNode implements ExpressionNode, Visitable {
public ExpressionNode expression; public ExpressionNode expression;
public String operator; // Stores the operator (e.g., "-", "!") public String operator; // Stores the operator (e.g., "-", "!")
@ -8,4 +12,9 @@ public class UnaryExpressionNode extends ExpressionNode {
this.expression = expression; this.expression = expression;
this.operator = operator; this.operator = operator;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -2,7 +2,7 @@ package ast.member;
import ast.type.AccessTypeNode; import ast.type.AccessTypeNode;
import bytecode.visitor.MethodVisitor; import bytecode.visitor.MethodVisitor;
import typechecker.Visitable; import visitor.Visitable;
public class ConstructorNode extends MethodNode implements Visitable { public class ConstructorNode extends MethodNode implements Visitable {
public ConstructorNode(AccessTypeNode visibility, String name) { public ConstructorNode(AccessTypeNode visibility, String name) {

View File

@ -5,7 +5,7 @@ import ast.type.TypeNode;
import bytecode.visitor.ClassVisitor; import bytecode.visitor.ClassVisitor;
import semantic.SemanticVisitor; import semantic.SemanticVisitor;
import typechecker.TypeCheckResult; import typechecker.TypeCheckResult;
import typechecker.Visitable; import visitor.Visitable;
public class FieldNode implements MemberNode, Visitable { public class FieldNode implements MemberNode, Visitable {
public AccessTypeNode accessTypeNode; public AccessTypeNode accessTypeNode;

View File

@ -3,15 +3,15 @@ package ast.member;
import ast.parameter.ParameterListNode; import ast.parameter.ParameterListNode;
import ast.statement.StatementNode; import ast.statement.StatementNode;
import ast.type.AccessTypeNode; import ast.type.AccessTypeNode;
import ast.type.TypeNode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import ast.type.TypeNode;
import bytecode.visitor.MethodVisitor; import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor; import semantic.SemanticVisitor;
import typechecker.TypeCheckResult; import typechecker.TypeCheckResult;
import typechecker.Visitable; import visitor.Visitable;
public class MethodNode implements MemberNode, Visitable { public class MethodNode implements MemberNode, Visitable {
public AccessTypeNode visibility; public AccessTypeNode visibility;

View File

@ -6,7 +6,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
public class ParameterListNode implements ASTNode { public class ParameterListNode implements ASTNode {
List<ParameterNode> parameters = new ArrayList<>(); public List<ParameterNode> parameters = new ArrayList<>();
public ParameterListNode(List<ParameterNode> parameters){ public ParameterListNode(List<ParameterNode> parameters){
this.parameters = parameters; this.parameters = parameters;

View File

@ -4,7 +4,7 @@ import ast.VarNode;
import ast.expression.ExpressionNode; import ast.expression.ExpressionNode;
import semantic.SemanticVisitor; import semantic.SemanticVisitor;
import typechecker.TypeCheckResult; import typechecker.TypeCheckResult;
import typechecker.Visitable; import visitor.Visitable;
public class AssignmentStatementNode extends StatementNode implements Visitable { public class AssignmentStatementNode extends StatementNode implements Visitable {
public VarNode varNode; public VarNode varNode;

View File

@ -1,6 +1,8 @@
package ast.statement; package ast.statement;
import ast.expression.ExpressionNode; import ast.expression.ExpressionNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public class IfStatementNode extends StatementNode { public class IfStatementNode extends StatementNode {
public ExpressionNode condition; public ExpressionNode condition;
@ -12,4 +14,9 @@ public class IfStatementNode extends StatementNode {
this.thenStatement = thenStatement; this.thenStatement = thenStatement;
this.elseStatement = elseStatement; this.elseStatement = elseStatement;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -1,6 +1,8 @@
package ast.statement; package ast.statement;
import ast.expression.ExpressionNode; import ast.expression.ExpressionNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public class ReturnStatementNode extends StatementNode { public class ReturnStatementNode extends StatementNode {
public ExpressionNode expression; public ExpressionNode expression;
@ -8,4 +10,9 @@ public class ReturnStatementNode extends StatementNode {
public ReturnStatementNode(ExpressionNode expression) { public ReturnStatementNode(ExpressionNode expression) {
this.expression = expression; this.expression = expression;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -1,7 +1,8 @@
package ast.statement; package ast.statement;
import ast.ASTNode; import ast.ASTNode;
import visitor.Visitable;
public abstract class StatementNode implements ASTNode { public abstract class StatementNode implements ASTNode, Visitable {
} }

View File

@ -1,7 +1,9 @@
package ast.statement; package ast.statement;
import ast.type.TypeNode;
import ast.expression.ExpressionNode; import ast.expression.ExpressionNode;
import ast.type.TypeNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public class VariableDeclarationStatementNode extends StatementNode { public class VariableDeclarationStatementNode extends StatementNode {
public TypeNode type; public TypeNode type;
@ -12,4 +14,9 @@ public class VariableDeclarationStatementNode extends StatementNode {
this.identifier = identifier; this.identifier = identifier;
this.expression = expression; this.expression = expression;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -1,6 +1,8 @@
package ast.statement; package ast.statement;
import ast.expression.ExpressionNode; import ast.expression.ExpressionNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public class WhileStatementNode extends StatementNode { public class WhileStatementNode extends StatementNode {
public ExpressionNode condition; public ExpressionNode condition;
@ -10,4 +12,9 @@ public class WhileStatementNode extends StatementNode {
this.condition = condition; this.condition = condition;
this.body = body; this.body = body;
} }
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
} }

View File

@ -1,6 +1,8 @@
package ast.type; package ast.type;
public class BaseTypeNode implements TypeNode{ import ast.ASTNode;
public class BaseTypeNode implements ASTNode, TypeNode {
public EnumTypeNode enumType; public EnumTypeNode enumType;

View File

@ -1,4 +1,6 @@
package ast.type; package ast.type;
public class ReferenceTypeNode implements TypeNode{ import ast.ASTNode;
public class ReferenceTypeNode implements ASTNode, TypeNode {
} }

View File

@ -4,6 +4,7 @@ import ast.ClassNode;
import ast.member.FieldNode; import ast.member.FieldNode;
import ast.member.MemberNode; import ast.member.MemberNode;
import ast.member.MethodNode; import ast.member.MethodNode;
import ast.type.BaseTypeNode;
import bytecode.visitor.ClassVisitor; import bytecode.visitor.ClassVisitor;
import java.io.File; import java.io.File;
import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ClassWriter;
@ -12,14 +13,19 @@ import org.objectweb.asm.Opcodes;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
public class ClassCodeGen implements ClassVisitor { public class ClassCodeGen implements ClassVisitor {
Mapper mapper = new Mapper(); private Mapper mapper;
ClassWriter classWriter; private ClassWriter classWriter;
public ClassCodeGen() {
mapper = new Mapper();
}
@Override @Override
public void visit(ClassNode classNode) { public void visit(ClassNode classNode) {
classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS); classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
classWriter.visit(Opcodes.V1_8, mapper.mapAccesTypeToOpcode(classNode.accessType), classNode.identifier, null, classWriter.visit(Opcodes.V1_5, mapper.mapAccessTypeToOpcode(classNode.accessType), classNode.identifier, null,
"java/lang/Object", null); "java/lang/Object", null);
for (MemberNode memberNode : classNode.members) { for (MemberNode memberNode : classNode.members) {
@ -39,7 +45,9 @@ public class ClassCodeGen implements ClassVisitor {
@Override @Override
public void visit(FieldNode fieldNode) { public void visit(FieldNode fieldNode) {
classWriter.visitField(mapper.mapAccesTypeToOpcode(fieldNode.accessTypeNode), fieldNode.identifier, mapper.getTypeChar(fieldNode.type.enumTypeNode), null, null ); if(fieldNode.type instanceof BaseTypeNode baseTypeNode){
classWriter.visitField(mapper.mapAccessTypeToOpcode(fieldNode.accessTypeNode), fieldNode.identifier, mapper.getTypeChar(baseTypeNode.enumType), null, null );
}
classWriter.visitEnd(); classWriter.visitEnd();
} }

View File

@ -1,13 +0,0 @@
package bytecode;
import ast.member.FieldNode;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
public class FieldCodeGen {
public void generateFieldCode(ClassWriter classWriter, FieldNode fieldNode) {
Mapper mapper = new Mapper();
FieldVisitor fieldVisitor = classWriter.visitField(mapper.mapAccesTypeToOpcode(fieldNode.accessTypeNode), fieldNode.identifier, "", null, null);
}
}

View File

@ -1,13 +1,13 @@
package bytecode; package bytecode;
import ast.type.AccessTypeNode; import ast.parameter.ParameterListNode;
import ast.type.EnumAccessTypeNode; import ast.parameter.ParameterNode;
import ast.type.EnumTypeNode; import ast.type.*;
import ast.type.TypeNode;
import org.objectweb.asm.Opcodes; import org.objectweb.asm.Opcodes;
import ast.type.BaseTypeNode;
public class Mapper { public class Mapper {
public int mapAccesTypeToOpcode(AccessTypeNode type) { public int mapAccessTypeToOpcode(AccessTypeNode type) {
switch (type.enumAccessTypeNode) { switch (type.enumAccessTypeNode) {
case EnumAccessTypeNode.PUBLIC: case EnumAccessTypeNode.PUBLIC:
return Opcodes.ACC_PUBLIC; return Opcodes.ACC_PUBLIC;
@ -17,9 +17,13 @@ public class Mapper {
return 0; return 0;
} }
public String generateMethodDescriptor(TypeNode typeNode) { public String generateMethodDescriptor(BaseTypeNode baseTypeNode, ParameterListNode parameterListNode) {
String descriptor = "()"; String descriptor = "(";
descriptor += getTypeChar(typeNode.enumTypeNode); for(ParameterNode parameterNode : parameterListNode.parameters) {
descriptor += getTypeChar(EnumTypeNode.INT);
}
descriptor += ")";
descriptor += getTypeChar(baseTypeNode.enumType);
return descriptor; return descriptor;
} }

View File

@ -2,37 +2,99 @@ package bytecode;
import ast.member.ConstructorNode; import ast.member.ConstructorNode;
import ast.member.MethodNode; import ast.member.MethodNode;
import ast.parameter.ParameterListNode;
import ast.parameter.ParameterNode;
import ast.type.BaseTypeNode;
import ast.type.EnumTypeNode;
import org.objectweb.asm.ClassWriter; import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import java.util.ArrayList;
import java.util.List;
import static org.objectweb.asm.Opcodes.*;
public class MethodCodeGen implements bytecode.visitor.MethodVisitor { public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
private ClassWriter classWriter; private ClassWriter classWriter;
Mapper mapper = new Mapper(); private Mapper mapper;
private MethodVisitor methodVisitor;
private List<String> localVaribales;
public MethodCodeGen(ClassWriter classWriter) { public MethodCodeGen(ClassWriter classWriter) {
this.classWriter = classWriter; this.classWriter = classWriter;
mapper = new Mapper();
localVaribales = new ArrayList<>();
} }
@Override @Override
public void visit(ConstructorNode constructorNode) { public void visit(ConstructorNode constructorNode) {
MethodVisitor constructor = methodVisitor =
classWriter.visitMethod(mapper.mapAccesTypeToOpcode(constructorNode.visibility), classWriter.visitMethod(mapper.mapAccessTypeToOpcode(constructorNode.visibility),
"<init>", "<init>",
"()V", "()V",
null, null,
null); null);
constructor.visitEnd(); methodVisitor.visitCode();
methodVisitor.visitVarInsn(ALOAD, 0);
methodVisitor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V", false);
methodVisitor.visitInsn(RETURN);
methodVisitor.visitMaxs(1, 1);
methodVisitor.visitEnd();
} }
@Override @Override
public void visit(MethodNode methodNode) { public void visit(MethodNode methodNode) {
MethodVisitor method = classWriter.visitMethod(mapper.mapAccesTypeToOpcode(methodNode.visibility), if (methodNode.type instanceof BaseTypeNode baseTypeNode) {
methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(methodNode.visibility),
methodNode.identifier, methodNode.identifier,
mapper.generateMethodDescriptor(methodNode.type), mapper.generateMethodDescriptor(baseTypeNode, methodNode.parameters),
null, null,
null); null);
method.visitEnd(); methodVisitor.visitCode();
localVaribales.add("this");
for (ParameterNode parameterNode : methodNode.parameters.parameters) {
localVaribales.add(parameterNode.identifier);
}
//test();
methodVisitor.visitMaxs(1, localVaribales.size());
methodVisitor.visitEnd();
}
}
public void test() {
Label start = new Label();
Label loop = new Label();
Label end = new Label();
methodVisitor.visitLabel(start);
//methodVisitor.visitVarInsn(Opcodes.ICONST_M1, 99);
//methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitLdcInsn(99);
// methodVisitor.visitInsn(Opcodes.ICONST_0);
//methodVisitor.visitVarInsn(Opcodes.ILOAD, 2);
methodVisitor.visitVarInsn(Opcodes.ISTORE, 1);
methodVisitor.visitLabel(loop);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 1);
methodVisitor.visitInsn(Opcodes.ICONST_5);
methodVisitor.visitJumpInsn(Opcodes.IF_ICMPGE, end);
methodVisitor.visitFieldInsn(Opcodes.GETSTATIC,
"java/lang/System", "out",
"Ljava/io/PrintStream;");
methodVisitor.visitLdcInsn("Bytecode");
methodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL,
"java/io/PrintStream", "println",
"(Ljava/lang/String;)V", false);
methodVisitor.visitIincInsn(1, 1);
methodVisitor.visitJumpInsn(Opcodes.GOTO, loop);
methodVisitor.visitLabel(end);
methodVisitor.visitVarInsn(Opcodes.ILOAD, 1);
methodVisitor.visitInsn(Opcodes.IRETURN);
methodVisitor.visitEnd();
} }
} }

View File

@ -13,10 +13,12 @@ import ast.parameter.ParameterNode;
import ast.statement.*; import ast.statement.*;
import ast.type.*; import ast.type.*;
import org.antlr.v4.runtime.tree.TerminalNode; import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import parser.generated.*; import parser.generated.*;
import parser.generated.SimpleJavaParser.LiteralContext; import parser.generated.SimpleJavaParser.LiteralContext;
import ast.type.BaseTypeNode;
public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> { public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
@Override @Override
@ -74,9 +76,9 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
@Override @Override
public ASTNode visitParameter(SimpleJavaParser.ParameterContext ctx) { public ASTNode visitParameter(SimpleJavaParser.ParameterContext ctx) {
TypeNode type = (TypeNode) visit(ctx.type()); TypeNode typeNode = (TypeNode) visit(ctx.type());
String identifier = ctx.IDENTIFIER().getText(); String identifier = ctx.IDENTIFIER().getText();
return new ParameterNode(type, identifier); return new ParameterNode(typeNode, identifier);
} }
@Override @Override
@ -204,6 +206,7 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
try { try {
int intValue = Integer.parseInt(literalContext.getText()); int intValue = Integer.parseInt(literalContext.getText());
LiteralNode literalNode = new LiteralNode(intValue); LiteralNode literalNode = new LiteralNode(intValue);
literalNode.setType("int"); literalNode.setType("int");
return literalNode; return literalNode;
} catch (NumberFormatException ignored) {} } catch (NumberFormatException ignored) {}

View File

@ -0,0 +1,36 @@
package semantic;
import ast.type.TypeNode;
import java.util.HashMap;
import java.util.Stack;
public class Scope {
private Stack<HashMap<String, TypeNode>> localVars;
public void addLocalVar(String name, TypeNode type) {
if (this.contains(name)) {
throw new RuntimeException("Variable " + name + " already exists in this scope");
}
localVars.peek().put(name, type);
}
public boolean contains(String name) {
for (HashMap<String, TypeNode> map : localVars) {
if (map.containsKey(name)) {
return true;
}
}
return false;
}
public void pushScope() {
localVars.push(new HashMap<String, TypeNode>());
}
public void popScope() {
localVars.pop();
}
}

View File

@ -2,22 +2,26 @@ package semantic;
import ast.*; import ast.*;
import ast.expression.ExpressionNode; import ast.expression.BinaryExpressionNode;
import ast.member.ConstructorNode; import ast.expression.IdentifierExpressionNode;
import ast.expression.UnaryExpressionNode;
import ast.member.FieldNode; import ast.member.FieldNode;
import ast.member.MemberNode; import ast.member.MemberNode;
import ast.member.MethodNode; import ast.member.MethodNode;
import ast.statement.AssignmentStatementNode; import ast.statement.*;
import ast.statement.StatementNode;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import typechecker.TypeCheckResult; import typechecker.TypeCheckResult;
public class SemanticAnalyzer implements SemanticVisitor { public class SemanticAnalyzer implements SemanticVisitor {
private ArrayList<String> currentFields = new ArrayList<>(); private ArrayList<String> currentFields = new ArrayList<>();
private Scope currentScope;
public static ASTNode generateTast(ASTNode node) throws RuntimeException { public static ASTNode generateTast(ASTNode node) throws RuntimeException {
SemanticAnalyzer semanticCheck = new SemanticAnalyzer(); SemanticAnalyzer semanticCheck = new SemanticAnalyzer();
ProgramNode programNode = (ProgramNode) node; ProgramNode programNode = (ProgramNode) node;
@ -36,34 +40,47 @@ public class SemanticAnalyzer implements SemanticVisitor {
List<ClassNode> classes = node.classes; List<ClassNode> classes = node.classes;
for (ClassNode classNode : classes) { for (ClassNode classNode : classes) {
classNode.accept(this); var result = classNode.accept(this);
valid = valid && result.isValid();
} }
return new TypeCheckResult(valid, null); return new TypeCheckResult(valid, null);
} }
@Override @Override
public TypeCheckResult analyze(ClassNode classNode) { public TypeCheckResult analyze(ClassNode classNode) {
var valid = true;
List<MemberNode> members = classNode.members; List<MemberNode> members = classNode.members;
for (MemberNode memberNode : members) { for (MemberNode memberNode : members) {
if (memberNode instanceof FieldNode fieldNode) { if (memberNode instanceof FieldNode fieldNode) {
fieldNode.accept(this); var result = fieldNode.accept(this);
valid = valid && result.isValid();
} else if (memberNode instanceof MethodNode methodNode) { } else if (memberNode instanceof MethodNode methodNode) {
methodNode.accept(this); var result = methodNode.accept(this);
valid = valid && result.isValid();
} }
} }
return null; return new TypeCheckResult(valid, null);
} }
@Override @Override
public TypeCheckResult analyze(MethodNode methodNode) { public TypeCheckResult analyze(MethodNode methodNode) {
var valid = true;
currentLocalScope.pushScope();
List<StatementNode> statements = methodNode.statements; List<StatementNode> statements = methodNode.statements;
for (StatementNode statement : statements) { for (StatementNode statement : statements) {
if (statement instanceof AssignmentStatementNode assignmentStatementNode) { if (statement instanceof AssignmentStatementNode assignmentStatementNode) {
assignmentStatementNode.accept(this); var result = assignmentStatementNode.accept(this);
valid = valid && result.isValid();
} else if (statement instanceof VariableDeclarationStatementNode variableDeclarationStatementNode) {
var result = variableDeclarationStatementNode.accept(this);
valid = valid && result.isValid();
} }
} }
return null; return new TypeCheckResult(valid, null);
} }
@Override @Override
@ -73,19 +90,56 @@ public class SemanticAnalyzer implements SemanticVisitor {
} else { } else {
currentFields.add(toCheck.identifier); currentFields.add(toCheck.identifier);
} }
return null; return new TypeCheckResult(true, null);
} }
@Override @Override
public TypeCheckResult analyze(AssignmentStatementNode assignmentStatementNode) { public TypeCheckResult analyze(AssignmentStatementNode assignmentStatementNode) {
if (assignmentStatementNode.expression instanceof LiteralNode literalNode) { if (assignmentStatementNode.expression instanceof LiteralNode literalNode) {
VarNode varNode = assignmentStatementNode.varNode; TypeCheckResult varResult = assignmentStatementNode.varNode.accept(this);
if(varNode.getType().equals(literalNode.getType())) { TypeCheckResult expressionResult = assignmentStatementNode.expression.accept(this);
System.out.println("Type is same");
} else {
throw new RuntimeException("Type mismatch");
} }
return new TypeCheckResult(true, null);
} }
@Override
public TypeCheckResult analyze(VarNode toCheck) {
return new TypeCheckResult(true, null);
}
@Override
public TypeCheckResult analyze(BinaryExpressionNode toCheck) {
return null;
}
@Override
public TypeCheckResult analyze(IdentifierExpressionNode toCheck) {
return null;
}
@Override
public TypeCheckResult analyze(UnaryExpressionNode toCheck) {
return null;
}
@Override
public TypeCheckResult analyze(VariableDeclarationStatementNode toCheck) {
return new TypeCheckResult(true, null);
}
@Override
public TypeCheckResult analyze(IfStatementNode toCheck) {
return null;
}
@Override
public TypeCheckResult analyze(ReturnStatementNode toCheck) {
return null;
}
@Override
public TypeCheckResult analyze(WhileStatementNode toCheck) {
return null; return null;
} }

View File

@ -3,13 +3,16 @@ package semantic;
import ast.ClassNode; import ast.ClassNode;
import ast.ProgramNode; import ast.ProgramNode;
import ast.VarNode;
import ast.expression.BinaryExpressionNode;
import ast.expression.IdentifierExpressionNode;
import ast.expression.UnaryExpressionNode;
import ast.member.FieldNode; import ast.member.FieldNode;
import ast.member.MethodNode; import ast.member.MethodNode;
import ast.statement.AssignmentStatementNode; import ast.statement.*;
import typechecker.TypeCheckResult; import typechecker.TypeCheckResult;
public interface SemanticVisitor { public interface SemanticVisitor {
// TypeCheckResult typeCheck(ASTNode toCheck);
TypeCheckResult analyze(ProgramNode toCheck); TypeCheckResult analyze(ProgramNode toCheck);
@ -20,43 +23,20 @@ public interface SemanticVisitor {
TypeCheckResult analyze(FieldNode toCheck); TypeCheckResult analyze(FieldNode toCheck);
TypeCheckResult analyze(AssignmentStatementNode toCheck); TypeCheckResult analyze(AssignmentStatementNode toCheck);
//
// TypeCheckResult typeCheck(MethodParameter toCheck);
//
// TypeCheckResult typeCheck(ForStmt forStmt);
//
// TypeCheckResult typeCheck(WhileStmt whileStmt);
//
// TypeCheckResult typeCheck(ReturnStmt returnStmt);
//
// TypeCheckResult typeCheck(LocalVarDecl localVarDecl);
//
// TypeCheckResult typeCheck(IfStmt ifStmt);
//
// TypeCheckResult typeCheck(Block block);
//
// TypeCheckResult typeCheck(NewDecl newDecl);
//
// TypeCheckResult typeCheck(MethodCall methodCall);
//
// TypeCheckResult typeCheck(Unary unary);
//
// TypeCheckResult typeCheck(This aThis);
//
// TypeCheckResult typeCheck(Null aNull);
//
// TypeCheckResult typeCheck(LocalOrFieldVar localOrFieldVar);
//
// TypeCheckResult typeCheck(IntegerExpr integerExpr);
//
// TypeCheckResult typeCheck(InstVar instVar);
//
// TypeCheckResult typeCheck(CharExpr charExpr);
//
// TypeCheckResult typeCheck(BoolExpr boolExpr);
//
// TypeCheckResult typeCheck(Binary binary);
//
// TypeCheckResult typeCheck(StringExpr instVar);
TypeCheckResult analyze(VarNode toCheck);
TypeCheckResult analyze(BinaryExpressionNode toCheck);
TypeCheckResult analyze(IdentifierExpressionNode toCheck);
TypeCheckResult analyze(UnaryExpressionNode toCheck);
TypeCheckResult analyze(VariableDeclarationStatementNode toCheck);
TypeCheckResult analyze(IfStatementNode toCheck);
TypeCheckResult analyze(ReturnStatementNode toCheck);
TypeCheckResult analyze(WhileStatementNode toCheck);
} }

View File

@ -1,5 +0,0 @@
package typechecker;
public interface Type {
boolean equals(Object obj);
}

View File

@ -1,12 +1,14 @@
package typechecker; package typechecker;
import ast.type.TypeNode;
public class TypeCheckResult { public class TypeCheckResult {
private boolean valid; private boolean valid;
private Type type; private TypeNode type;
public TypeCheckResult(boolean valid, Type type) { public TypeCheckResult(boolean valid, TypeNode type) {
this.valid = valid; this.valid = valid;
this.type = type; this.type = type;
} }
@ -15,7 +17,7 @@ public class TypeCheckResult {
return valid; return valid;
} }
public Type getType() { public TypeNode getType() {
return type; return type;
} }
} }

View File

@ -1,9 +0,0 @@
package typechecker;
public class Typer {
public static void Typeify(){
}
}

View File

@ -1,9 +1,10 @@
package typechecker; package visitor;
import bytecode.visitor.ClassVisitor; import bytecode.visitor.ClassVisitor;
import bytecode.visitor.MethodVisitor; import bytecode.visitor.MethodVisitor;
import bytecode.visitor.ProgramVisitor; import bytecode.visitor.ProgramVisitor;
import semantic.SemanticVisitor; import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public interface Visitable { public interface Visitable {
default void accept(ProgramVisitor programVisitor) { default void accept(ProgramVisitor programVisitor) {