14 Commits

Author SHA1 Message Date
4bee432294 Merge remote-tracking branch 'origin/Endabgabe' into Endabgabe
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 22:24:59 +02:00
0cf4715782 Fixes of Constructor 2024-07-04 22:24:50 +02:00
Purplumbi504
3c0f7e857a Adding comments to ASTBuilder und ANTL Grammar
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 21:57:53 +02:00
Purplumbi504
2b7e0d0d42 Changing location of Makefile
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 21:13:38 +02:00
Purplumbi504
bd61a0e595 Merge remote-tracking branch 'origin/Endabgabe' into Endabgabe
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 21:11:35 +02:00
Purplumbi504
24407a5c1c Revert test case directory: singleFeatureTests 2024-07-04 21:11:21 +02:00
195440e9d9 Added SemanticAnalyzer ElseIfStatement
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 20:49:54 +02:00
6fa57cf319 Type Error Change
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 20:36:36 +02:00
1de6add080 Fixe Type Error
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 20:23:43 +02:00
c315966219 Merge remote-tracking branch 'origin/Endabgabe' into Endabgabe
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 19:45:09 +02:00
c2c4974c76 More Abgabe Tests working 2024-07-04 19:44:59 +02:00
Purplumbi504
85e0cf3807 Revert test case directory: singleFeatureTests
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 19:10:21 +02:00
Purplumbi504
6f3fb02666 Fixing test case directory: singleFeatureTests
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 19:03:44 +02:00
Purplumbi504
435697053a Fixing ReflectionTests
Some checks are pending
Gitea Actions Demo / Explore-Gitea-Actions (push) Waiting to run
2024-07-04 18:57:36 +02:00
84 changed files with 1030 additions and 2680 deletions

6
.gitignore vendored
View File

@@ -77,10 +77,10 @@ fabric.properties
.idea/caches/build_file_checksums.ser
/target
src/main/resources/logs/RaupenLog.log
src/main/resources/logs/miniCompilerLog.log
src/main/resources/output/CompilerInput.class
src/test/resources/output/javac/CompilerInput$Test.class
src/test/resources/output/javac/CompilerInput.class
src/test/resources/output/raupenpiler/CompilerInput.class
src/test/resources/output/raupenpiler/CompilerInput$Test.class
src/test/resources/output/miniCompiler/CompilerInput.class
src/test/resources/output/miniCompiler/CompilerInput$Test.class
.idea/inspectionProfiles/Project_Default.xml

37
Makefile Normal file
View File

