Compare commits

..

No commits in common. "f781d8eeb6d79734618fb3cf60b7a45659157cd9" and "8b6189ea333296573ab84524a739a0d0be2c77cb" have entirely different histories.

45 changed files with 226 additions and 512 deletions

2
.idea/misc.xml generated
View File

@ -40,7 +40,7 @@
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_21" default="true" project-jdk-name="openjdk-21" project-jdk-type="JavaSDK">
<component name="ProjectRootManager" version="2" languageLevel="JDK_22" default="true" project-jdk-name="openjdk-22" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

View File

@ -1,13 +1,7 @@
public class Example {
public int testVar;
public static int testMethod(char b){
int a;
int a;
a = 3;
}
}

View File

@ -1,9 +1,6 @@
import ast.ASTNode;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.Token;
import ast.ClassNode;
import ast.ProgramNode;
import bytecode.ByteCodeGenerator;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.tree.ParseTree;
@ -23,13 +20,14 @@ public class Main {
public static void main(String[] args) throws Exception {
try {
CharStream codeCharStream = CharStreams.fromPath(Paths.get("src/main/java/CompilerInput.txt"));
parseFile(codeCharStream);
parsefile(codeCharStream);
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}
}
static void parsefile(CharStream codeCharStream) {
static void parsefile(CharStream codeCharStream){
/* ------------------------- Scanner -> tokens ------------------------- */
SimpleJavaLexer lexer = new SimpleJavaLexer(codeCharStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
@ -41,8 +39,7 @@ public class Main {
for (Token token : tokens) {
String tokenType = SimpleJavaLexer.VOCABULARY.getSymbolicName(token.getType());
String tokenText = token.getText();
// System.out.println("Token Type: " + tokenType + ", Token Text: " +
// tokenText);
// System.out.println("Token Type: " + tokenType + ", Token Text: " + tokenText);
System.out.println(tokenType + " " + tokenText);
}
System.out.println();
@ -53,10 +50,9 @@ public class Main {
// Printing the parse tree
System.out.println("-------------------- Parser -> Parsetree --------------------");
System.out.println(parseTree.toStringTree(parser));
System.out.println (parseTree.toStringTree(parser));
printTree(parseTree, parser, 0);
System.out.println();
ProgramNode typedAst = (ProgramNode) SemanticAnalyzer.generateTast(ast);
/* ------------------------- AST builder -> AST ------------------------- */
ASTBuilder astBuilder = new ASTBuilder();
@ -64,36 +60,30 @@ public class Main {
// Printing the AST
System.out.println("-------------------- AST builder -> AST --------------------");
// System.out.println("AST: " + ast.toString());
//System.out.println("AST: " + ast.toString());
printAST(abstractSyntaxTree, 0);
System.out.println();
/*
* ------------------------- Semantic Analyzer -> Tast -------------------------
*/
/* ------------------------- Semantic Analyzer -> Tast ------------------------- */
SemanticAnalyzer.generateTast(abstractSyntaxTree);
// Printing the Tast
System.out.println("Tast generated");
/*
* ------------------------- Bytecode Generator -> Bytecode
* -------------------------
*/
/* ------------------------- Bytecode Generator -> Bytecode ------------------------- */
ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator();
byteCodeGenerator.generateByteCode(abstractSyntaxTree);
System.out.println("Bytecode generated");
}
/**
* This method is used to print the parse tree in a structured format.
* It recursively traverses the tree and prints the rule names and text of the
* nodes.
* It recursively traverses the tree and prints the rule names and text of the nodes.
*
* @param tree The parse tree to be printed.
* @param parser The parser used to parse the input. It's used to get the rule
* names.
* @param parser The parser used to parse the input. It's used to get the rule names.
* @param indent The current indentation level. It's used to format the output.
*/
public static void printTree(ParseTree tree, Parser parser, int indent) {
@ -112,20 +102,19 @@ public class Main {
System.out.println(indentString + tree.getText());
}
// Recursively print the children of the current node, increasing the
// indentation level
// Recursively print the children of the current node, increasing the indentation level
for (int i = 0; i < tree.getChildCount(); i++) {
printTree(tree.getChild(i), parser, indent + 1);
}
}
public static void printAST(ASTNode node, int indent) {
String indentString = " ".repeat(indent * 2);
System.out.println(indentString + node.getClass().toString());
// for (ASTNode child : node.) {
// printAST(child, indent + 1);
// }
byteCodeGenerator.visit(typedAst);
for (ASTNode child : node.) {
printAST(child, indent + 1);
}
}
}

View File

@ -1,6 +1,6 @@
package ast;
public interface ASTNode {
public class ASTNode {
}

View File

@ -7,13 +7,11 @@ import ast.type.EnumAccessTypeNode;
import java.util.ArrayList;
import java.util.List;
import bytecode.visitor.ClassVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
import typechecker.Visitable;
public class ClassNode implements ASTNode, Visitable {
public class ClassNode extends ASTNode implements Visitable {
public String identifier;
public AccessTypeNode accessType;
public List<MemberNode> members = new ArrayList<>();
@ -40,11 +38,6 @@ public class ClassNode implements ASTNode, Visitable {
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
@Override
public void accept(ClassVisitor classVisitor) {
classVisitor.visit(this);
return visitor.typeCheck(this);
}
}

View File

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

View File

@ -2,13 +2,11 @@ package ast;
import java.util.ArrayList;
import java.util.List;
import bytecode.visitor.ProgramVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
import typechecker.Visitable;
public class ProgramNode implements ASTNode, Visitable{
public class ProgramNode extends ASTNode implements Visitable{
public List<ClassNode> classes = new ArrayList<>();
public void addClass(ClassNode classNode) {
@ -17,11 +15,6 @@ public class ProgramNode implements ASTNode, Visitable{
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
@Override
public void accept(ProgramVisitor programVisitor) {
programVisitor.visit(this);
return visitor.typeCheck(this);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,16 +1,9 @@
package ast.member;
import ast.type.AccessTypeNode;
import bytecode.visitor.MethodVisitor;
import visitor.Visitable;
public class ConstructorNode extends MethodNode implements Visitable {
public class ConstructorNode extends MethodNode {
public ConstructorNode(AccessTypeNode visibility, String name) {
super(visibility, name);
}
@Override
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
}
}

View File

@ -2,12 +2,11 @@ package ast.member;
import ast.type.AccessTypeNode;
import ast.type.TypeNode;
import bytecode.visitor.ClassVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
import typechecker.Visitable;
public class FieldNode implements MemberNode, Visitable {
public class FieldNode extends MemberNode implements Visitable {
public AccessTypeNode accessTypeNode;
public TypeNode type;
public String identifier;
@ -20,11 +19,6 @@ public class FieldNode implements MemberNode, Visitable {
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
@Override
public void accept(ClassVisitor classVisitor) {
classVisitor.visit(this);
return visitor.typeCheck(this);
}
}

View File

@ -2,5 +2,5 @@ package ast.member;
import ast.ASTNode;
public interface MemberNode extends ASTNode {
public class MemberNode extends ASTNode {
}

View File

@ -3,17 +3,15 @@ package ast.member;
import ast.parameter.ParameterListNode;
import ast.statement.StatementNode;
import ast.type.AccessTypeNode;
import ast.type.TypeNode;
import java.util.ArrayList;
import java.util.List;
import ast.type.TypeNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
import typechecker.Visitable;
public class MethodNode implements MemberNode, Visitable {
public class MethodNode extends MemberNode implements Visitable {
public AccessTypeNode visibility;
public TypeNode type;
public String identifier;
@ -38,11 +36,6 @@ public class MethodNode implements MemberNode, Visitable {
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
@Override
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
return visitor.typeCheck(this);
}
}

View File

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

View File

@ -3,7 +3,7 @@ package ast.parameter;
import ast.ASTNode;
import ast.type.TypeNode;
public class ParameterNode implements ASTNode {
public class ParameterNode extends ASTNode {
public TypeNode type;
public String identifier;

View File

@ -4,7 +4,7 @@ import ast.VarNode;
import ast.expression.ExpressionNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
import typechecker.Visitable;
public class AssignmentStatementNode extends StatementNode implements Visitable {
public VarNode varNode;
@ -17,6 +17,6 @@ public class AssignmentStatementNode extends StatementNode implements Visitable
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
return visitor.typeCheck(this);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -2,7 +2,7 @@ package ast.type;
import ast.ASTNode;
public class AccessTypeNode implements ASTNode {
public class AccessTypeNode extends ASTNode {
public EnumAccessTypeNode enumAccessTypeNode;
public AccessTypeNode(EnumAccessTypeNode enumAccessTypeNode) {

View File

@ -1,13 +0,0 @@
package ast.type;
import ast.ASTNode;
public class BaseTypeNode implements ASTNode, TypeNode {
public EnumTypeNode enumType;
public BaseTypeNode(EnumTypeNode enumType) {
this.enumType = enumType;
}
}

View File

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

View File

@ -2,5 +2,10 @@ package ast.type;
import ast.ASTNode;
public interface TypeNode extends ASTNode {
public class TypeNode extends ASTNode {
public EnumTypeNode enumTypeNode;
public TypeNode(EnumTypeNode enumTypeNode) {
this.enumTypeNode = enumTypeNode;
}
}

View File

@ -2,15 +2,13 @@ package bytecode;
import ast.ProgramNode;
import ast.ClassNode;
import bytecode.visitor.ProgramVisitor;
public class ByteCodeGenerator implements ProgramVisitor {
public class ByteCodeGenerator {
@Override
public void visit(ProgramNode programNode) {
for (ClassNode classDeclarationNode : programNode.classes) {
public void generateByteCode(ProgramNode ast) {
for (ClassNode classDeclarationNode : ast.classes) {
ClassCodeGen classCodeGen = new ClassCodeGen();
classDeclarationNode.accept(classCodeGen);
classCodeGen.generateClassCode(classDeclarationNode);
}
}
}

View File

@ -4,8 +4,6 @@ import ast.ClassNode;
import ast.member.FieldNode;
import ast.member.MemberNode;
import ast.member.MethodNode;
import ast.type.BaseTypeNode;
import bytecode.visitor.ClassVisitor;
import java.io.File;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
@ -13,22 +11,20 @@ import org.objectweb.asm.Opcodes;
import java.io.FileOutputStream;
import java.io.IOException;
public class ClassCodeGen implements ClassVisitor {
public class ClassCodeGen {
public void generateClassCode(ClassNode classNode) {
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
Mapper mapper = new Mapper();
ClassWriter classWriter;
@Override
public void visit(ClassNode classNode) {
classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS);
classWriter.visit(Opcodes.V1_8, mapper.mapAccesTypeToOpcode(classNode.accessType), classNode.identifier, null,
"java/lang/Object", null);
for (MemberNode memberNode : classNode.members) {
if (memberNode instanceof FieldNode) {
visit((FieldNode) memberNode);
FieldCodeGen fieldCodeGen = new FieldCodeGen();
fieldCodeGen.generateFieldCode(classWriter, (FieldNode) memberNode);
} else if (memberNode instanceof MethodNode) {
MethodCodeGen methodCodeGen = new MethodCodeGen(classWriter);
((MethodNode) memberNode).accept(methodCodeGen);
MethodCodeGen methodCodeGen = new MethodCodeGen();
methodCodeGen.generateMethodCode(classWriter, (MethodNode) memberNode);
}
}
@ -38,14 +34,6 @@ public class ClassCodeGen implements ClassVisitor {
classWriter.visitEnd();
}
@Override
public void visit(FieldNode fieldNode) {
if(fieldNode.type instanceof BaseTypeNode baseTypeNode){
classWriter.visitField(mapper.mapAccesTypeToOpcode(fieldNode.accessTypeNode), fieldNode.identifier, mapper.getTypeChar(baseTypeNode.enumType), null, null );
}
classWriter.visitEnd();
}
private void printIntoClassFile(byte[] byteCode, String name) {
String directoryPath = "src/main/java/classFileOutput";
File directory = new File(directoryPath);

View File

@ -1,8 +1,8 @@
package bytecode;
import ast.type.*;
import ast.type.AccessTypeNode;
import ast.type.EnumAccessTypeNode;
import org.objectweb.asm.Opcodes;
import ast.type.BaseTypeNode;
public class Mapper {
public int mapAccesTypeToOpcode(AccessTypeNode type) {
@ -14,26 +14,4 @@ public class Mapper {
}
return 0;
}
public String generateMethodDescriptor(BaseTypeNode baseTypeNode) {
String descriptor = "()";
descriptor += getTypeChar(baseTypeNode.enumType);
return descriptor;
}
public String getTypeChar(EnumTypeNode enumTypeNode) {
String typeChar = "";
switch (enumTypeNode) {
case EnumTypeNode.INT:
typeChar = "I";
break;
case EnumTypeNode.CHAR:
typeChar = "C";
break;
case EnumTypeNode.BOOLEAN:
typeChar = "Z";
break;
}
return typeChar;
}
}

View File

@ -1,40 +1,17 @@
package bytecode;
import ast.member.ConstructorNode;
import ast.member.MethodNode;
import ast.type.BaseTypeNode;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
private ClassWriter classWriter;
public class MethodCodeGen {
public void generateMethodCode(ClassWriter classWriter, MethodNode methodNode) {
Mapper mapper = new Mapper();
public MethodCodeGen(ClassWriter classWriter) {
this.classWriter = classWriter;
}
@Override
public void visit(ConstructorNode constructorNode) {
MethodVisitor constructor =
classWriter.visitMethod(mapper.mapAccesTypeToOpcode(constructorNode.visibility),
classWriter.visitMethod(mapper.mapAccesTypeToOpcode(methodNode.visibility),
"<init>",
"()V",
null,
null);
constructor.visitEnd();
}
@Override
public void visit(MethodNode methodNode) {
if(methodNode.type instanceof BaseTypeNode baseTypeNode){
MethodVisitor method = classWriter.visitMethod(mapper.mapAccesTypeToOpcode(methodNode.visibility),
methodNode.identifier,
mapper.generateMethodDescriptor(baseTypeNode),
null,
null);
method.visitEnd();
}
}
}

View File

@ -1,10 +0,0 @@
package bytecode.visitor;
import ast.ClassNode;
import ast.member.FieldNode;
import org.objectweb.asm.ClassWriter;
public interface ClassVisitor {
void visit(ClassNode classNode);
void visit(FieldNode fieldNode);
}

View File

@ -1,9 +0,0 @@
package bytecode.visitor;
import ast.member.ConstructorNode;
import ast.member.MethodNode;
public interface MethodVisitor {
void visit(ConstructorNode constructorNode);
void visit(MethodNode methodNode);
}

View File

@ -1,7 +0,0 @@
package bytecode.visitor;
import ast.ProgramNode;
public interface ProgramVisitor {
void visit(ProgramNode programNode);
}

View File

@ -11,14 +11,15 @@ import ast.member.MethodNode;
import ast.parameter.ParameterListNode;
import ast.parameter.ParameterNode;
import ast.statement.*;
import ast.type.*;
import ast.type.AccessTypeNode;
import ast.type.EnumAccessTypeNode;
import ast.type.EnumTypeNode;
import ast.type.TypeNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.ArrayList;
import java.util.List;
import parser.generated.*;
import parser.generated.SimpleJavaParser.LiteralContext;
import ast.type.BaseTypeNode;
public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
@Override
@ -76,9 +77,9 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
@Override
public ASTNode visitParameter(SimpleJavaParser.ParameterContext ctx) {
TypeNode typeNode = (TypeNode) visit(ctx.type());
TypeNode type = (TypeNode) visit(ctx.type());
String identifier = ctx.IDENTIFIER().getText();
return new ParameterNode(typeNode, identifier);
return new ParameterNode(type, identifier);
}
@Override
@ -86,11 +87,11 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
String typeStr = ctx.getText();
switch (typeStr) {
case "int":
return new BaseTypeNode(EnumTypeNode.INT);
return new TypeNode(EnumTypeNode.INT);
case "boolean":
return new BaseTypeNode(EnumTypeNode.BOOLEAN);
return new TypeNode(EnumTypeNode.BOOLEAN);
case "char":
return new BaseTypeNode(EnumTypeNode.CHAR);
return new TypeNode(EnumTypeNode.CHAR);
default:
throw new IllegalArgumentException("Unsupported type: " + typeStr);
}
@ -206,7 +207,6 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
try {
int intValue = Integer.parseInt(literalContext.getText());
LiteralNode literalNode = new LiteralNode(intValue);
literalNode.setType("int");
return literalNode;
} catch (NumberFormatException ignored) {}

View File

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

View File

@ -3,40 +3,60 @@ package semantic;
import ast.ClassNode;
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.MethodNode;
import ast.statement.*;
import ast.statement.AssignmentStatementNode;
import typechecker.TypeCheckResult;
public interface SemanticVisitor {
// TypeCheckResult typeCheck(ASTNode toCheck);
TypeCheckResult analyze(ProgramNode toCheck);
TypeCheckResult typeCheck(ProgramNode toCheck);
TypeCheckResult analyze(ClassNode toCheck);
TypeCheckResult typeCheck(ClassNode toCheck);
TypeCheckResult analyze(MethodNode toCheck);
TypeCheckResult typeCheck(MethodNode toCheck);
TypeCheckResult analyze(FieldNode toCheck);
TypeCheckResult typeCheck(FieldNode toCheck);
TypeCheckResult analyze(AssignmentStatementNode toCheck);
TypeCheckResult typeCheck(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

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

View File

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

View File

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

View File

@ -0,0 +1,16 @@
package typechecker;
import semantic.SemanticVisitor;
public interface Visitable {
// default void accept(ProgramCodeVisitor visitor) {
// }
//
// default void accept(ClassCodeVisitor visitor) {
// }
//
// default void accept(MethodCodeVisitor visitor) {
// }
TypeCheckResult accept(SemanticVisitor visitor);
}

View File

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