@@ -0,0 +1,37 @@
### IntelliJs play buttons do not work. Run in "src/test" folder with "make" command to run all
### Or run only parts with "make compile-javac", "make clean" etc.
all: compile-javac compile-miniCompiler
compile-javac:
#javac -d src/test/resources/output/javac src/test/resources/input/CompilerInput.java
compile-miniCompiler:
cd ../.. ; mvn -DskipTests install
cd ../.. ; mvn exec:java -DgenJar=true -DgenClass=true -Dexec.mainClass="main.Main" -Dexec.args="'src/main/resources/input/CompilerInput.java' 'src/main/resources/output'"
# cp src/main/resources/output/CompilerInput.class src/test/resources/output/miniCompiler
test-miniCompiler:
# move the compiled class to the test/main folder
mv src/main/resources/output/CompilerInput.class src/test/java/main/
# compile the test class
javac src/test/java/main/EndToEndTester.java
# run the test class
java -cp src/test/java/main EndToEndTester
clean:
# clean main output folders
rm -f src/main/resources/output/*.class
rm -f src/main/resources/output/*.jar
# clean resources output folders
rm -f src/test/resources/output/javac/*.class
rm -f src/test/resources/output/miniCompiler/*.class
rm -f src/test/resources/output/miniCompiler/*.jar
# clean logs
rm -f src/main/resources/logs/*
# clean test/java/main folders from .class files for End-to-End tests
rm -f src/test/java/main/*.class
# clean javac output from every folder
rm -f src/test/resources/input/*/*.class
# clean test results from maven surefire plugin
rm -f ../../target/surefire-reports/*.txt

134
README.md Normal file
View File

@@ -0,0 +1,134 @@
# "Nicht Haskel 2.0" Java Compiler
Realisation of a subset of the Java Standard Compiler in the course Compiler Construction of the 4th semester Computer Science at the Duale Hochschule Stuttgart (Horb).
This project aims to provide a simplified version of the Java compiler, focusing on key language features and demonstrating the principles of compiler construction.
## Realised Java syntax
- **Data types**: `int`, `boolean`, `char`
- **Access modifier**: `public`, `protected`, `private`
- **Operators**: `=` `+` `-` `*` `%` `/` `>` `<` `>=` `<=` `==` `!=` `!` `&&` `||` `++` `--`
- **Keywords**: `class`, `this`, `while`, `do`, `if`, `else`, `for`, `return`, `new`, `switch`, `case`, `break`, `default`, `:`
- **Statements**:
- `if` ... `if else` ... `else`;
- `while` ... ;
- `do` ... `while`;
- `for`;
- `switch` ... `case` ... ;
- **Comments**:
- Single line: `// comment`
- Multi-line: `/* comment */`
- **Further functions**:
- All methods are overloadable
- High maintainability and expandability through implementation of the visitor pattern
- Logging Input and Outputs
- Error Handling in the Semantic Check
## Project Structure
```plain
src/
└── main/
├── java/
│ ├── ast/ -> Defining the structure of the AST
│ ├── bytecode/ -> Generate Java bytecode
│ ├── main/ -> Running the compiler
│ ├── parser/
│ │ ├── astBuilder/ -> Builder creating the AST
│ │ ├── generated/ -> Antlr generated grammar
│ │ └── grammar/ -> Antlr grammar
│ ├── semantic/ -> Running the semantic check
│ └── visitor/ -> Visitor interface
└── resources/
test/
└── java/
│ ├── main/ -> Running E2E tests
│ ├── parser/ -> Performs tests on the parser
│ ├── semantic/ -> Performs tests on the semantic check
└── resources/ -> Ressources for running the Tests
```
## Class-Diagramm AST
![AST Diagramm](ast.png)
## Distribution of the realisation
### i22030 & i22035
Parser:
- Grammar -> (src/main/java/parser/grammar)
- Scanner
- Parser
- Abstract Syntax Tree (AST) -> (src/main/java/ast)
- AstBuilder -> (src/main/java/parser/astBuilder)
Parser tests:
- ParserTests -> (src/test/java/parser)
- TestCases -> (src/test/resources/input/singeFeatureTests)
Other:
- Documentation -> (README.md)
- Ast Class-Diagramm -> (ast.png)
- PowerPoint
### i22005
Semantic check:
- Set all types and check whether types have been used correctly
- Contexts -> (src/main/java/semantic/context)
- Exceptions Handling -> (src/main/java/semantic/exceptions)
Semantic Tests:
- Typing and Type checking -> (src/test/java/semantic/EndToTypedAstTest)
- Exception and feature test -> (src/test/resources/input/typedAstExceptionsTests)
### i22007
Bytecode generation:
- Complete bytecode generation -> (src/mein/java/bytecode)
### i22011
Tests and execution:
- Makefile
- Running Compiler -> (src/main/main)
- Running E2E tests -> (src/test/main)
- Typing and Type checking -> (src/test/java/semantic/EndToTypedAstTest)
## Used Tools
- [Maven 4.0](https://maven.apache.org/index.html)
- Used for automating the build process and managing dependencies.
- [ANTLR4 v.13.1](https://www.antlr.org/)
- Used to parse the input Java code into the Abstract Syntax Tree.
## How to run the compiler
### Possibilities
### 1. Start miniCompiler using make:
Make needs to be installed
```bash
cd .\src\test\ ; make clean compile-miniCompiler
```
### 2. Start miniCompiler using jar:
If you do not have the .jar, download it [here](https://gitea.hb.dhbw-stuttgart.de/i22005/NichtHaskell2.0/src/branch/Endabgabe/src) or compile it using mvn package or make first
```
java.exe -DgenJar=bool -DgenClass=bool -jar path_to_jar\jarName.jar 'path_to_input_file.java' 'path_to_output_directory'
```
Example (jar needs to be in the target directory)
```bash
java.exe -DgenJar=true -DgenClass=true -jar .\target\JavaCompiler-1.0-jar-with-dependencies.jar 'src/main/resources/input/CompilerInput.java' 'src/main/resources/output'
```
- set DgenJar true, to generate the jar, false for no jar
```
DgenJar=true
```
- set DgenClass true, to generate class files, false for no class files
```
DgenClass=true
```

BIN
ast.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 MiB

View File

@@ -1,68 +0,0 @@
# "Nicht Haskel 2.0" Java Compiler
Realisation of a subset of the Java Standard Compiler in the course Compiler Construction of the 4th semester Computer Science at the Duale Hochschule Suttgart (Horb).
This project aims to provide a simplified version of the Java compiler, focusing on key language features and demonstrating the principles of compiler construction.
## Realised Java syntax
- **Data types**: `int`, `boolean`, `char`
- **Access modifier**: `public`, `protected`, `private`
- **Operators**: `=` `+` `-` `*` `%` `/` `>` `<` `>=` `<=` `==` `!=` `!` `&&` `||` `++` `--`
- **Keywords**: `class`, `this`, `while`, `do`, `if`, `else`, `for`, `return`, `new`, `switch`, `case`, `break`, `default`, `:`
- **Statements**:
- `if` ... `if else` ... `else`;
- `while` ... ;
- `do` ... `while`;
- `for`;
- `switch` ... `case` ... ;
- **Comments**:
- Single line: `// comment`
- Multi-line: `/* comment */`
- **Further functions**:
- All methods are overloadable
- High maintainability and expandability through implementation of the visitor pattern
- Logging Input and Outputs
- Error Handling in the Semantic Check
## Project Structure
```plain
src/
└── main/
├── java/
│ ├── ast/ -> Defining the structure of the AST
│ ├── bytecode/ -> Generate Java bytecode
│ ├── main/ -> Running the compiler
│ ├── parser/
│ │ ├── astBuilder/ -> Builder creating the AST
│ │ ├── generated/ -> Antlr generated grammar
│ │ └── grammar/ -> Antlr grammar
│ ├── semantic/ -> Running the semantic check
│ └── visitor/ -> Visitor interface
└── resources/
test/
└── java/
│ ├── main/ -> MainTest, E2ETests, UtilityTests
│ ├── parser/ -> Performs tests on the parser
│ └── semantic/ -> Performs tests on the semantic check
└── resources/ -> Ressources for running the Tests
```
## Class-Diagramm AST
![AST Diagramm](ast.png)
## Used Tools
- [Maven 4.0](https://maven.apache.org/index.html)
- Used for automating the build process and managing dependencies.
- [ANTLR4 v.13.1](https://www.antlr.org/)
- Used to parse the input Java code into the Abstract Syntax Tree.
## How to run the compiler
## Download
```bash

View File

@@ -1,20 +1,6 @@
package ast;
import bytecode.visitor.ClassVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public interface ASTNode {
//Todo: @BruderJohn & @i22007 Interface anwenden + geeignetetn Methodename.
/*
Typecheck:
public TypeCheckResult acceptType(SemanticVisitor visitor);
Bytecode:
public void accepByteCode(ClassVisitor classVisitor);
*/
}

View File

@@ -1,12 +1,11 @@
package ast;
import ast.type.AccessModifierNode;
import ast.members.ConstructorNode;
import ast.members.MemberNode;
import ast.members.MethodNode;
import bytecode.visitor.ClassVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
import java.util.ArrayList;
@@ -17,11 +16,11 @@ public class ClassNode implements ASTNode, Visitable {
public String identifier;
public List<MemberNode> members = new ArrayList<>();
public ClassNode(){
public ClassNode() {
}
public ClassNode(String accessType, String identifier){
public ClassNode(String accessType, String identifier) {
this.accessType = new AccessModifierNode(accessType);
this.identifier = identifier;
}
@@ -30,7 +29,7 @@ public class ClassNode implements ASTNode, Visitable {
members.add(member);
}
public List<MethodNode> getMethods(){
public List<MethodNode> getMethods() {
List<MethodNode> methods = new ArrayList<>();
for (MemberNode member : members) {
if (member instanceof MethodNode methodNode) {

View File

@@ -2,7 +2,7 @@ package ast;
import bytecode.visitor.ProgramVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
import java.util.ArrayList;

View File

@@ -4,12 +4,12 @@ import ast.expressions.IExpressionNode;
import ast.type.type.*;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
public class BinaryNode implements IExpressionNode, Visitable {
private ITypeNode typeNode;
public ITypeNode typeNode;
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {

View File

@@ -1,9 +1,8 @@
package ast.expressions.binaryexpressions;
import ast.type.type.*;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class CalculationNode extends BinaryNode {
public CalculationNode calculationExpression;
@@ -20,11 +19,11 @@ public class CalculationNode extends BinaryNode {
this.dotExpression = dotExpression;
}
private void setOperator(String operator) {
if(operator != null) {
if(operator.equals("+")) {
public void setOperator(String operator) {
if (operator != null) {
if (operator.equals("+")) {
this.operator = EnumLineOperator.PLUS;
} else if(operator.equals("-")) {
} else if (operator.equals("-")) {
this.operator = EnumLineOperator.MINUS;
}
}

View File

@@ -2,30 +2,28 @@ package ast.expressions.binaryexpressions;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class DotNode extends BinaryNode {
public DotNode dotExpression;
public EnumDotOperator operator;
public DotSubstractionNode dotSubstractionExpression;
public DotSubtractionNode dotSubtractionExpression;
public DotNode(DotNode dotExpression, String operator, DotSubstractionNode dotSubstractionExpression) {
public DotNode(DotNode dotExpression, String operator, DotSubtractionNode dotSubtractionExpression) {
this.dotExpression = dotExpression;
setOperator(operator);
this.dotSubstractionExpression = dotSubstractionExpression;
this.dotSubtractionExpression = dotSubtractionExpression;
}
public DotNode(DotSubstractionNode dotSubstractionExpression) {
this.dotSubstractionExpression = dotSubstractionExpression;
public DotNode(DotSubtractionNode dotSubtractionExpression) {
this.dotSubtractionExpression = dotSubtractionExpression;
}
private void setOperator(String operator) {
if(operator.equals("*")) {
this.operator = EnumDotOperator.MULT;
} else if(operator.equals("/")) {
this.operator = EnumDotOperator.DIV;
} else if(operator.equals("%")) {
this.operator = EnumDotOperator.MOD;
public void setOperator(String operator) {
switch (operator) {
case "*" -> this.operator = EnumDotOperator.MULT;
case "/" -> this.operator = EnumDotOperator.DIV;
case "%" -> this.operator = EnumDotOperator.MOD;
}
}

View File

@@ -1,45 +1,44 @@
package ast.expressions.binaryexpressions;
import ast.expressions.unaryexpressions.MemberAccessNode;
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
import ast.type.type.*;
import ast.type.ValueNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public class DotSubstractionNode extends BinaryNode {
public ValueNode value;
public String identifier;
public MemberAccessNode memberAccess;
public MethodCallNode methodCall;
public CalculationNode calculationExpression;
public DotSubstractionNode(ValueNode value) {
this.value = value;
}
public DotSubstractionNode(String identifier) {
this.identifier = identifier;
}
public DotSubstractionNode(MemberAccessNode memberAccess) {
this.memberAccess = memberAccess;
}
public DotSubstractionNode(MethodCallNode methodCall, CalculationNode calculationExpression) {
this.methodCall = methodCall;
this.calculationExpression = calculationExpression;
}
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
@Override
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
}
}
package ast.expressions.binaryexpressions;
import ast.expressions.unaryexpressions.MemberAccessNode;
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
import ast.type.ValueNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import semantic.TypeCheckResult;
public class DotSubtractionNode extends BinaryNode {
public ValueNode value;
public String identifier;
public MemberAccessNode memberAccess;
public MethodCallNode methodCall;
public CalculationNode calculationExpression;
public DotSubtractionNode(ValueNode value) {
this.value = value;
}
public DotSubtractionNode(String identifier) {
this.identifier = identifier;
}
public DotSubtractionNode(MemberAccessNode memberAccess) {
this.memberAccess = memberAccess;
}
public DotSubtractionNode(MethodCallNode methodCall, CalculationNode calculationExpression) {
this.methodCall = methodCall;
this.calculationExpression = calculationExpression;
}
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
@Override
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
}
}

View File

@@ -2,10 +2,9 @@ package ast.expressions.binaryexpressions;
import ast.expressions.IExpressionNode;
import ast.expressions.unaryexpressions.UnaryNode;
import ast.type.type.*;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class NonCalculationNode extends BinaryNode {
public UnaryNode unaryExpression;
@@ -18,23 +17,16 @@ public class NonCalculationNode extends BinaryNode {
this.expression = expression;
}
private void setOperator(String operator) {
if(operator.equals("&&")) {
this.operator = EnumNonCalculationOperator.AND;
} else if(operator.equals("||")) {
this.operator = EnumNonCalculationOperator.OR;
} else if(operator.equals(">")) {
this.operator = EnumNonCalculationOperator.GREATER;
} else if(operator.equals("<")) {
this.operator = EnumNonCalculationOperator.LESS;
} else if(operator.equals(">=")) {
this.operator = EnumNonCalculationOperator.GREATER_EQUAL;
} else if(operator.equals("<=")) {
this.operator = EnumNonCalculationOperator.LESS_EQUAL;
} else if(operator.equals("==")) {
this.operator = EnumNonCalculationOperator.EQUAL;
} else if(operator.equals("!=")) {
this.operator = EnumNonCalculationOperator.NOT_EQUAL;
public void setOperator(String operator) {
switch (operator) {
case "&&" -> this.operator = EnumNonCalculationOperator.AND;
case "||" -> this.operator = EnumNonCalculationOperator.OR;
case ">" -> this.operator = EnumNonCalculationOperator.GREATER;
case "<" -> this.operator = EnumNonCalculationOperator.LESS;
case ">=" -> this.operator = EnumNonCalculationOperator.GREATER_EQUAL;
case "<=" -> this.operator = EnumNonCalculationOperator.LESS_EQUAL;
case "==" -> this.operator = EnumNonCalculationOperator.EQUAL;
case "!=" -> this.operator = EnumNonCalculationOperator.NOT_EQUAL;
}
}

View File

@@ -1,10 +1,11 @@
package ast.expressions.unaryexpressions;
import ast.ASTNode;
import bytecode.visitor.MethodVisitor;
import ast.type.type.ITypeNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
import java.util.ArrayList;
@@ -27,7 +28,7 @@ public class MemberAccessNode implements ASTNode, Visitable {
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
}
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);
}
@@ -40,4 +41,5 @@ public class MemberAccessNode implements ASTNode, Visitable {
this.typeNode = typeNode;
}
}

View File

@@ -1,13 +1,12 @@
package ast.expressions.unaryexpressions;
import ast.ASTNode;
import ast.expressions.IExpressionNode;
import ast.type.type.ITypeNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
import semantic.TypeCheckResult;
public class NotNode implements ASTNode, Visitable {
public class NotNode implements IExpressionNode {
public IExpressionNode expression;
public NotNode(IExpressionNode expression) {
@@ -24,4 +23,13 @@ public class NotNode implements ASTNode, Visitable {
return null;
}
}
@Override
public ITypeNode getType() {
return expression.getType();
}
@Override
public void setType(ITypeNode type) {
this.expression.setType(type);
}
}

View File

@@ -6,7 +6,7 @@ import ast.type.type.*;
import ast.type.ValueNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import java.util.Objects;
@@ -18,10 +18,10 @@ public class UnaryNode implements IExpressionNode {
public NotNode notExpression;
public IStatementNode statement;
public IExpressionNode expression;
private ITypeNode type;
public ITypeNode type;
public UnaryNode(String value) {
if(Objects.equals(value, "this")) {
if (Objects.equals(value, "this")) {
this.thisExp = "this";
} else {
this.identifier = value;

View File

@@ -1,11 +0,0 @@
package ast.literal;
public class BooleanLiteralNode {
private String value;
public BooleanLiteralNode(String value) {this.value = value;}
public String getValue() {
return value;
}
}

View File

@@ -1,11 +0,0 @@
package ast.literal;
public class CharLiteralNode {
public String value;
public CharLiteralNode(String value) {this.value = value;}
public String getValue() {
return value;
}
}

View File

@@ -1,31 +0,0 @@
package ast.literal;
import ast.expressions.IExpressionNode;
import ast.type.type.ITypeNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
public class LiteralNode implements IExpressionNode {
public String value;
private ITypeNode type;
public LiteralNode(String value, ITypeNode type) {
this.value = value;
this.type = type;
}
public ITypeNode getType() {
return type;
}
public void setType(ITypeNode type) {
this.type = type;
}
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return null;
}
}

View File

@@ -11,13 +11,8 @@ import java.util.List;
import java.util.Objects;
public class ConstructorNode extends MethodNode implements Visitable {
public AccessModifierNode accessType;
public String identifier;
public List<ParameterNode> parameters = new ArrayList<>();
public BlockNode block;
public ConstructorNode(String accessType, String identifier, BlockNode block) {
this.accessType = new AccessModifierNode(accessType);
this.accesModifier = new AccessModifierNode(accessType);
this.identifier = identifier;
this.block = block;
}
@@ -32,8 +27,7 @@ public class ConstructorNode extends MethodNode implements Visitable {
}
public boolean isSame(MethodNode methodNode) {
if (!(Objects.equals(this.identifier, methodNode.getIdentifier()))
|| getParameters().size() != methodNode.getParameters().size()) {
if (!(Objects.equals(this.identifier, methodNode.getIdentifier())) || getParameters().size() != methodNode.getParameters().size()) {
return false;
}

View File

@@ -3,9 +3,8 @@ package ast.members;
import ast.type.AccessModifierNode;
import ast.type.type.ITypeNode;
import bytecode.visitor.ClassVisitor;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
public class FieldNode implements MemberNode, Visitable {
@@ -13,7 +12,7 @@ public class FieldNode implements MemberNode, Visitable {
public ITypeNode type;
public String identifier;
public FieldNode(AccessModifierNode accessTypeNode, ITypeNode type, String name){
public FieldNode(AccessModifierNode accessTypeNode, ITypeNode type, String name) {
this.accessTypeNode = accessTypeNode;
this.type = type;
this.identifier = name;

View File

@@ -10,7 +10,8 @@ import ast.ASTNode;
@JsonSubTypes({
@JsonSubTypes.Type(value = MethodNode.class, name = "Method"),
@JsonSubTypes.Type(value = FieldNode.class, name = "Field") }
@JsonSubTypes.Type(value = FieldNode.class, name = "Field")}
)
public interface MemberNode extends ASTNode {}
public interface MemberNode extends ASTNode {
}

View File

@@ -6,7 +6,7 @@ import ast.type.AccessModifierNode;
import ast.type.type.*;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
import java.util.ArrayList;
@@ -15,16 +15,16 @@ import java.util.Objects;
public class MethodNode implements MemberNode, Visitable {
public AccessModifierNode accesModifier;
private ITypeNode type;
public ITypeNode type;
public Boolean voidType;
private String identifier;
public String identifier;
public List<ParameterNode> parameters = new ArrayList<>();
public BlockNode block;
public MethodNode() {
}
public MethodNode(String accessModifier, ITypeNode type, Boolean voidType, String identifier, BlockNode block){
public MethodNode(String accessModifier, ITypeNode type, Boolean voidType, String identifier, BlockNode block) {
this.accesModifier = new AccessModifierNode(accessModifier);
this.type = type;
this.voidType = voidType;
@@ -40,7 +40,7 @@ public class MethodNode implements MemberNode, Visitable {
return parameters;
}
public boolean isSame(MethodNode methodNode){
public boolean isSame(MethodNode methodNode) {
if (!(Objects.equals(this.identifier, methodNode.getIdentifier())) || type.equals(methodNode.type)
|| getParameters().size() != methodNode.getParameters().size()) {
return false;

View File

@@ -3,7 +3,7 @@ package ast.parameters;
import ast.ASTNode;
import ast.type.type.*;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
public class ParameterNode implements ASTNode, Visitable {

View File

@@ -3,7 +3,7 @@ package ast.statementexpressions;
import ast.expressions.IExpressionNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class AssignNode implements IStatementExpressionNode {
public AssignableNode assignable;

View File

@@ -2,12 +2,13 @@ package ast.statementexpressions;
import ast.expressions.unaryexpressions.MemberAccessNode;
import ast.type.type.ITypeNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class AssignableNode implements IStatementExpressionNode {
public String identifier;
private ITypeNode typeNode;
public ITypeNode typeNode;
public MemberAccessNode memberAccess;
@@ -24,10 +25,6 @@ public class AssignableNode implements IStatementExpressionNode {
return visitor.analyze(this);
}
public ITypeNode getTypeNode() {
return typeNode;
}
public void setTypeNode(ITypeNode typeNode) {
this.typeNode = typeNode;
}

View File

@@ -2,4 +2,5 @@ package ast.statementexpressions;
import ast.statements.IStatementNode;
public interface IStatementExpressionNode extends IStatementNode {}
public interface IStatementExpressionNode extends IStatementNode {
}

View File

@@ -3,7 +3,7 @@ package ast.statementexpressions;
import ast.expressions.IExpressionNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import java.util.ArrayList;
import java.util.List;

View File

@@ -4,7 +4,7 @@ import ast.statementexpressions.AssignableNode;
import ast.statementexpressions.IStatementExpressionNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
public class DecrementNode implements IStatementExpressionNode, Visitable {

View File

@@ -4,8 +4,8 @@ import ast.statementexpressions.AssignableNode;
import ast.statementexpressions.IStatementExpressionNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import visitor.Visitable;
import semantic.TypeCheckResult;
public class IncrementNode implements IStatementExpressionNode, Visitable {
public CrementType crementType;

View File

@@ -4,7 +4,7 @@ import ast.ASTNode;
import ast.expressions.IExpressionNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
import java.util.ArrayList;

View File

@@ -5,7 +5,7 @@ import ast.statements.IStatementNode;
import ast.type.type.ITypeNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import java.util.ArrayList;
import java.util.List;

View File

@@ -3,9 +3,8 @@ package ast.statementexpressions.methodcallstatementnexpressions;
import ast.ASTNode;
import ast.expressions.unaryexpressions.MemberAccessNode;
import ast.statementexpressions.NewDeclarationNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
public class TargetNode implements ASTNode, Visitable {

View File

@@ -1,8 +1,8 @@
package ast.statements;
import ast.ASTNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
import java.util.ArrayList;
@@ -11,7 +11,8 @@ import java.util.List;
public class BlockNode implements IStatementNode, Visitable {
public List<IStatementNode> statements = new ArrayList<>();
public BlockNode() {}
public BlockNode() {
}
public void addStatement(IStatementNode statement) {
statements.add(statement);
@@ -22,4 +23,9 @@ public class BlockNode implements IStatementNode, Visitable {
return visitor.analyze(this);
}
@Override
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
}
}

View File

@@ -1,10 +0,0 @@
package ast.statements;
import java.util.List;
public class BlockStatementNode {
List<IStatementNode> statements;
public BlockStatementNode(List<IStatementNode> statements) {this.statements = statements;}
}

View File

@@ -1,7 +1,8 @@
package ast.statements;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class ElseNode implements IStatementNode {
public BlockNode block;

View File

@@ -1,7 +1,8 @@
package ast.statements;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import java.util.ArrayList;
import java.util.List;
@@ -20,6 +21,11 @@ public class IfElseNode implements IStatementNode {
elseIfStatements.add(elseIfStament);
}
@Override
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
}
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);

View File

@@ -2,7 +2,7 @@ package ast.statements;
import ast.expressions.IExpressionNode;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class IfNode implements IStatementNode {
public IExpressionNode expression;

View File

@@ -4,7 +4,7 @@ import ast.expressions.IExpressionNode;
import ast.type.type.*;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class LocalVariableDeclarationNode implements IStatementNode {
public ITypeNode type;

View File

@@ -3,14 +3,14 @@ package ast.statements;
import ast.expressions.IExpressionNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class ReturnNode implements IStatementNode {
public IExpressionNode expression;
public Boolean voidReturn = false;
public ReturnNode(IExpressionNode expression) {
if(expression != null) {
if (expression != null) {
this.expression = expression;
} else {
voidReturn = true;

View File

@@ -1,8 +1,9 @@
package ast.statements;
import ast.expressions.IExpressionNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
public class WhileNode implements IStatementNode {
public IExpressionNode expression;
@@ -14,10 +15,14 @@ public class WhileNode implements IStatementNode {
}
public void test() {
return;
}
@Override
public void accept(MethodVisitor methodVisitor) {
methodVisitor.visit(this);
}
@Override
public TypeCheckResult accept(SemanticVisitor visitor) {
return visitor.analyze(this);

View File

@@ -8,7 +8,7 @@ public class AccessModifierNode {
}
private void setModifier(String accessType) {
switch(accessType) {
switch (accessType) {
case "public":
this.accessType = EnumAccessModifierNode.PUBLIC;
break;

View File

@@ -3,7 +3,7 @@ package ast.type;
import ast.ASTNode;
import bytecode.visitor.MethodVisitor;
import semantic.SemanticVisitor;
import typechecker.TypeCheckResult;
import semantic.TypeCheckResult;
import visitor.Visitable;
public class ValueNode implements ASTNode, Visitable {

View File

@@ -2,7 +2,7 @@ package ast.type.type;
public class BaseType implements ITypeNode {
private TypeEnum typeEnum;
public final TypeEnum typeEnum;
public BaseType(TypeEnum typeEnum) {
this.typeEnum = typeEnum;
@@ -21,8 +21,6 @@ public class BaseType implements ITypeNode {
if (getClass() != obj.getClass())
return false;
BaseType other = (BaseType) obj;
if (typeEnum != other.typeEnum)
return false;
return true;
return typeEnum == other.typeEnum;
}
}

View File

@@ -1,5 +1,4 @@
package ast.type.type;
public interface ITypeNode {
}

View File

@@ -1,8 +1,8 @@
package ast.type.type;
public class ReferenceType implements ITypeNode{
public class ReferenceType implements ITypeNode {
private String identifier;
public final String identifier;
public ReferenceType(String identifier) {
this.identifier = identifier;
@@ -22,11 +22,8 @@ public class ReferenceType implements ITypeNode{
return false;
ReferenceType other = (ReferenceType) obj;
if (identifier == null) {
if (other.identifier != null)
return false;
} else if (!identifier.equals(other.identifier))
return false;
return true;
return other.identifier == null;
} else return identifier.equals(other.identifier);
}

View File

@@ -4,6 +4,5 @@ public enum TypeEnum {
VOID,
INT,
CHAR,
BOOL;
BOOL
}

View File

@@ -17,9 +17,9 @@ public class ByteCodeGenerator implements ProgramVisitor {
private JarOutputStream jarOutputStream;
private ByteArrayOutputStream byteArrayOutputStream;
private String outputDirectory;
private boolean generateJar;
private boolean generateClassFiles;
private final String outputDirectory;
private final boolean generateJar;
private final boolean generateClassFiles;
public ByteCodeGenerator(String outputDirectory, boolean generateJar, boolean generateClassFiles) {
this.outputDirectory = outputDirectory;

View File

@@ -19,12 +19,12 @@ import java.util.jar.JarOutputStream;
public class ClassCodeGen implements ClassVisitor {
private Mapper mapper;
private final Mapper mapper;
private ClassWriter classWriter;
private JarOutputStream jarOutputStream;
private String outputDirectory;
private boolean generateJar;
private boolean generateClassFiles;
private final JarOutputStream jarOutputStream;
private final String outputDirectory;
private final boolean generateJar;
private final boolean generateClassFiles;
public ClassCodeGen(JarOutputStream jarOutputStream, String outputDirectory, boolean generateJar, boolean generateClassFiles) {
this.mapper = new Mapper();

View File

@@ -16,6 +16,8 @@ import ast.statementexpressions.crementexpressions.DecrementNode;
import ast.statementexpressions.crementexpressions.IncrementNode;
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
import ast.statements.*;
import ast.type.AccessModifierNode;
import ast.type.EnumAccessModifierNode;
import ast.type.ValueNode;
import ast.type.type.BaseType;
import ast.type.type.ReferenceType;
@@ -33,11 +35,11 @@ import static org.objectweb.asm.Opcodes.*;
public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
private ClassWriter classWriter;
private Mapper mapper;
private final ClassWriter classWriter;
private final Mapper mapper;
private MethodVisitor methodVisitor;
private List<String> localVariables;
private final List<String> localVariables;
public MethodCodeGen(ClassWriter classWriter) {
this.classWriter = classWriter;
@@ -51,7 +53,7 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
@Override
public void visit(ConstructorNode constructorNode) {
methodVisitor =
classWriter.visitMethod(mapper.mapAccessTypeToOpcode(constructorNode.accessType),
classWriter.visitMethod(mapper.mapAccessTypeToOpcode(constructorNode.accesModifier),
"<init>",
mapper.generateMethodDescriptor(new BaseType(TypeEnum.VOID), constructorNode.parameters),
null,
@@ -78,8 +80,10 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
@Override
public void visit(MainMethodNode mainMethodNode) {
methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(mainMethodNode.accesModifier),
mainMethodNode.getIdentifier(),
AccessModifierNode accessModifierNode = new AccessModifierNode("");
accessModifierNode.accessType = EnumAccessModifierNode.PUBLIC_STATIC;
methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
"main",
"([Ljava/lang/String;)V",
null,
null);
@@ -131,12 +135,12 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
@Override
public void visit(CalculationNode calculationNode) {
if (calculationNode.dotExpression != null) {
calculationNode.dotExpression.accept(this);
}
if (calculationNode.calculationExpression != null) {
calculationNode.calculationExpression.accept(this);
}
if (calculationNode.dotExpression != null) {
calculationNode.dotExpression.accept(this);
}
if (calculationNode.operator != null) {
switch (calculationNode.operator) {
case PLUS:
@@ -154,8 +158,8 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
if (dotNode.dotExpression != null) {
dotNode.dotExpression.accept(this);
}
if (dotNode.dotSubstractionExpression != null) {
dotNode.dotSubstractionExpression.accept(this);
if (dotNode.dotSubtractionExpression != null) {
dotNode.dotSubtractionExpression.accept(this);
}
if (dotNode.operator != null) {
switch (dotNode.operator) {
@@ -173,17 +177,17 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
}
@Override
public void visit(DotSubstractionNode dotSubstractionNode) {
if (dotSubstractionNode.value != null) {
dotSubstractionNode.value.accept(this);
} else if (dotSubstractionNode.identifier != null) {
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(dotSubstractionNode.identifier));
} else if (dotSubstractionNode.memberAccess != null) {
dotSubstractionNode.memberAccess.accept(this);
} else if (dotSubstractionNode.methodCall != null) {
dotSubstractionNode.methodCall.accept(this);
} else if (dotSubstractionNode.calculationExpression != null) {
dotSubstractionNode.calculationExpression.accept(this);
public void visit(DotSubtractionNode dotSubtractionNode) {
if (dotSubtractionNode.value != null) {
dotSubtractionNode.value.accept(this);
} else if (dotSubtractionNode.identifier != null) {
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(dotSubtractionNode.identifier));
} else if (dotSubtractionNode.memberAccess != null) {
dotSubtractionNode.memberAccess.accept(this);
} else if (dotSubtractionNode.methodCall != null) {
dotSubtractionNode.methodCall.accept(this);
} else if (dotSubtractionNode.calculationExpression != null) {
dotSubtractionNode.calculationExpression.accept(this);
}
}
@@ -318,9 +322,17 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
// Statements
@Override
public void visit(BlockNode blockNode) {
for(IStatementNode statementNode : blockNode.statements) {
statementNode.accept(this);
}
}
@Override
public void visit(IfElseNode ifElseNode) {
Label elseLabel = new Label();
Label endLabel = new Label();
Label[] elseIfLabels = new Label[ifElseNode.elseIfStatements.size()];
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
@@ -338,7 +350,6 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
ifElseNode.ifStatement.block.accept(this); // accept if block
Label endLabel = new Label();
methodVisitor.visitJumpInsn(GOTO, endLabel);
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
@@ -357,6 +368,8 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
if (ifElseNode.elseStatement != null) {
methodVisitor.visitLabel(elseLabel);
ifElseNode.elseStatement.block.accept(this);
} else {
methodVisitor.visitLabel(elseLabel);
}
methodVisitor.visitLabel(endLabel);
@@ -423,8 +436,7 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
assignLocalVar(assignNode);
incrementNode.accept(this);
}
} else if (assignNode.expression instanceof DecrementNode) {
DecrementNode decrementNode = (DecrementNode) assignNode.expression;
} else if (assignNode.expression instanceof DecrementNode decrementNode) {
if (decrementNode.crementType.equals(CrementType.PREFIX)) {
decrementNode.accept(this);
assignLocalVar(assignNode);
@@ -521,9 +533,9 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
if(incrementNode.assignableExpression.memberAccess != null) {
incrementNode.assignableExpression.memberAccess.accept(this);
} else {
if(assignNode.assignable.getTypeNode() instanceof BaseType) {
if(assignNode.assignable.typeNode instanceof BaseType) {
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(assignNode.assignable.identifier));
} else if(assignNode.assignable.getTypeNode() instanceof ReferenceType) {
} else if(assignNode.assignable.typeNode instanceof ReferenceType) {
methodVisitor.visitVarInsn(ALOAD, localVariables.indexOf(assignNode.assignable.identifier));
}
}
@@ -532,9 +544,9 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
if(decrementNode.assignableExpression.memberAccess != null) {
decrementNode.assignableExpression.memberAccess.accept(this);
} else {
if(assignNode.assignable.getTypeNode() instanceof BaseType) {
if(assignNode.assignable.typeNode instanceof BaseType) {
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(assignNode.assignable.identifier));
} else if(assignNode.assignable.getTypeNode() instanceof ReferenceType) {
} else if(assignNode.assignable.typeNode instanceof ReferenceType) {
methodVisitor.visitVarInsn(ALOAD, localVariables.indexOf(assignNode.assignable.identifier));
}
}

View File

@@ -8,48 +8,58 @@ import ast.members.ConstructorNode;
import ast.members.MainMethodNode;
import ast.members.MethodNode;
import ast.statementexpressions.AssignNode;
import ast.statementexpressions.AssignableNode;
import ast.statementexpressions.NewDeclarationNode;
import ast.statementexpressions.crementexpressions.DecrementNode;
import ast.statementexpressions.crementexpressions.IncrementNode;
import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNode;
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
import ast.statements.*;
import ast.type.ValueNode;
public interface MethodVisitor {
// members
void visit(ConstructorNode constructorNode);
void visit(MethodNode methodNode);
void visit(MainMethodNode mainMethodNode);
// Binary expressions
void visit(BinaryNode binaryNode);
void visit(CalculationNode calculationNode);
void visit(DotNode dotNode);
void visit(DotSubstractionNode dotSubstractionNode);
void visit(DotSubtractionNode dotSubtractionNode);
void visit(NonCalculationNode nonCalculationNode);
// Unary expressions
void visit(MemberAccessNode memberAccessNode);
void visit(NotNode notExpressionNode);
void visit(UnaryNode unaryExpressionNode);
// statements
void visit(BlockNode blockNode);
void visit(IfElseNode ifElseNode);
void visit(IncrementNode incrementNode);
void visit(DecrementNode decrementNode);
void visit(LocalVariableDeclarationNode localVariableDeclarationNode);
void visit(ReturnNode returnNode);
void visit(WhileNode whileNode);
// statement expression
void visit(MethodCallNode methodCallNode);
void visit(AssignNode assignNode);
void visit(NewDeclarationNode newDeclarationNode);
// type

View File

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

View File

@@ -15,12 +15,11 @@ import java.io.IOException;
import java.nio.file.Paths;
import java.util.Optional;
/**
* Start Raupenpiler using make:
* Start miniCompiler using make:
* <p> <code> cd .\src\test\ </code>
* <p> <code> make clean compile-raupenpiler </code>
* <p> Start Raupenpiler using jar:
* <p> <code> make clean compile-miniCompiler </code>
* <p> Start miniCompiler using jar:
* <p> <code> java.exe -DgenJar=true_OR_false -DgenClass=true_OR_false -jar path_to_jar\JavaCompiler-1.0-jar-with-dependencies.jar 'path_to_input_file.java' 'path_to_output_directory' </code>
* <p> Example (jar needs to be in the target directory, compile with make or mvn package first):
* <code> java.exe -DgenJar=true -DgenClass=true -jar .\target\JavaCompiler-1.0-jar-with-dependencies.jar 'src/main/resources/input/CompilerInput.java' 'src/main/resources/output' </code>
@@ -40,16 +39,14 @@ public class Main {
System.err.println("Error reading the file: " + e.getMessage());
}
}
/* !!! Else Branch (main ohne args starten) ist nicht zur Verwendung vorgesehen, immer mit args starten !!!
else {
try {
CharStream codeCharStream = CharStreams.fromPath(Paths.get("src/main/resources/input/CompilerInput.java"));
compileFile(codeCharStream);
CharStream codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/input/endabgabeTests/Person.java"));
compileFile(codeCharStream, "src/test/resources/input/endabgabeTests");
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
}
}
*/
}
/**
@@ -66,7 +63,7 @@ public class Main {
*/
static void compileFile(CharStream inputCharStream, String outputDirectoryPath) {
// Initialize the logger
new RaupenLogger();
new MiniCompilerLogger();
/* ------------------------- Scanner -> tokens ------------------------- */
// Use the SimpleJavaLexer to tokenize the input CharStream
@@ -74,27 +71,27 @@ public class Main {
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
tokenStream.fill();
// Log the tokens
RaupenLogger.logScanner(tokenStream);
MiniCompilerLogger.logScanner(tokenStream);
/*------------------------- Parser -> Parsetree -------------------------*/
// Use the SimpleJavaParser to parse the tokens and generate a ParseTree
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
ParseTree parseTree = parser.program(); // parse the input
// Log the ParseTree
RaupenLogger.logParser(parseTree, parser);
MiniCompilerLogger.logParser(parseTree, parser);
/*------------------------- AST builder -> AST -------------------------*/
// Use the ASTBuilder to visit the ParseTree and generate an Abstract Syntax Tree (AST)
ASTBuilder astBuilder = new ASTBuilder();
ASTNode abstractSyntaxTree = astBuilder.visit(parseTree);
// Log the AST
RaupenLogger.logAST(abstractSyntaxTree);
MiniCompilerLogger.logAST(abstractSyntaxTree);
/*------------------------- Semantic Analyzer -> typed AST -------------------------*/
// Use the SemanticAnalyzer to generate a typed AST
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
// Log the typed AST
RaupenLogger.logSemanticAnalyzer(typedAst);
MiniCompilerLogger.logSemanticAnalyzer(typedAst);
if(SemanticAnalyzer.errors.isEmpty()){
/*------------------------- Bytecode Generator -> Bytecode -------------------------*/
@@ -107,7 +104,7 @@ public class Main {
assert typedAst != null;
byteCodeGenerator.visit((ProgramNode) typedAst);
// Log the bytecode generation
RaupenLogger.logBytecodeGenerator();
MiniCompilerLogger.logBytecodeGenerator();
} else {
for(Exception exception : SemanticAnalyzer.errors){
exception.printStackTrace();

View File

@@ -29,11 +29,11 @@ import java.util.logging.*;
* <code>consoleHandler.setLevel(Level.OFF);</code>
* <code>fileHandler.setLevel(Level.ALL);</code>
*/
public class RaupenLogger {
public class MiniCompilerLogger {
static Logger logger = Logger.getLogger("RaupenLogs");
static Logger logger = Logger.getLogger("miniCompilerLogs");
public RaupenLogger() {
public MiniCompilerLogger() {
// ------------------------- Logging -------------------------
logger.setLevel(Level.ALL);
logger.getParent().getHandlers()[0].setLevel(Level.ALL);
@@ -66,13 +66,13 @@ public class RaupenLogger {
logger.addHandler(consoleHandler);
// Configure file handler
Handler fileHandler = new FileHandler("src/main/resources/logs/RaupenLog.log");
//Handler fileHandler = new FileHandler("src/main/resources/logs/miniCompiler.log");
// Toggle file logging on/off
fileHandler.setLevel(Level.ALL);
fileHandler.setFormatter(new CustomFormatter());
logger.addHandler(fileHandler);
//fileHandler.setLevel(Level.ALL);
//fileHandler.setFormatter(new CustomFormatter());
//logger.addHandler(fileHandler);
} catch (SecurityException | IOException e) {
} catch (SecurityException e) {
e.printStackTrace();
}
}
@@ -117,7 +117,7 @@ public class RaupenLogger {
public static void logBytecodeGenerator() {
// Printing the bytecode
logger.info("-------------------- Bytecode Generator -> Bytecode --------------------");
logger.info("Bytecode generated");
logger.info("Bytecode generated without errors.");
logger.info("\n");
}

View File

@@ -30,7 +30,18 @@ import parser.generated.*;
import java.util.ArrayList;
import java.util.List;
/**
* ASTBuilder is a visitor that converts the parse tree into an abstract syntax tree (AST).
*/
public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
/**
* Visits a program node and creates a ProgramNode.
* It iterates through all class declarations in the context and adds them to the ProgramNode.
*
* @param ctx the program context
* @return the AST node for the program
*/
@Override
public ASTNode visitProgram(SimpleJavaParser.ProgramContext ctx) {
ProgramNode program = new ProgramNode();
@@ -40,6 +51,14 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return program;
}
/**
* Visits a class declaration and creates a ClassNode.
* It checks for an access modifier, processes member declarations, and ensures the class has a constructor.
*
* @param ctx the class declaration context
* @return the AST node for the class
*/
@Override
public ASTNode visitClassDeclaration(SimpleJavaParser.ClassDeclarationContext ctx) {
ClassNode classNode;
@@ -71,6 +90,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return classNode;
}
/**
* Visits a constructor declaration and creates a ConstructorNode.
* It processes access modifiers, block statements, and parameters.
*
* @param ctx the constructor declaration context
* @return the AST node for the constructor
*/
@Override
public ASTNode visitConstructorDeclaration(SimpleJavaParser.ConstructorDeclarationContext ctx) {
ConstructorNode constructorNode;
@@ -88,6 +114,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return constructorNode;
}
/**
* Visits a method declaration and creates a MethodNode or MainMethodNode.
* It handles method types, access modifiers, block statements, and parameters.
*
* @param ctx the method declaration context
* @return the AST node for the method
*/
@Override
public ASTNode visitMethodDeclaration(SimpleJavaParser.MethodDeclarationContext ctx) {
if(ctx.MainMethodDeclaration() != null) {
@@ -137,6 +170,14 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
}
}
/**
* Visits a field declaration and creates a FieldNode.
* It handles access modifiers and types.
*
* @param ctx the field declaration context
* @return the AST node for the field
*/
@Override
public ASTNode visitFieldDeclaration(SimpleJavaParser.FieldDeclarationContext ctx) {
if(ctx.AccessModifier() != null) {
@@ -146,11 +187,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
}
}
/**
* Visits a parameter and creates a ParameterNode.
* It handles the type and identifier of the parameter.
*
* @param ctx the parameter context
* @return the AST node for the parameter
*/
@Override
public ASTNode visitParameter(SimpleJavaParser.ParameterContext ctx) {
return new ParameterNode(createTypeNode(ctx.type().getText()), ctx.Identifier().getText());
}
/**
* Visits a statement and creates the corresponding AST node.
* It determines the specific type of statement and processes it accordingly.
*
* @param ctx the statement context
* @return the AST node for the statement
*/
@Override
public ASTNode visitStatement(SimpleJavaParser.StatementContext ctx) {
if(ctx.returnStatement() != null) {
@@ -175,11 +230,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a return statement and creates a ReturnNode.
* It processes the expression in the return statement.
*
* @param ctx the return statement context
* @return the AST node for the return statement
*/
@Override
public ASTNode visitReturnStatement(SimpleJavaParser.ReturnStatementContext ctx) {
return new ReturnNode((IExpressionNode) visit(ctx.expression()));
}
/**
* Visits a return statement and creates a ReturnNode.
* It processes the expression in the return statement.
*
* @param ctx the return statement context
* @return the AST node for the return statement
*/
@Override
public ASTNode visitLocalVariableDeclaration(SimpleJavaParser.LocalVariableDeclarationContext ctx) {
if(ctx.Assign() != null) {
@@ -190,6 +259,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
}
/**
* Visits a block statement and creates a BlockNode.
* It processes all statements within the block.
*
* @param ctx the block statement context
* @return the AST node for the block statement
*/
@Override
public ASTNode visitBlockStatement(SimpleJavaParser.BlockStatementContext ctx) {
BlockNode blockNode = new BlockNode();
@@ -199,11 +275,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return blockNode;
}
/**
* Visits a while statement and creates a WhileNode.
* It processes the condition expression and the block statement.
*
* @param ctx the while statement context
* @return the AST node for the while statement
*/
@Override
public ASTNode visitWhileStatement(SimpleJavaParser.WhileStatementContext ctx) {
return new WhileNode((IExpressionNode) visit(ctx.expression()), (BlockNode) visit(ctx.blockStatement()));
}
/**
* Visits a do-while statement and creates a BlockNode containing a WhileNode.
* It processes the condition expression and the block statement.
*
* @param ctx the do-while statement context
* @return the AST node for the do-while statement
*/
@Override
public ASTNode visitDoWhileStatement(SimpleJavaParser.DoWhileStatementContext ctx) {
IExpressionNode condition = (IExpressionNode) visit(ctx.expression());
@@ -211,12 +301,19 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
WhileNode While = new WhileNode(condition, doBlock);
BlockNode resultBlock = new BlockNode();
resultBlock.addStatement((IStatementNode) doBlock);
resultBlock.addStatement((IStatementNode) While);
resultBlock.addStatement(doBlock);
resultBlock.addStatement(While);
return resultBlock;
}
/**
* Visits a for statement and creates a BlockNode that contains a WhileNode.
* It processes the initialization, condition, and increment parts of the for loop.
*
* @param ctx the for statement context
* @return the AST node for the for statement
*/
@Override
public ASTNode visitForStatement(SimpleJavaParser.ForStatementContext ctx) {
List<IStatementNode> statements = new ArrayList<>();
@@ -253,7 +350,7 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
// Prä-Inkrement: Das Inkrement kommt vor dem Block
if (crement != null && isPrefix) {
whileBody.addStatement((IStatementNode) crement);
whileBody.addStatement(crement);
}
// Block Statements der For-Schleife in den While-Block kopieren
@@ -263,7 +360,7 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
// Post-Inkrement: Das Inkrement kommt nach dem Block
if (crement != null && !isPrefix) {
whileBody.addStatement((IStatementNode) crement);
whileBody.addStatement(crement);
}
// Bedingung der While-Schleife
@@ -273,12 +370,19 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
BlockNode resultBlock = new BlockNode();
for (IStatementNode statement : statements) {
resultBlock.addStatement((IStatementNode) statement);
resultBlock.addStatement(statement);
}
return resultBlock;
}
/**
* Visits an if-else statement and creates an IfElseNode.
* It processes the if, else-if, and else parts of the statement.
*
* @param ctx the if-else statement context
* @return the AST node for the if-else statement
*/
@Override
public ASTNode visitIfElseStatement(SimpleJavaParser.IfElseStatementContext ctx) {
IfElseNode ifElseStatementNode;
@@ -296,21 +400,49 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return ifElseStatementNode;
}
/**
* Visits an if statement and creates an IfNode.
* It processes the condition expression and the block statement.
*
* @param ctx the if statement context
* @return the AST node for the if statement
*/
@Override
public ASTNode visitIfStatement(SimpleJavaParser.IfStatementContext ctx) {
return new IfNode((IExpressionNode) visit(ctx.expression()), (BlockNode) visit(ctx.blockStatement()));
}
/**
* Visits an else-if statement and creates an IfNode.
* It processes the condition expression and the block statement.
*
* @param ctx the else-if statement context
* @return the AST node for the else-if statement
*/
@Override
public ASTNode visitElseIfStatement(SimpleJavaParser.ElseIfStatementContext ctx) {
return new IfNode((IExpressionNode) visit(ctx.expression()), (BlockNode) visit(ctx.blockStatement()));
}
/**
* Visits an else statement and creates an ElseNode.
* It processes the block statement of the else part.
*
* @param ctx the else statement context
* @return the AST node for the else statement
*/
@Override
public ASTNode visitElseStatement(SimpleJavaParser.ElseStatementContext ctx) {
return new ElseNode((BlockNode) visit(ctx.blockStatement()));
}
/**
* Visits a statement expression and creates the corresponding AST node.
* It handles assignments, new declarations, method calls, and increment/decrement expressions.
*
* @param ctx the statement expression context
* @return the AST node for the statement expression
*/
@Override
public ASTNode visitStatementExpression(SimpleJavaParser.StatementExpressionContext ctx) {
if(ctx.assign() != null) {
@@ -325,6 +457,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a switch statement and creates an IfElseNode representing the switch cases.
* It processes the switch expression, case statements, and default statement.
*
* @param ctx the switch statement context
* @return the AST node for the switch statement
*/
@Override
public ASTNode visitSwitchStatement(SimpleJavaParser.SwitchStatementContext ctx) {
UnaryNode switchExpression = (UnaryNode) visit(ctx.expression());
@@ -368,11 +507,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return ifElseNode;
}
/**
* Visits an assignment expression and creates an AssignNode.
* It handles the assignable expression and the assigned expression.
*
* @param ctx the assignment context
* @return the AST node for the assignment
*/
@Override
public ASTNode visitAssign(SimpleJavaParser.AssignContext ctx) {
return new AssignNode((AssignableNode) visit(ctx.assignableExpression()), (IExpressionNode) visit(ctx.expression()));
}
/**
* Visits a new declaration and creates a NewDeclarationNode.
* It processes the identifier and the argument list.
*
* @param ctx the new declaration context
* @return the AST node for the new declaration
*/
@Override
public ASTNode visitNewDeclaration(SimpleJavaParser.NewDeclarationContext ctx) {
NewDeclarationNode newDeclarationNode = new NewDeclarationNode(ctx.Identifier().getText());
@@ -382,6 +535,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return newDeclarationNode;
}
/**
* Visits a method call and creates a MethodCallNode.
* It processes the target, chained methods, and argument list.
*
* @param ctx the method call context
* @return the AST node for the method call
*/
@Override
public ASTNode visitMethodCall(SimpleJavaParser.MethodCallContext ctx) {
MethodCallNode methodCallStatementExpressionNode;
@@ -399,6 +559,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return methodCallStatementExpressionNode;
}
/**
* Visits the target of a method call and creates a TargetNode.
* It handles various types of targets including 'this', member access, new declarations, and identifiers.
*
* @param ctx the target context
* @return the AST node for the target
*/
@Override
public ASTNode visitTarget(SimpleJavaParser.TargetContext ctx) {
if(ctx.This() != null) {
@@ -413,6 +580,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a chained method and creates a ChainedMethodNode.
* It processes the identifier and the argument list.
*
* @param ctx the chained method context
* @return the AST node for the chained method
*/
@Override
public ASTNode visitChainedMethod(SimpleJavaParser.ChainedMethodContext ctx) {
ChainedMethodNode chainedMethodNode = new ChainedMethodNode(ctx.Identifier().getText());
@@ -422,6 +596,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return chainedMethodNode;
}
/**
* Visits an increment or decrement expression and creates the corresponding AST node.
* It handles both prefix and suffix forms of increment and decrement.
*
* @param ctx the crement expression context
* @return the AST node for the crement expression
*/
@Override
public ASTNode visitCrementExpression(SimpleJavaParser.CrementExpressionContext ctx) {
if(ctx.incrementExpression() != null) {
@@ -432,6 +613,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits an increment expression and creates an IncrementNode.
* It handles both prefix and suffix forms.
*
* @param ctx the increment expression context
* @return the AST node for the increment expression
*/
@Override
public ASTNode visitIncrementExpression(SimpleJavaParser.IncrementExpressionContext ctx) {
if(ctx.prefixIncrementExpression() != null) {
@@ -442,16 +630,35 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a prefix increment expression and creates an IncrementNode.
*
* @param ctx the prefix increment expression context
* @return the AST node for the prefix increment expression
*/
@Override
public ASTNode visitPrefixIncrementExpression(SimpleJavaParser.PrefixIncrementExpressionContext ctx) {
return new IncrementNode(CrementType.PREFIX, (AssignableNode) visit(ctx.assignableExpression()));
}
/**
* Visits a suffix increment expression and creates an IncrementNode.
*
* @param ctx the suffix increment expression context
* @return the AST node for the suffix increment expression
*/
@Override
public ASTNode visitSuffixIncrementExpression(SimpleJavaParser.SuffixIncrementExpressionContext ctx) {
return new IncrementNode(CrementType.SUFFIX, (AssignableNode) visit(ctx.assignableExpression()));
}
/**
* Visits a decrement expression and creates a DecrementNode.
* It handles both prefix and suffix forms.
*
* @param ctx the decrement expression context
* @return the AST node for the decrement expression
*/
@Override
public ASTNode visitDecrementExpression(SimpleJavaParser.DecrementExpressionContext ctx) {
if(ctx.prefixDecrementExpression() != null) {
@@ -462,16 +669,35 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a prefix decrement expression and creates a DecrementNode.
*
* @param ctx the prefix decrement expression context
* @return the AST node for the prefix decrement expression
*/
@Override
public ASTNode visitPrefixDecrementExpression(SimpleJavaParser.PrefixDecrementExpressionContext ctx) {
return new DecrementNode(CrementType.PREFIX, (AssignableNode) visit(ctx.assignableExpression()));
}
/**
* Visits a suffix decrement expression and creates a DecrementNode.
*
* @param ctx the suffix decrement expression context
* @return the AST node for the suffix decrement expression
*/
@Override
public ASTNode visitSuffixDecrementExpression(SimpleJavaParser.SuffixDecrementExpressionContext ctx) {
return new DecrementNode(CrementType.SUFFIX, (AssignableNode) visit(ctx.assignableExpression()));
}
/**
* Visits an expression and creates the corresponding AST node.
* It handles both unary and binary expressions.
*
* @param ctx the expression context
* @return the AST node for the expression
*/
@Override
public ASTNode visitExpression(SimpleJavaParser.ExpressionContext ctx) {
if(ctx.unaryExpression() != null) {
@@ -482,6 +708,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a unary expression and creates a UnaryNode.
* It handles various forms of unary expressions including 'this', identifiers, member access, values, and more.
*
* @param ctx the unary expression context
* @return the AST node for the unary expression
*/
@Override
public ASTNode visitUnaryExpression(SimpleJavaParser.UnaryExpressionContext ctx) {
if(ctx.This() != null) {
@@ -502,6 +735,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a member access expression and creates a MemberAccessNode.
* It processes the 'this' keyword and identifiers for member access.
*
* @param ctx the member access context
* @return the AST node for the member access
*/
@Override
public ASTNode visitMemberAccess(SimpleJavaParser.MemberAccessContext ctx) {
MemberAccessNode memberAccessNode;
@@ -516,6 +756,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return memberAccessNode;
}
/**
* Visits a value and creates a ValueNode.
* It handles integer, boolean, char, and null values.
*
* @param ctx the value context
* @return the AST node for the value
*/
@Override
public ASTNode visitValue(SimpleJavaParser.ValueContext ctx) {
if(ctx.IntValue() != null) {
@@ -530,12 +777,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a not expression and creates a NotNode.
* It processes the expression to which the 'not' operator is applied.
*
* @param ctx the not expression context
* @return the AST node for the not expression
*/
@Override
public ASTNode visitNotExpression(SimpleJavaParser.NotExpressionContext ctx) {
return new NotNode((IExpressionNode) visitExpression(ctx.expression()));
}
/**
* Visits a binary expression and creates the corresponding AST node.
* It handles both calculation and non-calculation expressions.
*
* @param ctx the binary expression context
* @return the AST node for the binary expression
*/
@Override
public ASTNode visitBinaryExpression(SimpleJavaParser.BinaryExpressionContext ctx) {
if(ctx.calculationExpression() != null) {
@@ -546,6 +806,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a calculation expression and creates a CalculationNode.
* It handles line operators and dot expressions.
*
* @param ctx the calculation expression context
* @return the AST node for the calculation expression
*/
@Override
public ASTNode visitCalculationExpression(SimpleJavaParser.CalculationExpressionContext ctx) {
if(ctx.calculationExpression() != null) {
@@ -556,35 +823,63 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Visits a dot expression and creates a DotNode.
* It handles dot operators and dot subtraction expressions.
*
* @param ctx the dot expression context
* @return the AST node for the dot expression
*/
@Override
public ASTNode visitDotExpression(SimpleJavaParser.DotExpressionContext ctx) {
if(ctx.dotExpression() != null) {
return new DotNode((DotNode) visit(ctx.dotExpression()), ctx.DotOperator().getText(), (DotSubstractionNode) visit(ctx.dotSubtractionExpression()));
return new DotNode((DotNode) visit(ctx.dotExpression()), ctx.DotOperator().getText(), (DotSubtractionNode) visit(ctx.dotSubtractionExpression()));
} else if(ctx.dotSubtractionExpression() != null) {
return new DotNode((DotSubstractionNode) visit(ctx.dotSubtractionExpression()));
return new DotNode((DotSubtractionNode) visit(ctx.dotSubtractionExpression()));
}
return null;
}
/**
* Visits a dot subtraction expression and creates a DotSubtractionNode.
* It handles integer values, identifiers, member access, and method calls.
*
* @param ctx the dot subtraction expression context
* @return the AST node for the dot subtraction expression
*/
@Override
public ASTNode visitDotSubtractionExpression(SimpleJavaParser.DotSubtractionExpressionContext ctx) {
if(ctx.IntValue() != null) {
return new DotSubstractionNode(new ValueNode(EnumValueNode.INT_VALUE, ctx.IntValue().getText()));
return new DotSubtractionNode(new ValueNode(EnumValueNode.INT_VALUE, ctx.IntValue().getText()));
} else if(ctx.Identifier() != null) {
return new DotSubstractionNode(ctx.Identifier().getText());
return new DotSubtractionNode(ctx.Identifier().getText());
} else if(ctx.memberAccess() != null) {
return new DotSubstractionNode((MemberAccessNode) visit(ctx.memberAccess()));
return new DotSubtractionNode((MemberAccessNode) visit(ctx.memberAccess()));
} else if(ctx.methodCall() != null && ctx.calculationExpression() != null) {
return new DotSubstractionNode((MethodCallNode) visit(ctx.methodCall()), (CalculationNode) visit(ctx.calculationExpression()));
return new DotSubtractionNode((MethodCallNode) visit(ctx.methodCall()), (CalculationNode) visit(ctx.calculationExpression()));
}
return null;
}
/**
* Visits a non-calculation expression and creates a NonCalculationNode.
* It handles unary expressions combined with non-calculation operators.
*
* @param ctx the non-calculation expression context
* @return the AST node for the non-calculation expression
*/
@Override
public ASTNode visitNonCalculationExpression(SimpleJavaParser.NonCalculationExpressionContext ctx) {
return new NonCalculationNode((UnaryNode) visit(ctx.unaryExpression()), ctx.nonCalculationOperator().getText(), (IExpressionNode) visit(ctx.expression()));
}
/**
* Visits an assignable expression and creates an AssignableNode.
* It handles identifiers and member access.
*
* @param ctx the assignable expression context
* @return the AST node for the assignable expression
*/
@Override
public ASTNode visitAssignableExpression(SimpleJavaParser.AssignableExpressionContext ctx) {
if(ctx.Identifier() != null) {
@@ -595,6 +890,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
return null;
}
/**
* Creates an ITypeNode based on the type identifier.
* It handles basic types and reference types.
*
* @param identifier the type identifier
* @return the type node
*/
public ITypeNode createTypeNode(String identifier){
return switch (identifier) {
case "int" -> new BaseType(TypeEnum.INT);

View File

@@ -1,18 +1,18 @@
grammar SimpleJava;
// Programm-Konstrukte
program: classDeclaration+;
program: classDeclaration+; // Ein Programm besteht aus einer oder mehreren Klassendeklarationen
classDeclaration: AccessModifier? 'class' Identifier OpenCurlyBracket memberDeclaration* ClosedCurlyBracket;
memberDeclaration: constructorDeclaration | fieldDeclaration | methodDeclaration;
classDeclaration: AccessModifier? 'class' Identifier OpenCurlyBracket memberDeclaration* ClosedCurlyBracket; // Deklariert eine Klasse mit optionalem Zugriffsmodifikator und mehreren Mitgliedern
memberDeclaration: constructorDeclaration | fieldDeclaration | methodDeclaration; // Ein Mitglied kann ein Konstruktor, ein Feld oder eine Methode sein
constructorDeclaration: AccessModifier? Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement;
fieldDeclaration: AccessModifier? type Identifier (Assign expression)? Semicolon;
methodDeclaration: MainMethodDeclaration blockStatement | AccessModifier? (type | Void) Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement;
constructorDeclaration: AccessModifier? Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement; // Deklariert einen Konstruktor
fieldDeclaration: AccessModifier? type Identifier (Assign expression)? Semicolon; // Deklariert ein Feld mit optionaler Initialisierung
methodDeclaration: MainMethodDeclaration blockStatement | AccessModifier? (type | Void) Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement; // Deklariert eine Methode
parameterList: parameter (Comma parameter)*;
parameter: type Identifier;
argumentList: (expression (Comma expression)*)?;
parameterList: parameter (Comma parameter)*; // Parameterliste für Methoden und Konstruktoren
parameter: type Identifier; // Ein einzelner Parameter mit Typ und Bezeichner
argumentList: (expression (Comma expression)*)?; // Argumentliste für Methodenaufrufe
// Anweisungen
statement: returnStatement Semicolon
@@ -23,32 +23,32 @@ statement: returnStatement Semicolon
| forStatement
| ifElseStatement
| switchStatement
| statementExpression Semicolon;
| statementExpression Semicolon; // Verschiedene Arten von Anweisungen
blockStatement: OpenCurlyBracket statement* ClosedCurlyBracket;
blockStatement: OpenCurlyBracket statement* ClosedCurlyBracket; // Ein Block von Anweisungen
returnStatement: Return (expression)?;
localVariableDeclaration: type Identifier (Assign expression)?;
returnStatement: Return (expression)?; // Rückgabe-Anweisung
localVariableDeclaration: type Identifier (Assign expression)?; // Deklaration einer lokalen Variable
whileStatement: While OpenRoundBracket expression ClosedRoundBracket blockStatement;
doWhileStatement: Do blockStatement While OpenRoundBracket expression ClosedRoundBracket Semicolon;
forStatement: For OpenRoundBracket (statementExpression | localVariableDeclaration) Semicolon (expression)? Semicolon (statementExpression)? ClosedRoundBracket blockStatement;
whileStatement: While OpenRoundBracket expression ClosedRoundBracket blockStatement; // While-Schleife
doWhileStatement: Do blockStatement While OpenRoundBracket expression ClosedRoundBracket Semicolon; // Do-While-Schleife
forStatement: For OpenRoundBracket (statementExpression | localVariableDeclaration) Semicolon (expression)? Semicolon (statementExpression)? ClosedRoundBracket blockStatement; // For-Schleife
ifElseStatement: ifStatement elseIfStatement* elseStatement?;
ifStatement: If OpenRoundBracket expression ClosedRoundBracket blockStatement;
elseIfStatement: Else If OpenRoundBracket expression ClosedRoundBracket blockStatement;
elseStatement: Else blockStatement;
ifElseStatement: ifStatement elseIfStatement* elseStatement?; // If-Else-Bedingung
ifStatement: If OpenRoundBracket expression ClosedRoundBracket blockStatement; // If-Teil der Bedingung
elseIfStatement: Else If OpenRoundBracket expression ClosedRoundBracket blockStatement; // Else-If-Teil der Bedingung
elseStatement: Else blockStatement; // Else-Teil der Bedingung
switchStatement: Switch OpenRoundBracket expression ClosedRoundBracket OpenCurlyBracket caseStatement+ defaultStatement? ClosedCurlyBracket;
caseStatement: Case value Colon statement*;
defaultStatement: Default Colon statement*;
switchStatement: Switch OpenRoundBracket expression ClosedRoundBracket OpenCurlyBracket caseStatement+ defaultStatement? ClosedCurlyBracket; // Switch-Anweisung
caseStatement: Case value Colon statement*; // Ein Case-Teil einer Switch-Anweisung
defaultStatement: Default Colon statement*; // Default-Teil einer Switch-Anweisung
statementExpression: assign | newDeclaration | methodCall | crementExpression;
assign: assignableExpression Assign expression;
newDeclaration: New Identifier OpenRoundBracket argumentList ClosedRoundBracket;
statementExpression: assign | newDeclaration | methodCall | crementExpression; // Ausdruck innerhalb einer Anweisung
assign: assignableExpression Assign expression; // Zuweisung
newDeclaration: New Identifier OpenRoundBracket argumentList ClosedRoundBracket; // Instanziierung eines neuen Objekts
// Ausdrücke
expression: unaryExpression | binaryExpression;
expression: unaryExpression | binaryExpression; // Ein Ausdruck kann unär oder binär sein
unaryExpression: This
| Identifier
@@ -56,97 +56,97 @@ unaryExpression: This
| value
| notExpression
| statementExpression
| OpenRoundBracket expression ClosedRoundBracket;
| OpenRoundBracket expression ClosedRoundBracket; // Unäre Ausdrücke
notExpression: Not expression;
notExpression: Not expression; // Nicht-Ausdruck
crementExpression: incrementExpression | decrementExpression;
crementExpression: incrementExpression | decrementExpression; // Inkrement-/Dekrement-Ausdrücke
incrementExpression: prefixIncrementExpression | suffixIncrementExpression;
prefixIncrementExpression: '++' assignableExpression;
suffixIncrementExpression: assignableExpression '++';
prefixIncrementExpression: '++' assignableExpression; // Präfix-Inkrement
suffixIncrementExpression: assignableExpression '++'; // Suffix-Inkrement
decrementExpression: prefixDecrementExpression | suffixDecrementExpression;
prefixDecrementExpression: '--' assignableExpression;
suffixDecrementExpression: assignableExpression '--';
decrementExpression: prefixDecrementExpression | suffixDecrementExpression; // Dekrement-Ausdrücke
prefixDecrementExpression: '--' assignableExpression; // Präfix-Dekrement
suffixDecrementExpression: assignableExpression '--'; // Suffix-Dekrement
assignableExpression: Identifier | memberAccess;
assignableExpression: Identifier | memberAccess; // Zuweisbarer Ausdruck
memberAccess: This Dot Identifier
| (This Dot)? (Identifier Dot)+ Identifier;
| (This Dot)? (Identifier Dot)+ Identifier; // Mitgliedszugriff
binaryExpression: calculationExpression | nonCalculationExpression;
binaryExpression: calculationExpression | nonCalculationExpression; // Binäre Ausdrücke
calculationExpression: calculationExpression LineOperator dotExpression
| dotExpression;
| dotExpression; // Berechnungsausdrücke
dotExpression: dotExpression DotOperator dotSubtractionExpression
| dotSubtractionExpression;
| dotSubtractionExpression; // Punktoperationen
dotSubtractionExpression: IntValue
| Identifier
| memberAccess
| methodCall OpenRoundBracket calculationExpression ClosedRoundBracket;
| methodCall OpenRoundBracket calculationExpression ClosedRoundBracket; // Punkt-Subtraktionsausdrücke
nonCalculationExpression: unaryExpression nonCalculationOperator expression;
nonCalculationExpression: unaryExpression nonCalculationOperator expression; // Nicht-Berechnungsausdrücke
// Methodenaufrufe
methodCall: target? chainedMethod* Identifier OpenRoundBracket argumentList ClosedRoundBracket;
target: (This | memberAccess | newDeclaration | Identifier) Dot;
chainedMethod: Identifier OpenRoundBracket argumentList ClosedRoundBracket Dot;
methodCall: target? chainedMethod* Identifier OpenRoundBracket argumentList ClosedRoundBracket; // Methodenaufruf
target: (This | memberAccess | newDeclaration | Identifier) Dot; // Ziel eines Methodenaufrufs
chainedMethod: Identifier OpenRoundBracket argumentList ClosedRoundBracket Dot; // Verkettete Methode
// Typen
type: Int
| Boolean
| Char
| Identifier;
| Identifier; // Datentypen
Void: 'void';
Boolean: 'boolean';
Char: 'char';
Int: 'int';
Void: 'void'; // Void-Typ
Boolean: 'boolean'; // Boolean-Typ
Char: 'char'; // Char-Typ
Int: 'int'; // Integer-Typ
value: IntValue
| BooleanValue
| CharValue
| NullValue;
| NullValue; // Werte
// Zugriffsmodifikatoren
AccessModifier: 'public' | 'private' | 'public static' | 'private static';
MainMethodDeclaration: 'public static void main(String[] args)';
AccessModifier: 'public' | 'private' | 'public static' | 'private static'; // Zugriffsmodifikatoren
MainMethodDeclaration: 'public static void main(String[] args)'; // Hauptmethoden-Deklaration
// Operatoren
nonCalculationOperator: LogicalOperator | ComparisonOperator;
nonCalculationOperator: LogicalOperator | ComparisonOperator; // Nicht-Berechnungsoperatoren
DotOperator: Mult | Div | Modulo;
LineOperator: Plus | Minus;
ComparisonOperator: Greater | Less | GreaterEqual | LessEqual | Equal | NotEqual;
LogicalOperator: And | Or;
DotOperator: Mult | Div | Modulo; // Punktoperatoren
LineOperator: Plus | Minus; // Linienoperatoren
ComparisonOperator: Greater | Less | GreaterEqual | LessEqual | Equal | NotEqual; // Vergleichsoperatoren
LogicalOperator: And | Or; // Logische Operatoren
Assign: '=';
Plus: '+';
Minus: '-';
Mult: '*';
Modulo: '%';
Div: '/';
Greater: '>';
Less: '<';
GreaterEqual: '>=';
LessEqual: '<=';
Equal: '==';
NotEqual: '!=';
Not: '!';
And: '&&';
Or: '||';
Assign: '='; // Zuweisungsoperator
Plus: '+'; // Plus-Operator
Minus: '-'; // Minus-Operator
Mult: '*'; // Multiplikationsoperator
Modulo: '%'; // Modulo-Operator
Div: '/'; // Divisionsoperator
Greater: '>'; // Größer-Operator
Less: '<'; // Kleiner-Operator
GreaterEqual: '>='; // Größer-Gleich-Operator
LessEqual: '<='; // Kleiner-Gleich-Operator
Equal: '=='; // Gleichheitsoperator
NotEqual: '!='; // Ungleichheitsoperator
Not: '!'; // Nicht-Operator
And: '&&'; // Und-Operator
Or: '||'; // Oder-Operator
// Symbole
Dot: '.';
OpenRoundBracket: '(';
ClosedRoundBracket: ')';
OpenCurlyBracket: '{';
ClosedCurlyBracket: '}';
Semicolon: ';';
Comma: ',';
Dot: '.'; // Punkt-Symbol
OpenRoundBracket: '('; // Öffnende runde Klammer
ClosedRoundBracket: ')'; // Schließende runde Klammer
OpenCurlyBracket: '{'; // Öffnende geschweifte Klammer
ClosedCurlyBracket: '}'; // Schließende geschweifte Klammer
Semicolon: ';'; // Semikolon
Comma: ','; // Komma
// Schlüsselwörter
Class: 'class';
@@ -161,21 +161,21 @@ New: 'new';
Switch: 'switch';
Case: 'case';
Default: 'default';
Colon: ':';
Colon: ':'; // Doppelpunkt
// Werte
CharValue: '\'' ~[\r\n]* '\'';
IntValue: Minus? Numeric+;
BooleanValue: 'true' | 'false';
NullValue: 'null';
CharValue: '\'' ~[\r\n]* '\''; // Zeichenwert
IntValue: Minus? Numeric+; // Ganzzahlwert
BooleanValue: 'true' | 'false'; // Boolean-Wert
NullValue: 'null'; // Null-Wert
// Bezeichner
fragment Alphabetic: [a-zA-Z];
fragment Numeric: [0-9];
fragment ValidIdentSymbols: Alphabetic | Numeric | '$' | '_';
Identifier: Alphabetic ValidIdentSymbols*;
Identifier: Alphabetic ValidIdentSymbols*; // Bezeichner
// Whitespaces und Kommentare ignorieren
WS: [ \t\r\n]+ -> skip;
InlineComment: '//' ~[\r\n]* -> skip;
MultilineComment: '/*' .*? '*/' -> skip;
WS: [ \t\r\n]+ -> skip; // Leerzeichen ignorieren
InlineComment: '//' ~[\r\n]* -> skip; // Einzeilige Kommentare ignorieren
MultilineComment: '/*' .*? '*/' -> skip; // Mehrzeilige Kommentare ignorieren

View File

@@ -8,7 +8,7 @@ import java.util.Stack;
public class Scope {
private Stack<HashMap<String, ITypeNode>> localVars;
private final Stack<HashMap<String, ITypeNode>> localVars;
public Scope() {
localVars = new Stack<HashMap<String, ITypeNode>>();

View File

@@ -1,6 +1,5 @@
package semantic;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@@ -25,15 +24,11 @@ import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNod
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
import ast.statements.*;
import ast.type.AccessModifierNode;
import ast.type.EnumAccessModifierNode;
import ast.type.ValueNode;
import ast.type.type.*;
import com.sun.jdi.IntegerType;
import semantic.context.ClassContext;
import semantic.context.Context;
import semantic.exceptions.*;
import typechecker.TypeCheckResult;
public class SemanticAnalyzer implements SemanticVisitor {
@@ -114,10 +109,6 @@ public class SemanticAnalyzer implements SemanticVisitor {
@Override
public TypeCheckResult analyze(MethodNode methodNode) {
if (methodNode instanceof ConstructorNode) {
return new TypeCheckResult(true, new BaseType(TypeEnum.VOID));
} else {
var valid = true;
for (var otherMethod : currentClass.getMethods()) {
@@ -159,8 +150,6 @@ public class SemanticAnalyzer implements SemanticVisitor {
}
return new TypeCheckResult(valid, resultType);
}
}
@Override
@@ -177,8 +166,6 @@ public class SemanticAnalyzer implements SemanticVisitor {
currentFields.put(toCheck.identifier, toCheck.type);
}
return new TypeCheckResult(true, null);
}
@Override
@@ -317,9 +304,18 @@ public class SemanticAnalyzer implements SemanticVisitor {
@Override
public TypeCheckResult analyze(IfElseNode toCheck) {
var resultIf = toCheck.ifStatement.accept(this);
var validElseIf = true;
if(!toCheck.elseIfStatements.isEmpty()) {
for(IfNode ifNode : toCheck.elseIfStatements) {
var resultIfFor = ifNode.accept(this);
validElseIf = validElseIf && resultIfFor.isValid();
}
}
if(toCheck.elseStatement != null){
var resultElse = toCheck.elseStatement.accept(this);
return new TypeCheckResult(resultIf.isValid() && resultElse.isValid(), new BaseType(TypeEnum.VOID));
return new TypeCheckResult(resultIf.isValid() && resultElse.isValid() && validElseIf, new BaseType(TypeEnum.VOID));
}
@@ -364,6 +360,7 @@ public class SemanticAnalyzer implements SemanticVisitor {
if (toCheck.target.thisTar) {
var type = getTypeFromMethod(toCheck, new ReferenceType(currentClass.identifier));
if (type != null) {
toCheck.type = type;
return new TypeCheckResult(true, type);
}
}
@@ -375,7 +372,6 @@ public class SemanticAnalyzer implements SemanticVisitor {
}
}
} else {
ReferenceType reference = new ReferenceType(currentClass.identifier);
if (!toCheck.chainedMethods.isEmpty()) {
for (ChainedMethodNode chainedMethod : toCheck.chainedMethods) {
@@ -480,8 +476,8 @@ public class SemanticAnalyzer implements SemanticVisitor {
@Override
public TypeCheckResult analyze(DotNode toCheck) {
if (toCheck.dotSubstractionExpression != null) {
var result = toCheck.dotSubstractionExpression.accept(this);
if (toCheck.dotSubtractionExpression != null) {
var result = toCheck.dotSubtractionExpression.accept(this);
toCheck.setType(result.getType());
return result;
}
@@ -489,7 +485,7 @@ public class SemanticAnalyzer implements SemanticVisitor {
}
@Override
public TypeCheckResult analyze(DotSubstractionNode toCheck) {
public TypeCheckResult analyze(DotSubtractionNode toCheck) {
if (toCheck.value != null) {
var result = toCheck.value.accept(this);
toCheck.setType(result.getType());
@@ -575,6 +571,10 @@ public class SemanticAnalyzer implements SemanticVisitor {
var type = currentFields.get(unary.identifier);
unary.setType(type);
return new TypeCheckResult(valid,type );
} else if (unary.value != null) {
var result = unary.value.accept(this);
unary.setType(result.getType());
return new TypeCheckResult(result.isValid(), result.getType());
} else if (unary.statement != null) {
var result = unary.statement.accept(this);
unary.setType(result.getType());

View File

@@ -15,7 +15,6 @@ import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
import ast.statements.*;
import ast.type.ValueNode;
import typechecker.TypeCheckResult;
public interface SemanticVisitor {
@@ -61,7 +60,7 @@ public interface SemanticVisitor {
TypeCheckResult analyze(DotNode toCheck);
TypeCheckResult analyze(DotSubstractionNode toCheck);
TypeCheckResult analyze(DotSubtractionNode toCheck);
TypeCheckResult analyze(NonCalculationNode toCheck);

View File

@@ -1,23 +1,23 @@
package typechecker;
import ast.type.type.ITypeNode;
public class TypeCheckResult {
private boolean valid;
private ITypeNode type;
public TypeCheckResult(boolean valid, ITypeNode type) {
this.valid = valid;
this.type = type;
}
public boolean isValid() {
return valid;
}
public ITypeNode getType() {
return type;
}
package semantic;
import ast.type.type.ITypeNode;
public class TypeCheckResult {
private final boolean valid;
private final ITypeNode type;
public TypeCheckResult(boolean valid, ITypeNode type) {
this.valid = valid;
this.type = type;
}
public boolean isValid() {
return valid;
}
public ITypeNode getType() {
return type;
}
}

View File

@@ -9,8 +9,8 @@ import java.util.HashMap;
public class ClassContext {
private HashMap<String, FieldContext> fields;
private ArrayList<MethodNode> methods = new ArrayList<>();
private final HashMap<String, FieldContext> fields;
private final ArrayList<MethodNode> methods = new ArrayList<>();
public ClassContext(ClassNode classNode) {

View File

@@ -5,7 +5,7 @@ import java.util.HashMap;
public class Context {
private HashMap<String, ClassContext> classes;
private final HashMap<String, ClassContext> classes;
public Context(ProgramNode programNode) {
classes = new HashMap<>();

View File

@@ -6,8 +6,8 @@ import ast.type.type.*;
public class FieldContext {
private AccessModifierNode accessModifier;
private ITypeNode type;
private final AccessModifierNode accessModifier;
private final ITypeNode type;
public FieldContext(FieldNode field) {
accessModifier = field.accessTypeNode;

View File

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

View File

View File

@@ -2,17 +2,17 @@
### IntelliJs play buttons do not work. Run in "src/test" folder with "make" command to run all
### Or run only parts with "make compile-javac", "make clean" etc.
all: compile-javac compile-raupenpiler
all: compile-javac compile-miniCompiler
compile-javac:
javac -d .\resources\output\javac .\resources\input\CompilerInput.java
compile-raupenpiler:
compile-miniCompiler:
cd ../.. ; mvn -DskipTests install
cd ../.. ; mvn exec:java -DgenJar=true -DgenClass=true -Dexec.mainClass="main.Main" -Dexec.args="'src/main/resources/input/CompilerInput.java' 'src/main/resources/output'"
# cp ../main/resources/output/CompilerInput.class .java/resources/output/raupenpiler
# cp ../main/resources/output/CompilerInput.class .java/resources/output/miniCompiler
test-raupenpiler:
test-miniCompiler:
# move the compiled class to the test/main folder
mv ../main/resources/output/CompilerInput.class .java/main/
# compile the test class
@@ -28,8 +28,8 @@ clean:
rm -f ../main/resources/output/*.jar
# clean resources output folders
rm -f ./resources/output/javac/*.class
rm -f ./resources/output/raupenpiler/*.class
rm -f ./resources/output/raupenpiler/*.jar
rm -f ./resources/output/miniCompiler/*.class
rm -f ./resources/output/miniCompiler/*.jar
# clean logs
rm -f ../main/resources/logs/*
# clean test/java/main folders from .class files for End-to-End tests

File diff suppressed because it is too large Load Diff

View File

@@ -11,8 +11,6 @@ package main;
* Wenn unser Compiler funktioniert, sollten keine Errors kommen (sondern nur die Ausgaben, die wir in der CompilerInput.java Datei gemacht haben,
* oder Methoden, die wir hier aufrufen).</p>
*
* <p><strong>PROBLEM:</strong> Hier kommen Errors, was eigentlich heißt, dass der Compiler nicht funktioniert, der Test sollte eigentlich passen.
* <br><strong>DENN:</strong> Wenn ich statt unserem CompilerInput.class die CompilerInput.class von javac verwende (aus <code> src/test/resources/output/javac </code>), dann funktioniert es.</p>
*/
public class EndToEndTester {
public static void main(String[] args) {

View File

@@ -2,8 +2,6 @@ package main;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import parser.ParserTest;
import parser.ScannerTest;
import semantic.EndToTypedAstTest;
import semantic.SemanticTest;
@@ -15,8 +13,6 @@ import semantic.SemanticTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
InputFilesTest.class,
ScannerTest.class,
ParserTest.class,
SemanticTest.class,
EndToTypedAstTest.class
})

View File

@@ -6,7 +6,7 @@ import ast.ProgramNode;
import ast.expressions.IExpressionNode;
import ast.expressions.binaryexpressions.CalculationNode;
import ast.expressions.binaryexpressions.DotNode;
import ast.expressions.binaryexpressions.DotSubstractionNode;
import ast.expressions.binaryexpressions.DotSubtractionNode;
import ast.expressions.binaryexpressions.NonCalculationNode;
import ast.expressions.unaryexpressions.MemberAccessNode;
import ast.expressions.unaryexpressions.UnaryNode;
@@ -438,9 +438,7 @@ class AstBuilderTest {
BlockNode testMethod3Block = new BlockNode();
testMethod3Block.addStatement(new LocalVariableDeclarationNode(new ReferenceType("SelfReference"),"selfReference1", "=", new UnaryNode(new NewDeclarationNode("SelfReference")))); // Assing einfach "=" ?
MemberAccessNode methodAccess = new MemberAccessNode(false);
methodAccess.addIdentifier("selfReference1");
methodAccess.addIdentifier("selfReference");
TargetNode methodTarget = new TargetNode(methodAccess);
TargetNode methodTarget = new TargetNode("selfReference1");
testMethod3Block.addStatement(new ReturnNode(new UnaryNode(new MethodCallNode(methodTarget,"testMethod1"))));
MethodNode testMethod3 = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod3", testMethod3Block);
@@ -514,31 +512,31 @@ class AstBuilderTest {
ClassNode class1 = Helper.generateEmptyClass("VariableCalculation");
BlockNode aPlusBBlock = new BlockNode();
aPlusBBlock.addStatement(new ReturnNode(new CalculationNode(new CalculationNode(new DotNode(new DotSubstractionNode("a"))), "+", new DotNode(new DotSubstractionNode("b")))));
aPlusBBlock.addStatement(new ReturnNode(new CalculationNode(new CalculationNode(new DotNode(new DotSubtractionNode("a"))), "+", new DotNode(new DotSubtractionNode("b")))));
MethodNode aPlusBMethod = new MethodNode("public", new BaseType(TypeEnum.INT), false, "aPlusB", aPlusBBlock);
aPlusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
aPlusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
BlockNode aMinusBBlock = new BlockNode();
aMinusBBlock.addStatement(new ReturnNode(new CalculationNode(new CalculationNode(new DotNode(new DotSubstractionNode("a"))), "-", new DotNode(new DotSubstractionNode("b")))));
aMinusBBlock.addStatement(new ReturnNode(new CalculationNode(new CalculationNode(new DotNode(new DotSubtractionNode("a"))), "-", new DotNode(new DotSubtractionNode("b")))));
MethodNode aMinusBMethod = new MethodNode("public", new BaseType(TypeEnum.INT), false, "aMinusB", aMinusBBlock);
aMinusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
aMinusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
BlockNode aTimeBBlock = new BlockNode();
aTimeBBlock.addStatement(new ReturnNode(new CalculationNode(new DotNode(new DotNode(new DotSubstractionNode("a")), "*", new DotSubstractionNode("b")))));
aTimeBBlock.addStatement(new ReturnNode(new CalculationNode(new DotNode(new DotNode(new DotSubtractionNode("a")), "*", new DotSubtractionNode("b")))));
MethodNode aTimeBMethod = new MethodNode("public", new BaseType(TypeEnum.INT), false, "aTimeB", aTimeBBlock);
aTimeBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
aTimeBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
BlockNode aDivBBlock = new BlockNode();
aDivBBlock.addStatement(new ReturnNode(new CalculationNode(new DotNode(new DotNode(new DotSubstractionNode("a")), "/", new DotSubstractionNode("b")))));
aDivBBlock.addStatement(new ReturnNode(new CalculationNode(new DotNode(new DotNode(new DotSubtractionNode("a")), "/", new DotSubtractionNode("b")))));
MethodNode aDivBMethod = new MethodNode("public", new BaseType(TypeEnum.INT), false, "aDivB", aDivBBlock);
aDivBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
aDivBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
BlockNode complexCalcBlock = new BlockNode();
complexCalcBlock.addStatement(new ReturnNode(new CalculationNode(null, null, new DotNode(new DotNode(new DotNode(new DotNode(new DotSubstractionNode("a")), "*", new DotSubstractionNode("b")), "/", new DotSubstractionNode(new ValueNode(EnumValueNode.INT_VALUE, "1"))), "*", new DotSubstractionNode(new ValueNode(EnumValueNode.INT_VALUE, "3"))))));
complexCalcBlock.addStatement(new ReturnNode(new CalculationNode(null, null, new DotNode(new DotNode(new DotNode(new DotNode(new DotSubtractionNode("a")), "*", new DotSubtractionNode("b")), "/", new DotSubtractionNode(new ValueNode(EnumValueNode.INT_VALUE, "1"))), "*", new DotSubtractionNode(new ValueNode(EnumValueNode.INT_VALUE, "3"))))));
MethodNode complexCalcMethod = new MethodNode("public", new BaseType(TypeEnum.INT), false, "complexCalc", complexCalcBlock);
complexCalcMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
complexCalcMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));

View File

@@ -2,12 +2,10 @@ package parser;
import ast.ASTNode;
import ast.ClassNode;
import ast.ProgramNode;
import ast.members.ConstructorNode;
import ast.members.MemberNode;
import ast.statements.BlockNode;
import ast.statements.ReturnNode;
import ast.type.AccessModifierNode;
import org.antlr.v4.runtime.CharStream;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonTokenStream;
@@ -39,7 +37,7 @@ public class Helper {
public static ClassNode generateEmptyClass(String className) {
BlockNode blockNode = new BlockNode();
blockNode.addStatement(new ReturnNode(null));
MemberNode constructor = new ConstructorNode("public",className, blockNode);
MemberNode constructor = new ConstructorNode("public", className, blockNode);
ClassNode classNode = new ClassNode("public", className);
classNode.addMember(constructor);
return classNode;

View File

@@ -1,138 +0,0 @@
package parser;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import parser.generated.SimpleJavaLexer;
import parser.generated.SimpleJavaParser;
import static org.junit.jupiter.api.Assertions.*;
import java.util.*;
public class ParserTest {
/*
@BeforeEach
public void init() { // noch nicht benötigt
String inputFilePath = "src/main/resources/input/CompilerInput.java";
String outputDirectoryPath = "src/main/resources/output";
}
*/
@Test
public void parserTest() {
// init
CharStream inputCharStream = CharStreams.fromString("public class Name {}");
SimpleJavaLexer lexer = new SimpleJavaLexer(inputCharStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
tokenStream.fill();
/* Parser -> Parsetree */
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
ParseTree parseTree = parser.program(); // parse the input
//Variante 1 (geht)
String expectedParseTreeAsString = "(program (classDeclaration public class Name { }))";
String actualParseTreeAsString = parseTree.toStringTree(parser);
assertEquals(expectedParseTreeAsString, actualParseTreeAsString);
// Variante 2 (geht nicht)
// - Sollte es gehen und es liegt am Parser? (keine Ahnung) -> Bitte Fehler (actual und expected) durchlesen
// ist die Methode parseStringToTree() korrekt? -> (glaub nicht)
Map<String, Object> expectedTreeStructure = parseStringToTree(expectedParseTreeAsString);
Map<String, Object> actualTreeStructure = buildTreeStructure(parseTree, parser);
// assertEquals(expectedTreeStructure, actualTreeStructure);
}
// Helpers Variante 2.1
public static Map<String, Object> buildTreeStructure(ParseTree tree, Parser parser) {
return buildTree(tree, parser, 0);
}
private static Map<String, Object> buildTree(ParseTree tree, Parser parser, int indent) {
Map<String, Object> node = new HashMap<>();
if (tree instanceof RuleContext) {
int ruleIndex = ((RuleContext) tree).getRuleIndex();
String ruleName = parser.getRuleNames()[ruleIndex];
node.put("rule", ruleName);
} else {
node.put("text", tree.getText());
}
List<Map<String, Object>> children = new ArrayList<>();
for (int i = 0; i < tree.getChildCount(); i++) {
children.add(buildTree(tree.getChild(i), parser, indent + 1));
}
if (!children.isEmpty()) {
node.put("children", children);
}
return node;
}
// Helpers Variante 2.2
public static Map<String, Object> parseStringToTree(String input) {
input = input.trim();
if (input.startsWith("(") && input.endsWith(")")) {
input = input.substring(1, input.length() - 1).trim();
}
return parse(input);
}
private static Map<String, Object> parse(String input) {
Map<String, Object> node = new HashMap<>();
StringBuilder currentToken = new StringBuilder();
List<Map<String, Object>> children = new ArrayList<>();
int depth = 0;
boolean inToken = false;
for (char ch : input.toCharArray()) {
if (ch == '(') {
if (depth == 0) {
if (!currentToken.isEmpty()) {
node.put("node", currentToken.toString().trim());
currentToken.setLength(0);
}
} else {
currentToken.append(ch);
}
depth++;
} else if (ch == ')') {
depth--;
if (depth == 0) {
children.add(parse(currentToken.toString().trim()));
currentToken.setLength(0);
} else {
currentToken.append(ch);
}
} else if (Character.isWhitespace(ch) && depth == 0) {
if (!currentToken.isEmpty()) {
node.put("node", currentToken.toString().trim());
currentToken.setLength(0);
}
} else {
currentToken.append(ch);
}
}
if (!currentToken.isEmpty()) {
node.put("node", currentToken.toString().trim());
}
if (!children.isEmpty()) {
node.put("children", children);
}
return node;
}
}

View File

@@ -1,45 +0,0 @@
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.Token;
import org.junit.jupiter.api.Test;
import parser.generated.SimpleJavaLexer;
import java.util.Arrays;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ScannerTest {
/**
* This test method is used to test the scanner functionality of the SimpleJavaLexer.
* It creates a CharStream from a string representing a simple Java class declaration,
* and uses the SimpleJavaLexer to tokenize this input.
* It then compares the actual tokens and their types produced by the lexer to the expected tokens and their types.
*/
@Test
public void scannerTest() {
// Create a CharStream from a string representing a simple Java class declaration
CharStream inputCharStream = CharStreams.fromString("public class Name {}");
// Use the SimpleJavaLexer to tokenize the input
SimpleJavaLexer lexer = new SimpleJavaLexer(inputCharStream);
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
tokenStream.fill();
// Prepare the expected results
List<String> expectedTokens = Arrays.asList("public", "class", "Name", "{", "}", "<EOF>");
List<String> expectedTokenTypes = Arrays.asList("AccessModifier", "Class", "Identifier", "OpenCurlyBracket", "ClosedCurlyBracket", "EOF");
List<Token> actualTokens = tokenStream.getTokens();
// Compare the actual tokens and their types to the expected tokens and their types
assertEquals(expectedTokens.size(), actualTokens.size());
for (int i = 0; i < expectedTokens.size(); i++) {
assertEquals(expectedTokens.get(i), actualTokens.get(i).getText());
assertEquals(expectedTokenTypes.get(i), SimpleJavaLexer.VOCABULARY.getSymbolicName(actualTokens.get(i).getType()));
}
}
}

View File

@@ -30,6 +30,6 @@ public class SemanticHelper {
ParseTree parseTree = parser.program();
ASTBuilder astBuilder = new ASTBuilder();
return (ProgramNode) astBuilder.visit(parseTree);
return astBuilder.visit(parseTree);
}
}

View File

@@ -4,13 +4,13 @@ public class ControlStructures {
return a + b;
}
public cahr checkNumber(int num) {
public char checkNumber(int num) {
if (num > 0) {
return "p";
return 'p';
} else if (num < 0) {
return "n";
return 'n';
} else {
return "z";
return 'z';
}
}
@@ -19,7 +19,7 @@ public class ControlStructures {
int uneven = 0;
int i = 0;
while (i < limit) {
if (i % 2 == 0) {
if ((i % 2) == 0) {
even++;
} else {
uneven = uneven + 1;

View File

@@ -0,0 +1,5 @@
public class Main {
public static void main(String[] args) {
Person testPerson = new Person(5);
}
}

View File

@@ -8,4 +8,11 @@ public class Person {
public int getAge() {
return this.age;
}
}
public class Person2 {
public void greet() {
Person person = new Person(10);
person.getAge();
}
}

View File

@@ -0,0 +1,25 @@
public class Calculation {
public int add(int a, int b) {
return a + b;
}
public int sub(int a, int b) {
return a - b;
}
public int mul(int a, int b) {
return a * b;
}
public int div(int a, int b) {
return a / b;
}
public int mod(int a, int b) {
return a % b;
}
public int complexCalculation() {
return 3 - 2 * 2 + 5;
}
}

View File

@@ -0,0 +1 @@
public class EmptyClass {}

View File

@@ -0,0 +1,17 @@
public class Loops {
public boolean If(int a, int b) {
if(a == b) {
return true;
} else {
return false;
}
}
public int While(int a) {
int count = 0;
while(count < a) {
count++;
}
return count;
}
}

View File

@@ -1,8 +1,8 @@
class Null{
Null a;
int a;
public Null(){
this.a = null;
this.a = 1;
}
}

View File

@@ -1,4 +1,4 @@
class SelfReference{
class SelfReference {
SelfReference selfReference;
@@ -10,9 +10,9 @@ class SelfReference{
return 1;
}
int testMethod3(){
int testMethod3() {
SelfReference selfReference1 = new SelfReference();
return selfReference1.selfReference.testMethod1();
return selfReference1.testMethod1();
}
}
}

View File

@@ -1,16 +1,8 @@
public class Compiler {
Node node;
public int add(int i, int j) {
node = new Node();
node.x = 1;
return i+j;
}
}
public class Node {
public int x;
public void main() {
Compiler compiler = new Compiler();
int i = compiler.add(5, 8);
public class If {
public If() {
int intValue = 5;
if(intValue == 5) {
intValue--;
}
}
}

View File