Compare commits
121 Commits
ParserAlte
...
main
Author | SHA1 | Date | |
---|---|---|---|
|
4c4c06f728 | ||
|
30bd5a0b5c | ||
f673612f54 | |||
|
9760e39a29 | ||
|
93e17e5415 | ||
|
b151edc2fd | ||
|
c0d8ab8399 | ||
|
f50bb7efd7 | ||
|
51a390752b | ||
|
3114064038 | ||
|
745db43b34 | ||
|
e0286e0840 | ||
|
ebef717141 | ||
|
3de54afa93 | ||
|
30d3cfa44a | ||
efa1a21655 | |||
3fb11e5d7e | |||
|
c6e61defce | ||
|
dbde4e8047 | ||
5a12d61623 | |||
f5bccab651 | |||
0de5c3e993 | |||
3628a0a4d8 | |||
36f0683240 | |||
|
97aadb9ba8 | ||
|
e5dcbb8f99 | ||
e96f30fe19 | |||
64b15af6ef | |||
4ff6854094 | |||
0a9cc7655a | |||
7e66b5b8e3 | |||
d835a98e6f | |||
240913d422 | |||
4bee432294 | |||
0cf4715782 | |||
|
3c0f7e857a | ||
|
2b7e0d0d42 | ||
|
bd61a0e595 | ||
|
24407a5c1c | ||
195440e9d9 | |||
6fa57cf319 | |||
1de6add080 | |||
c315966219 | |||
c2c4974c76 | |||
|
85e0cf3807 | ||
|
6f3fb02666 | ||
|
435697053a | ||
8eba420d48 | |||
fbff03c3d7 | |||
721e1caa79 | |||
6d3e1f859e | |||
f6b34bf70b | |||
430d551f7d | |||
8e0d627505 | |||
6b6051cad8 | |||
1f8e045b1e | |||
ceb1231632 | |||
|
31929878b0 | ||
|
ea97f34398 | ||
|
2f7b310254 | ||
|
9b8155ebab | ||
|
4775c3f47e | ||
|
2e3a7850a4 | ||
|
d925a3258c | ||
|
fb5372bc8f | ||
|
f29be4fd8c | ||
|
34bb86c7f4 | ||
|
c0e197e2d0 | ||
|
ae872ed906 | ||
91552ad147 | |||
084808c3ab | |||
d19748766f | |||
|
4bdb65a6ce | ||
|
97e0c228d6 | ||
|
d4be77ceb2 | ||
ca539add98 | |||
1bcf396f95 | |||
8ba58d492b | |||
|
ed25868ff7 | ||
879fa08cdc | |||
|
0e512161a0 | ||
|
ba08c6f6b0 | ||
c5aea85965 | |||
2a1d0a0b8a | |||
f1abe5d5a8 | |||
|
a9d7e841f5 | ||
|
b7863d0684 | ||
|
7ccff3208c | ||
|
3e0e6f8327 | ||
|
ab5a51d3b1 | ||
|
a4c1c502ab | ||
|
84ecf316cd | ||
|
7ddea8f18d | ||
46154fbb01 | |||
9aac795c07 | |||
e59f4e7190 | |||
|
e6a2b0fe9d | ||
|
44c2f551de | ||
|
bad034acfd | ||
|
2ef50f93a9 | ||
|
1cf1aaf837 | ||
|
2bf73385af | ||
|
b072af346b | ||
|
27baa429b4 | ||
|
6cec17eb45 | ||
87be850a0e | |||
72f82ff863 | |||
7419953510 | |||
449b895d20 | |||
f0dd6d5eb6 | |||
8956362033 | |||
|
ed4aa2d59b | ||
|
6760a17f00 | ||
|
671317f28b | ||
|
e862a7427b | ||
233725778f | |||
|
f7338a06b3 | ||
|
3996082fa7 | ||
|
2537051668 | ||
|
82356ec189 | ||
|
561eafbf4c |
8
.gitignore
vendored
8
.gitignore
vendored
@ -77,10 +77,10 @@ fabric.properties
|
|||||||
.idea/caches/build_file_checksums.ser
|
.idea/caches/build_file_checksums.ser
|
||||||
|
|
||||||
/target
|
/target
|
||||||
src/main/resources/logs/RaupenLog.log
|
src/main/resources/logs/miniCompilerLog.log
|
||||||
src/main/resources/output/CompilerInput.class
|
src/test/java/main/CompilerInput.class
|
||||||
src/test/resources/output/javac/CompilerInput$Test.class
|
src/test/resources/output/javac/CompilerInput$Test.class
|
||||||
src/test/resources/output/javac/CompilerInput.class
|
src/test/resources/output/javac/CompilerInput.class
|
||||||
src/test/resources/output/raupenpiler/CompilerInput.class
|
src/test/resources/output/miniCompiler/CompilerInput.class
|
||||||
src/test/resources/output/raupenpiler/CompilerInput$Test.class
|
src/test/resources/output/miniCompiler/CompilerInput$Test.class
|
||||||
.idea/inspectionProfiles/Project_Default.xml
|
.idea/inspectionProfiles/Project_Default.xml
|
||||||
|
BIN
JavaCompiler-1.0-jar-with-dependencies.jar
Normal file
BIN
JavaCompiler-1.0-jar-with-dependencies.jar
Normal file
Binary file not shown.
37
Makefile
Normal file
37
Makefile
Normal 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
|
BIN
Parser_Dokumentation.pdf
Normal file
BIN
Parser_Dokumentation.pdf
Normal file
Binary file not shown.
136
README.md
Normal file
136
README.md
Normal file
@ -0,0 +1,136 @@
|
|||||||
|
# "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`;
|
||||||
|
- **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
|
||||||
|
Ausführliche Beschreibung der Parser Umsetzung:
|
||||||
|
|
||||||
|
![Parserumsetzung](Parser_Dokumentation.pdf)
|
||||||
|
|
||||||
|
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/main/JavaCompiler-1.0-jar-with-dependencies.jar) 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
|
||||||
|
```
|
31
pom.xml
31
pom.xml
@ -20,7 +20,25 @@
|
|||||||
<dependency>
|
<dependency>
|
||||||
<groupId>org.junit.jupiter</groupId>
|
<groupId>org.junit.jupiter</groupId>
|
||||||
<artifactId>junit-jupiter-engine</artifactId>
|
<artifactId>junit-jupiter-engine</artifactId>
|
||||||
<version>5.9.3</version> <!-- Change the version as needed -->
|
<version>5.11.0-M2</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.platform</groupId>
|
||||||
|
<artifactId>junit-platform-suite-engine</artifactId>
|
||||||
|
<version>1.11.0-M2</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.junit.jupiter</groupId>
|
||||||
|
<artifactId>junit-jupiter-api</artifactId>
|
||||||
|
<version>5.11.0-M2</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>junit</groupId>
|
||||||
|
<artifactId>junit</artifactId>
|
||||||
|
<version>4.13.1</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
<dependency>
|
||||||
@ -44,12 +62,6 @@
|
|||||||
<version>3.26.0</version>
|
<version>3.26.0</version>
|
||||||
<scope>test</scope>
|
<scope>test</scope>
|
||||||
</dependency>
|
</dependency>
|
||||||
<dependency>
|
|
||||||
<groupId>org.mockito</groupId>
|
|
||||||
<artifactId>mockito-core</artifactId>
|
|
||||||
<version>5.11.0</version>
|
|
||||||
<scope>test</scope>
|
|
||||||
</dependency>
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
@ -59,6 +71,11 @@
|
|||||||
<groupId>org.apache.maven.plugins</groupId>
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
<artifactId>maven-surefire-plugin</artifactId>
|
<artifactId>maven-surefire-plugin</artifactId>
|
||||||
<version>3.0.0-M5</version> <!-- Change the version as needed -->
|
<version>3.0.0-M5</version> <!-- Change the version as needed -->
|
||||||
|
<configuration>
|
||||||
|
<includes>
|
||||||
|
<include>**/*Test.java</include>
|
||||||
|
</includes>
|
||||||
|
</configuration>
|
||||||
</plugin>
|
</plugin>
|
||||||
<plugin>
|
<plugin>
|
||||||
<artifactId>maven-assembly-plugin</artifactId>
|
<artifactId>maven-assembly-plugin</artifactId>
|
||||||
|
@ -1,20 +1,6 @@
|
|||||||
package ast;
|
package ast;
|
||||||
|
|
||||||
import bytecode.visitor.ClassVisitor;
|
|
||||||
import semantic.SemanticVisitor;
|
|
||||||
import typechecker.TypeCheckResult;
|
|
||||||
|
|
||||||
public interface ASTNode {
|
public interface ASTNode {
|
||||||
|
|
||||||
//Todo: @BruderJohn & @i22007 Interface anwenden + geeignetetn Methodename.
|
|
||||||
|
|
||||||
/*
|
|
||||||
Typecheck:
|
|
||||||
public TypeCheckResult acceptType(SemanticVisitor visitor);
|
|
||||||
|
|
||||||
Bytecode:
|
|
||||||
public void accepByteCode(ClassVisitor classVisitor);
|
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,12 +1,11 @@
|
|||||||
package ast;
|
package ast;
|
||||||
|
|
||||||
import ast.type.AccessModifierNode;
|
import ast.type.AccessModifierNode;
|
||||||
import ast.members.ConstructorNode;
|
|
||||||
import ast.members.MemberNode;
|
import ast.members.MemberNode;
|
||||||
import ast.members.MethodNode;
|
import ast.members.MethodNode;
|
||||||
import bytecode.visitor.ClassVisitor;
|
import bytecode.visitor.ClassVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@ -17,11 +16,11 @@ public class ClassNode implements ASTNode, Visitable {
|
|||||||
public String identifier;
|
public String identifier;
|
||||||
public List<MemberNode> members = new ArrayList<>();
|
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.accessType = new AccessModifierNode(accessType);
|
||||||
this.identifier = identifier;
|
this.identifier = identifier;
|
||||||
}
|
}
|
||||||
@ -30,7 +29,7 @@ public class ClassNode implements ASTNode, Visitable {
|
|||||||
members.add(member);
|
members.add(member);
|
||||||
}
|
}
|
||||||
|
|
||||||
public List<MethodNode> getMethods(){
|
public List<MethodNode> getMethods() {
|
||||||
List<MethodNode> methods = new ArrayList<>();
|
List<MethodNode> methods = new ArrayList<>();
|
||||||
for (MemberNode member : members) {
|
for (MemberNode member : members) {
|
||||||
if (member instanceof MethodNode methodNode) {
|
if (member instanceof MethodNode methodNode) {
|
||||||
|
@ -2,7 +2,7 @@ package ast;
|
|||||||
|
|
||||||
import bytecode.visitor.ProgramVisitor;
|
import bytecode.visitor.ProgramVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
|
@ -4,12 +4,12 @@ import ast.expressions.IExpressionNode;
|
|||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class BinaryNode implements IExpressionNode, Visitable {
|
public class BinaryNode implements IExpressionNode, Visitable {
|
||||||
|
|
||||||
private ITypeNode typeNode;
|
public ITypeNode typeNode;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
|
@ -1,15 +1,13 @@
|
|||||||
package ast.expressions.binaryexpressions;
|
package ast.expressions.binaryexpressions;
|
||||||
|
|
||||||
import ast.type.type.*;
|
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class CalculationNode extends BinaryNode {
|
public class CalculationNode extends BinaryNode {
|
||||||
public CalculationNode calculationExpression;
|
public CalculationNode calculationExpression;
|
||||||
public EnumLineOperator operator;
|
public EnumLineOperator operator;
|
||||||
public DotNode dotExpression;
|
public DotNode dotExpression;
|
||||||
private ITypeNode typeNode;
|
|
||||||
|
|
||||||
public CalculationNode(CalculationNode calculationExpression, String operator, DotNode dotExpression) {
|
public CalculationNode(CalculationNode calculationExpression, String operator, DotNode dotExpression) {
|
||||||
this.calculationExpression = calculationExpression;
|
this.calculationExpression = calculationExpression;
|
||||||
@ -21,11 +19,11 @@ public class CalculationNode extends BinaryNode {
|
|||||||
this.dotExpression = dotExpression;
|
this.dotExpression = dotExpression;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setOperator(String operator) {
|
public void setOperator(String operator) {
|
||||||
if(operator != null) {
|
if (operator != null) {
|
||||||
if(operator.equals("+")) {
|
if (operator.equals("+")) {
|
||||||
this.operator = EnumLineOperator.PLUS;
|
this.operator = EnumLineOperator.PLUS;
|
||||||
} else if(operator.equals("-")) {
|
} else if (operator.equals("-")) {
|
||||||
this.operator = EnumLineOperator.MINUS;
|
this.operator = EnumLineOperator.MINUS;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,30 +2,28 @@ package ast.expressions.binaryexpressions;
|
|||||||
|
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class DotNode extends BinaryNode {
|
public class DotNode extends BinaryNode {
|
||||||
public DotNode dotExpression;
|
public DotNode dotExpression;
|
||||||
public EnumDotOperator operator;
|
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;
|
this.dotExpression = dotExpression;
|
||||||
setOperator(operator);
|
setOperator(operator);
|
||||||
this.dotSubstractionExpression = dotSubstractionExpression;
|
this.dotSubtractionExpression = dotSubtractionExpression;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DotNode(DotSubstractionNode dotSubstractionExpression) {
|
public DotNode(DotSubtractionNode dotSubtractionExpression) {
|
||||||
this.dotSubstractionExpression = dotSubstractionExpression;
|
this.dotSubtractionExpression = dotSubtractionExpression;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setOperator(String operator) {
|
public void setOperator(String operator) {
|
||||||
if(operator.equals("*")) {
|
switch (operator) {
|
||||||
this.operator = EnumDotOperator.MULT;
|
case "*" -> this.operator = EnumDotOperator.MULT;
|
||||||
} else if(operator.equals("/")) {
|
case "/" -> this.operator = EnumDotOperator.DIV;
|
||||||
this.operator = EnumDotOperator.DIV;
|
case "%" -> this.operator = EnumDotOperator.MOD;
|
||||||
} else if(operator.equals("%")) {
|
|
||||||
this.operator = EnumDotOperator.MOD;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2,32 +2,31 @@ package ast.expressions.binaryexpressions;
|
|||||||
|
|
||||||
import ast.expressions.unaryexpressions.MemberAccessNode;
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
import ast.type.type.*;
|
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class DotSubstractionNode extends BinaryNode {
|
public class DotSubtractionNode extends BinaryNode {
|
||||||
public ValueNode value;
|
public ValueNode value;
|
||||||
public String identifier;
|
public String identifier;
|
||||||
public MemberAccessNode memberAccess;
|
public MemberAccessNode memberAccess;
|
||||||
public MethodCallNode methodCall;
|
public MethodCallNode methodCall;
|
||||||
public CalculationNode calculationExpression;
|
public CalculationNode calculationExpression;
|
||||||
|
|
||||||
public DotSubstractionNode(ValueNode value) {
|
public DotSubtractionNode(ValueNode value) {
|
||||||
this.value = value;
|
this.value = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DotSubstractionNode(String identifier) {
|
public DotSubtractionNode(String identifier) {
|
||||||
this.identifier = identifier;
|
this.identifier = identifier;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DotSubstractionNode(MemberAccessNode memberAccess) {
|
public DotSubtractionNode(MemberAccessNode memberAccess) {
|
||||||
this.memberAccess = memberAccess;
|
this.memberAccess = memberAccess;
|
||||||
}
|
}
|
||||||
|
|
||||||
public DotSubstractionNode(MethodCallNode methodCall, CalculationNode calculationExpression) {
|
public DotSubtractionNode(MethodCallNode methodCall, CalculationNode calculationExpression) {
|
||||||
this.methodCall = methodCall;
|
this.methodCall = methodCall;
|
||||||
this.calculationExpression = calculationExpression;
|
this.calculationExpression = calculationExpression;
|
||||||
}
|
}
|
@ -2,10 +2,9 @@ package ast.expressions.binaryexpressions;
|
|||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import ast.expressions.unaryexpressions.UnaryNode;
|
import ast.expressions.unaryexpressions.UnaryNode;
|
||||||
import ast.type.type.*;
|
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class NonCalculationNode extends BinaryNode {
|
public class NonCalculationNode extends BinaryNode {
|
||||||
public UnaryNode unaryExpression;
|
public UnaryNode unaryExpression;
|
||||||
@ -18,23 +17,16 @@ public class NonCalculationNode extends BinaryNode {
|
|||||||
this.expression = expression;
|
this.expression = expression;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void setOperator(String operator) {
|
public void setOperator(String operator) {
|
||||||
if(operator.equals("&&")) {
|
switch (operator) {
|
||||||
this.operator = EnumNonCalculationOperator.AND;
|
case "&&" -> this.operator = EnumNonCalculationOperator.AND;
|
||||||
} else if(operator.equals("||")) {
|
case "||" -> this.operator = EnumNonCalculationOperator.OR;
|
||||||
this.operator = EnumNonCalculationOperator.OR;
|
case ">" -> this.operator = EnumNonCalculationOperator.GREATER;
|
||||||
} else if(operator.equals(">")) {
|
case "<" -> this.operator = EnumNonCalculationOperator.LESS;
|
||||||
this.operator = EnumNonCalculationOperator.GREATER;
|
case ">=" -> this.operator = EnumNonCalculationOperator.GREATER_EQUAL;
|
||||||
} else if(operator.equals("<")) {
|
case "<=" -> this.operator = EnumNonCalculationOperator.LESS_EQUAL;
|
||||||
this.operator = EnumNonCalculationOperator.LESS;
|
case "==" -> this.operator = EnumNonCalculationOperator.EQUAL;
|
||||||
} else if(operator.equals(">=")) {
|
case "!=" -> this.operator = EnumNonCalculationOperator.NOT_EQUAL;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,10 +1,11 @@
|
|||||||
package ast.expressions.unaryexpressions;
|
package ast.expressions.unaryexpressions;
|
||||||
|
|
||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
|
||||||
import ast.type.type.ITypeNode;
|
import ast.type.type.ITypeNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
|
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@ -40,4 +41,5 @@ public class MemberAccessNode implements ASTNode, Visitable {
|
|||||||
this.typeNode = typeNode;
|
this.typeNode = typeNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,13 +1,12 @@
|
|||||||
package ast.expressions.unaryexpressions;
|
package ast.expressions.unaryexpressions;
|
||||||
|
|
||||||
import ast.ASTNode;
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
|
import ast.type.type.ITypeNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
|
||||||
|
|
||||||
public class NotNode implements ASTNode, Visitable {
|
public class NotNode implements IExpressionNode {
|
||||||
public IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
|
|
||||||
public NotNode(IExpressionNode expression) {
|
public NotNode(IExpressionNode expression) {
|
||||||
@ -24,4 +23,13 @@ public class NotNode implements ASTNode, Visitable {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ITypeNode getType() {
|
||||||
|
return expression.getType();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void setType(ITypeNode type) {
|
||||||
|
this.expression.setType(type);
|
||||||
|
}
|
||||||
}
|
}
|
@ -6,7 +6,7 @@ import ast.type.type.*;
|
|||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
@ -18,10 +18,10 @@ public class UnaryNode implements IExpressionNode {
|
|||||||
public NotNode notExpression;
|
public NotNode notExpression;
|
||||||
public IStatementNode statement;
|
public IStatementNode statement;
|
||||||
public IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
private ITypeNode type;
|
public ITypeNode type;
|
||||||
|
|
||||||
public UnaryNode(String value) {
|
public UnaryNode(String value) {
|
||||||
if(Objects.equals(value, "this")) {
|
if (Objects.equals(value, "this")) {
|
||||||
this.thisExp = "this";
|
this.thisExp = "this";
|
||||||
} else {
|
} else {
|
||||||
this.identifier = value;
|
this.identifier = value;
|
||||||
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -11,13 +11,8 @@ import java.util.List;
|
|||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
|
|
||||||
public class ConstructorNode extends MethodNode implements Visitable {
|
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) {
|
public ConstructorNode(String accessType, String identifier, BlockNode block) {
|
||||||
this.accessType = new AccessModifierNode(accessType);
|
this.accesModifier = new AccessModifierNode(accessType);
|
||||||
this.identifier = identifier;
|
this.identifier = identifier;
|
||||||
this.block = block;
|
this.block = block;
|
||||||
}
|
}
|
||||||
@ -32,8 +27,7 @@ public class ConstructorNode extends MethodNode implements Visitable {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public boolean isSame(MethodNode methodNode) {
|
public boolean isSame(MethodNode methodNode) {
|
||||||
if (!(Objects.equals(this.identifier, methodNode.getIdentifier()))
|
if (!(Objects.equals(this.identifier, methodNode.getIdentifier())) || getParameters().size() != methodNode.getParameters().size()) {
|
||||||
|| getParameters().size() != methodNode.getParameters().size()) {
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -3,9 +3,8 @@ package ast.members;
|
|||||||
import ast.type.AccessModifierNode;
|
import ast.type.AccessModifierNode;
|
||||||
import ast.type.type.ITypeNode;
|
import ast.type.type.ITypeNode;
|
||||||
import bytecode.visitor.ClassVisitor;
|
import bytecode.visitor.ClassVisitor;
|
||||||
import bytecode.visitor.MethodVisitor;
|
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class FieldNode implements MemberNode, Visitable {
|
public class FieldNode implements MemberNode, Visitable {
|
||||||
@ -13,7 +12,7 @@ public class FieldNode implements MemberNode, Visitable {
|
|||||||
public ITypeNode type;
|
public ITypeNode type;
|
||||||
public String identifier;
|
public String identifier;
|
||||||
|
|
||||||
public FieldNode(AccessModifierNode accessTypeNode, ITypeNode type, String name){
|
public FieldNode(AccessModifierNode accessTypeNode, ITypeNode type, String name) {
|
||||||
this.accessTypeNode = accessTypeNode;
|
this.accessTypeNode = accessTypeNode;
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.identifier = name;
|
this.identifier = name;
|
||||||
|
@ -5,7 +5,6 @@ import bytecode.visitor.MethodVisitor;
|
|||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class MainMethodNode extends MethodNode implements Visitable {
|
public class MainMethodNode extends MethodNode implements Visitable {
|
||||||
public BlockNode block;
|
|
||||||
|
|
||||||
public MainMethodNode(BlockNode block) {
|
public MainMethodNode(BlockNode block) {
|
||||||
this.block = block;
|
this.block = block;
|
||||||
|
@ -10,7 +10,8 @@ import ast.ASTNode;
|
|||||||
@JsonSubTypes({
|
@JsonSubTypes({
|
||||||
@JsonSubTypes.Type(value = MethodNode.class, name = "Method"),
|
@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 {
|
||||||
|
}
|
||||||
|
@ -6,7 +6,7 @@ import ast.type.AccessModifierNode;
|
|||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@ -15,16 +15,16 @@ import java.util.Objects;
|
|||||||
|
|
||||||
public class MethodNode implements MemberNode, Visitable {
|
public class MethodNode implements MemberNode, Visitable {
|
||||||
public AccessModifierNode accesModifier;
|
public AccessModifierNode accesModifier;
|
||||||
private ITypeNode type;
|
public ITypeNode type;
|
||||||
public Boolean voidType;
|
public Boolean voidType;
|
||||||
private String identifier;
|
public String identifier;
|
||||||
public List<ParameterNode> parameters = new ArrayList<>();
|
public List<ParameterNode> parameters = new ArrayList<>();
|
||||||
public BlockNode block;
|
public BlockNode block;
|
||||||
|
|
||||||
public MethodNode() {
|
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.accesModifier = new AccessModifierNode(accessModifier);
|
||||||
this.type = type;
|
this.type = type;
|
||||||
this.voidType = voidType;
|
this.voidType = voidType;
|
||||||
@ -40,7 +40,7 @@ public class MethodNode implements MemberNode, Visitable {
|
|||||||
return parameters;
|
return parameters;
|
||||||
}
|
}
|
||||||
|
|
||||||
public boolean isSame(MethodNode methodNode){
|
public boolean isSame(MethodNode methodNode) {
|
||||||
if (!(Objects.equals(this.identifier, methodNode.getIdentifier())) || type.equals(methodNode.type)
|
if (!(Objects.equals(this.identifier, methodNode.getIdentifier())) || type.equals(methodNode.type)
|
||||||
|| getParameters().size() != methodNode.getParameters().size()) {
|
|| getParameters().size() != methodNode.getParameters().size()) {
|
||||||
return false;
|
return false;
|
||||||
|
@ -3,7 +3,7 @@ package ast.parameters;
|
|||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class ParameterNode implements ASTNode, Visitable {
|
public class ParameterNode implements ASTNode, Visitable {
|
||||||
|
@ -1,11 +0,0 @@
|
|||||||
package ast.statement;
|
|
||||||
|
|
||||||
import ast.statements.IStatementNode;
|
|
||||||
|
|
||||||
import java.util.List;
|
|
||||||
|
|
||||||
public class BlockStatementNode {
|
|
||||||
List<IStatementNode> statements;
|
|
||||||
|
|
||||||
public BlockStatementNode(List<IStatementNode> statements) {this.statements = statements;}
|
|
||||||
}
|
|
@ -3,7 +3,7 @@ package ast.statementexpressions;
|
|||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class AssignNode implements IStatementExpressionNode {
|
public class AssignNode implements IStatementExpressionNode {
|
||||||
public AssignableNode assignable;
|
public AssignableNode assignable;
|
||||||
|
@ -2,12 +2,13 @@ package ast.statementexpressions;
|
|||||||
|
|
||||||
import ast.expressions.unaryexpressions.MemberAccessNode;
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
import ast.type.type.ITypeNode;
|
import ast.type.type.ITypeNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class AssignableNode implements IStatementExpressionNode {
|
public class AssignableNode implements IStatementExpressionNode {
|
||||||
public String identifier;
|
public String identifier;
|
||||||
private ITypeNode typeNode;
|
public ITypeNode typeNode;
|
||||||
|
|
||||||
public MemberAccessNode memberAccess;
|
public MemberAccessNode memberAccess;
|
||||||
|
|
||||||
@ -24,10 +25,6 @@ public class AssignableNode implements IStatementExpressionNode {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
public ITypeNode getTypeNode() {
|
|
||||||
return typeNode;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void setTypeNode(ITypeNode typeNode) {
|
public void setTypeNode(ITypeNode typeNode) {
|
||||||
this.typeNode = typeNode;
|
this.typeNode = typeNode;
|
||||||
}
|
}
|
||||||
|
@ -2,4 +2,5 @@ package ast.statementexpressions;
|
|||||||
|
|
||||||
import ast.statements.IStatementNode;
|
import ast.statements.IStatementNode;
|
||||||
|
|
||||||
public interface IStatementExpressionNode extends IStatementNode {}
|
public interface IStatementExpressionNode extends IStatementNode {
|
||||||
|
}
|
||||||
|
@ -3,7 +3,7 @@ package ast.statementexpressions;
|
|||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
@ -4,10 +4,10 @@ import ast.statementexpressions.AssignableNode;
|
|||||||
import ast.statementexpressions.IStatementExpressionNode;
|
import ast.statementexpressions.IStatementExpressionNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class DecrementNode implements IStatementExpressionNode {
|
public class DecrementNode implements IStatementExpressionNode, Visitable {
|
||||||
public CrementType crementType;
|
public CrementType crementType;
|
||||||
public AssignableNode assignableExpression;
|
public AssignableNode assignableExpression;
|
||||||
|
|
||||||
@ -20,4 +20,9 @@ public class DecrementNode implements IStatementExpressionNode {
|
|||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,9 +4,10 @@ import ast.statementexpressions.AssignableNode;
|
|||||||
import ast.statementexpressions.IStatementExpressionNode;
|
import ast.statementexpressions.IStatementExpressionNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import visitor.Visitable;
|
||||||
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class IncrementNode implements IStatementExpressionNode {
|
public class IncrementNode implements IStatementExpressionNode, Visitable {
|
||||||
public CrementType crementType;
|
public CrementType crementType;
|
||||||
public AssignableNode assignableExpression;
|
public AssignableNode assignableExpression;
|
||||||
|
|
||||||
@ -19,4 +20,9 @@ public class IncrementNode implements IStatementExpressionNode {
|
|||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -4,7 +4,7 @@ import ast.ASTNode;
|
|||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@ -22,11 +22,6 @@ public class ChainedMethodNode implements ASTNode, Visitable {
|
|||||||
expressions.add(expression);
|
expressions.add(expression);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void accept(MethodVisitor methodVisitor) {
|
|
||||||
methodVisitor.visit(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return null;
|
return null;
|
||||||
|
@ -2,15 +2,17 @@ package ast.statementexpressions.methodcallstatementnexpressions;
|
|||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import ast.statements.IStatementNode;
|
import ast.statements.IStatementNode;
|
||||||
|
import ast.type.type.ITypeNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
public class MethodCallNode implements IStatementNode {
|
public class MethodCallNode implements IStatementNode {
|
||||||
public TargetNode target;
|
public TargetNode target;
|
||||||
|
public ITypeNode type;
|
||||||
public List<ChainedMethodNode> chainedMethods = new ArrayList<>();
|
public List<ChainedMethodNode> chainedMethods = new ArrayList<>();
|
||||||
public String identifier;
|
public String identifier;
|
||||||
public List<IExpressionNode> parameters = new ArrayList<>();
|
public List<IExpressionNode> parameters = new ArrayList<>();
|
||||||
|
@ -3,9 +3,8 @@ package ast.statementexpressions.methodcallstatementnexpressions;
|
|||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
import ast.expressions.unaryexpressions.MemberAccessNode;
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
import ast.statementexpressions.NewDeclarationNode;
|
import ast.statementexpressions.NewDeclarationNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class TargetNode implements ASTNode, Visitable {
|
public class TargetNode implements ASTNode, Visitable {
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
import ast.ASTNode;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
@ -11,7 +11,8 @@ import java.util.List;
|
|||||||
public class BlockNode implements IStatementNode, Visitable {
|
public class BlockNode implements IStatementNode, Visitable {
|
||||||
public List<IStatementNode> statements = new ArrayList<>();
|
public List<IStatementNode> statements = new ArrayList<>();
|
||||||
|
|
||||||
public BlockNode() {}
|
public BlockNode() {
|
||||||
|
}
|
||||||
|
|
||||||
public void addStatement(IStatementNode statement) {
|
public void addStatement(IStatementNode statement) {
|
||||||
statements.add(statement);
|
statements.add(statement);
|
||||||
@ -22,4 +23,9 @@ public class BlockNode implements IStatementNode, Visitable {
|
|||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -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;}
|
|
||||||
}
|
|
@ -1,7 +1,8 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class ElseNode implements IStatementNode {
|
public class ElseNode implements IStatementNode {
|
||||||
public BlockNode block;
|
public BlockNode block;
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -20,6 +21,11 @@ public class IfElseNode implements IStatementNode {
|
|||||||
elseIfStatements.add(elseIfStament);
|
elseIfStatements.add(elseIfStament);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
|
@ -2,7 +2,7 @@ package ast.statements;
|
|||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class IfNode implements IStatementNode {
|
public class IfNode implements IStatementNode {
|
||||||
public IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
|
@ -4,7 +4,7 @@ import ast.expressions.IExpressionNode;
|
|||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class LocalVariableDeclarationNode implements IStatementNode {
|
public class LocalVariableDeclarationNode implements IStatementNode {
|
||||||
public ITypeNode type;
|
public ITypeNode type;
|
||||||
|
@ -3,14 +3,14 @@ package ast.statements;
|
|||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class ReturnNode implements IStatementNode {
|
public class ReturnNode implements IStatementNode {
|
||||||
public IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
public Boolean voidReturn = false;
|
public Boolean voidReturn = false;
|
||||||
|
|
||||||
public ReturnNode(IExpressionNode expression) {
|
public ReturnNode(IExpressionNode expression) {
|
||||||
if(expression != null) {
|
if (expression != null) {
|
||||||
this.expression = expression;
|
this.expression = expression;
|
||||||
} else {
|
} else {
|
||||||
voidReturn = true;
|
voidReturn = true;
|
||||||
|
@ -1,8 +1,9 @@
|
|||||||
package ast.statements;
|
package ast.statements;
|
||||||
|
|
||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public class WhileNode implements IStatementNode {
|
public class WhileNode implements IStatementNode {
|
||||||
public IExpressionNode expression;
|
public IExpressionNode expression;
|
||||||
@ -13,6 +14,15 @@ public class WhileNode implements IStatementNode {
|
|||||||
this.block = block;
|
this.block = block;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void test() {
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void accept(MethodVisitor methodVisitor) {
|
||||||
|
methodVisitor.visit(this);
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult accept(SemanticVisitor visitor) {
|
public TypeCheckResult accept(SemanticVisitor visitor) {
|
||||||
return visitor.analyze(this);
|
return visitor.analyze(this);
|
||||||
|
@ -8,7 +8,7 @@ public class AccessModifierNode {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private void setModifier(String accessType) {
|
private void setModifier(String accessType) {
|
||||||
switch(accessType) {
|
switch (accessType) {
|
||||||
case "public":
|
case "public":
|
||||||
this.accessType = EnumAccessModifierNode.PUBLIC;
|
this.accessType = EnumAccessModifierNode.PUBLIC;
|
||||||
break;
|
break;
|
||||||
|
@ -3,7 +3,7 @@ package ast.type;
|
|||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
import visitor.Visitable;
|
import visitor.Visitable;
|
||||||
|
|
||||||
public class ValueNode implements ASTNode, Visitable {
|
public class ValueNode implements ASTNode, Visitable {
|
||||||
|
@ -2,7 +2,7 @@ package ast.type.type;
|
|||||||
|
|
||||||
public class BaseType implements ITypeNode {
|
public class BaseType implements ITypeNode {
|
||||||
|
|
||||||
private TypeEnum typeEnum;
|
public final TypeEnum typeEnum;
|
||||||
|
|
||||||
public BaseType(TypeEnum typeEnum) {
|
public BaseType(TypeEnum typeEnum) {
|
||||||
this.typeEnum = typeEnum;
|
this.typeEnum = typeEnum;
|
||||||
@ -21,8 +21,6 @@ public class BaseType implements ITypeNode {
|
|||||||
if (getClass() != obj.getClass())
|
if (getClass() != obj.getClass())
|
||||||
return false;
|
return false;
|
||||||
BaseType other = (BaseType) obj;
|
BaseType other = (BaseType) obj;
|
||||||
if (typeEnum != other.typeEnum)
|
return typeEnum == other.typeEnum;
|
||||||
return false;
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
package ast.type.type;
|
package ast.type.type;
|
||||||
|
|
||||||
public interface ITypeNode {
|
public interface ITypeNode {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
package ast.type.type;
|
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) {
|
public ReferenceType(String identifier) {
|
||||||
this.identifier = identifier;
|
this.identifier = identifier;
|
||||||
@ -22,11 +22,8 @@ public class ReferenceType implements ITypeNode{
|
|||||||
return false;
|
return false;
|
||||||
ReferenceType other = (ReferenceType) obj;
|
ReferenceType other = (ReferenceType) obj;
|
||||||
if (identifier == null) {
|
if (identifier == null) {
|
||||||
if (other.identifier != null)
|
return other.identifier == null;
|
||||||
return false;
|
} else return identifier.equals(other.identifier);
|
||||||
} else if (!identifier.equals(other.identifier))
|
|
||||||
return false;
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -4,6 +4,6 @@ public enum TypeEnum {
|
|||||||
VOID,
|
VOID,
|
||||||
INT,
|
INT,
|
||||||
CHAR,
|
CHAR,
|
||||||
BOOL;
|
BOOL,
|
||||||
|
NULL
|
||||||
}
|
}
|
||||||
|
@ -17,9 +17,9 @@ public class ByteCodeGenerator implements ProgramVisitor {
|
|||||||
|
|
||||||
private JarOutputStream jarOutputStream;
|
private JarOutputStream jarOutputStream;
|
||||||
private ByteArrayOutputStream byteArrayOutputStream;
|
private ByteArrayOutputStream byteArrayOutputStream;
|
||||||
private String outputDirectory;
|
private final String outputDirectory;
|
||||||
private boolean generateJar;
|
private final boolean generateJar;
|
||||||
private boolean generateClassFiles;
|
private final boolean generateClassFiles;
|
||||||
|
|
||||||
public ByteCodeGenerator(String outputDirectory, boolean generateJar, boolean generateClassFiles) {
|
public ByteCodeGenerator(String outputDirectory, boolean generateJar, boolean generateClassFiles) {
|
||||||
this.outputDirectory = outputDirectory;
|
this.outputDirectory = outputDirectory;
|
||||||
|
@ -19,15 +19,15 @@ import java.util.jar.JarOutputStream;
|
|||||||
|
|
||||||
|
|
||||||
public class ClassCodeGen implements ClassVisitor {
|
public class ClassCodeGen implements ClassVisitor {
|
||||||
private Mapper mapper;
|
private final Mapper mapper;
|
||||||
private ClassWriter classWriter;
|
private ClassWriter classWriter;
|
||||||
private JarOutputStream jarOutputStream;
|
private final JarOutputStream jarOutputStream;
|
||||||
private String outputDirectory;
|
private final String outputDirectory;
|
||||||
private boolean generateJar;
|
private final boolean generateJar;
|
||||||
private boolean generateClassFiles;
|
private final boolean generateClassFiles;
|
||||||
|
|
||||||
public ClassCodeGen(JarOutputStream jarOutputStream, String outputDirectory, boolean generateJar, boolean generateClassFiles) {
|
public ClassCodeGen(JarOutputStream jarOutputStream, String outputDirectory, boolean generateJar, boolean generateClassFiles) {
|
||||||
mapper = new Mapper();
|
this.mapper = new Mapper();
|
||||||
this.jarOutputStream = jarOutputStream;
|
this.jarOutputStream = jarOutputStream;
|
||||||
this.outputDirectory = outputDirectory;
|
this.outputDirectory = outputDirectory;
|
||||||
this.generateJar = generateJar;
|
this.generateJar = generateJar;
|
||||||
|
@ -3,6 +3,7 @@ package bytecode;
|
|||||||
import ast.parameters.ParameterNode;
|
import ast.parameters.ParameterNode;
|
||||||
import ast.type.*;
|
import ast.type.*;
|
||||||
import ast.type.type.BaseType;
|
import ast.type.type.BaseType;
|
||||||
|
import ast.type.type.ITypeNode;
|
||||||
import ast.type.type.ReferenceType;
|
import ast.type.type.ReferenceType;
|
||||||
import ast.type.type.TypeEnum;
|
import ast.type.type.TypeEnum;
|
||||||
import org.objectweb.asm.Opcodes;
|
import org.objectweb.asm.Opcodes;
|
||||||
@ -24,7 +25,7 @@ public class Mapper {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
public String generateMethodDescriptor(BaseType type, List<ParameterNode> parameters) {
|
public String generateMethodDescriptor(ITypeNode type, List<ParameterNode> parameters) {
|
||||||
String descriptor = "(";
|
String descriptor = "(";
|
||||||
for (ParameterNode parameterNode : parameters) {
|
for (ParameterNode parameterNode : parameters) {
|
||||||
if(parameterNode.type instanceof BaseType) {
|
if(parameterNode.type instanceof BaseType) {
|
||||||
@ -35,7 +36,11 @@ public class Mapper {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
descriptor += ")";
|
descriptor += ")";
|
||||||
descriptor += getTypeChar(type);
|
if(type instanceof BaseType) {
|
||||||
|
descriptor += getTypeChar((BaseType) type);
|
||||||
|
} else if(type instanceof ReferenceType) {
|
||||||
|
descriptor += "L" + ((ReferenceType) type).getIdentifier() +";";
|
||||||
|
}
|
||||||
return descriptor;
|
return descriptor;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -10,14 +10,15 @@ import ast.members.MainMethodNode;
|
|||||||
import ast.members.MethodNode;
|
import ast.members.MethodNode;
|
||||||
import ast.parameters.ParameterNode;
|
import ast.parameters.ParameterNode;
|
||||||
import ast.statementexpressions.AssignNode;
|
import ast.statementexpressions.AssignNode;
|
||||||
|
import ast.statementexpressions.AssignableNode;
|
||||||
import ast.statementexpressions.NewDeclarationNode;
|
import ast.statementexpressions.NewDeclarationNode;
|
||||||
import ast.statementexpressions.crementexpressions.CrementType;
|
import ast.statementexpressions.crementexpressions.CrementType;
|
||||||
import ast.statementexpressions.crementexpressions.DecrementNode;
|
import ast.statementexpressions.crementexpressions.DecrementNode;
|
||||||
import ast.statementexpressions.crementexpressions.IncrementNode;
|
import ast.statementexpressions.crementexpressions.IncrementNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNode;
|
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
|
||||||
import ast.statements.*;
|
import ast.statements.*;
|
||||||
|
import ast.type.AccessModifierNode;
|
||||||
|
import ast.type.EnumAccessModifierNode;
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
import ast.type.type.BaseType;
|
import ast.type.type.BaseType;
|
||||||
import ast.type.type.ReferenceType;
|
import ast.type.type.ReferenceType;
|
||||||
@ -35,11 +36,11 @@ import static org.objectweb.asm.Opcodes.*;
|
|||||||
|
|
||||||
public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
||||||
|
|
||||||
private ClassWriter classWriter;
|
private final ClassWriter classWriter;
|
||||||
private Mapper mapper;
|
private final Mapper mapper;
|
||||||
private MethodVisitor methodVisitor;
|
private MethodVisitor methodVisitor;
|
||||||
|
|
||||||
private List<String> localVariables;
|
private final List<String> localVariables;
|
||||||
|
|
||||||
public MethodCodeGen(ClassWriter classWriter) {
|
public MethodCodeGen(ClassWriter classWriter) {
|
||||||
this.classWriter = classWriter;
|
this.classWriter = classWriter;
|
||||||
@ -53,7 +54,7 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
@Override
|
@Override
|
||||||
public void visit(ConstructorNode constructorNode) {
|
public void visit(ConstructorNode constructorNode) {
|
||||||
methodVisitor =
|
methodVisitor =
|
||||||
classWriter.visitMethod(mapper.mapAccessTypeToOpcode(constructorNode.accessType),
|
classWriter.visitMethod(mapper.mapAccessTypeToOpcode(constructorNode.accesModifier),
|
||||||
"<init>",
|
"<init>",
|
||||||
mapper.generateMethodDescriptor(new BaseType(TypeEnum.VOID), constructorNode.parameters),
|
mapper.generateMethodDescriptor(new BaseType(TypeEnum.VOID), constructorNode.parameters),
|
||||||
null,
|
null,
|
||||||
@ -71,9 +72,7 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
|
|
||||||
// Visit all statements
|
// Visit all statements
|
||||||
for (IStatementNode statementNode : constructorNode.block.statements) {
|
for (IStatementNode statementNode : constructorNode.block.statements) {
|
||||||
if (statementNode != null) {
|
statementNode.accept(this);
|
||||||
statementNode.accept(this);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
methodVisitor.visitMaxs(0, 0);
|
methodVisitor.visitMaxs(0, 0);
|
||||||
@ -82,8 +81,10 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(MainMethodNode mainMethodNode) {
|
public void visit(MainMethodNode mainMethodNode) {
|
||||||
methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(mainMethodNode.accesModifier),
|
AccessModifierNode accessModifierNode = new AccessModifierNode("");
|
||||||
mainMethodNode.getIdentifier(),
|
accessModifierNode.accessType = EnumAccessModifierNode.PUBLIC_STATIC;
|
||||||
|
methodVisitor = classWriter.visitMethod(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC,
|
||||||
|
"main",
|
||||||
"([Ljava/lang/String;)V",
|
"([Ljava/lang/String;)V",
|
||||||
null,
|
null,
|
||||||
null);
|
null);
|
||||||
@ -105,7 +106,7 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
public void visit(MethodNode methodNode) {
|
public void visit(MethodNode methodNode) {
|
||||||
methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(methodNode.accesModifier),
|
methodVisitor = classWriter.visitMethod(mapper.mapAccessTypeToOpcode(methodNode.accesModifier),
|
||||||
methodNode.getIdentifier(),
|
methodNode.getIdentifier(),
|
||||||
mapper.generateMethodDescriptor((BaseType) methodNode.getType(), methodNode.parameters),
|
mapper.generateMethodDescriptor(methodNode.getType(), methodNode.parameters),
|
||||||
null,
|
null,
|
||||||
null);
|
null);
|
||||||
|
|
||||||
@ -135,12 +136,12 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(CalculationNode calculationNode) {
|
public void visit(CalculationNode calculationNode) {
|
||||||
if (calculationNode.dotExpression != null) {
|
|
||||||
calculationNode.dotExpression.accept(this);
|
|
||||||
}
|
|
||||||
if (calculationNode.calculationExpression != null) {
|
if (calculationNode.calculationExpression != null) {
|
||||||
calculationNode.calculationExpression.accept(this);
|
calculationNode.calculationExpression.accept(this);
|
||||||
}
|
}
|
||||||
|
if (calculationNode.dotExpression != null) {
|
||||||
|
calculationNode.dotExpression.accept(this);
|
||||||
|
}
|
||||||
if (calculationNode.operator != null) {
|
if (calculationNode.operator != null) {
|
||||||
switch (calculationNode.operator) {
|
switch (calculationNode.operator) {
|
||||||
case PLUS:
|
case PLUS:
|
||||||
@ -158,8 +159,8 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
if (dotNode.dotExpression != null) {
|
if (dotNode.dotExpression != null) {
|
||||||
dotNode.dotExpression.accept(this);
|
dotNode.dotExpression.accept(this);
|
||||||
}
|
}
|
||||||
if (dotNode.dotSubstractionExpression != null) {
|
if (dotNode.dotSubtractionExpression != null) {
|
||||||
dotNode.dotSubstractionExpression.accept(this);
|
dotNode.dotSubtractionExpression.accept(this);
|
||||||
}
|
}
|
||||||
if (dotNode.operator != null) {
|
if (dotNode.operator != null) {
|
||||||
switch (dotNode.operator) {
|
switch (dotNode.operator) {
|
||||||
@ -177,17 +178,17 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(DotSubstractionNode dotSubstractionNode) {
|
public void visit(DotSubtractionNode dotSubtractionNode) {
|
||||||
if (dotSubstractionNode.value != null) {
|
if (dotSubtractionNode.value != null) {
|
||||||
dotSubstractionNode.value.accept(this);
|
dotSubtractionNode.value.accept(this);
|
||||||
} else if (dotSubstractionNode.identifier != null) {
|
} else if (dotSubtractionNode.identifier != null) {
|
||||||
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(dotSubstractionNode.identifier));
|
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(dotSubtractionNode.identifier));
|
||||||
} else if (dotSubstractionNode.memberAccess != null) {
|
} else if (dotSubtractionNode.memberAccess != null) {
|
||||||
dotSubstractionNode.memberAccess.accept(this);
|
dotSubtractionNode.memberAccess.accept(this);
|
||||||
} else if (dotSubstractionNode.methodCall != null) {
|
} else if (dotSubtractionNode.methodCall != null) {
|
||||||
dotSubstractionNode.methodCall.accept(this);
|
dotSubtractionNode.methodCall.accept(this);
|
||||||
} else if (dotSubstractionNode.calculationExpression != null) {
|
} else if (dotSubtractionNode.calculationExpression != null) {
|
||||||
dotSubstractionNode.calculationExpression.accept(this);
|
dotSubtractionNode.calculationExpression.accept(this);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -241,7 +242,7 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
nonCalculationNode.unaryExpression.accept(this);
|
nonCalculationNode.unaryExpression.accept(this);
|
||||||
nonCalculationNode.expression.accept(this);
|
nonCalculationNode.expression.accept(this);
|
||||||
if (nonCalculationNode.unaryExpression.getType() instanceof BaseType && nonCalculationNode.expression.getType() instanceof BaseType) {
|
if (nonCalculationNode.unaryExpression.getType() instanceof BaseType && nonCalculationNode.expression.getType() instanceof BaseType) {
|
||||||
methodVisitor.visitJumpInsn(IF_ACMPEQ, labelFalse);
|
methodVisitor.visitJumpInsn(IF_ICMPEQ, labelFalse);
|
||||||
} else {
|
} else {
|
||||||
methodVisitor.visitJumpInsn(IF_ACMPEQ, labelFalse);
|
methodVisitor.visitJumpInsn(IF_ACMPEQ, labelFalse);
|
||||||
}
|
}
|
||||||
@ -266,9 +267,17 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
@Override
|
@Override
|
||||||
public void visit(MemberAccessNode memberAccessNode) {
|
public void visit(MemberAccessNode memberAccessNode) {
|
||||||
// Only used to get, not to put
|
// Only used to get, not to put
|
||||||
if (memberAccessNode.thisExpr) { // Field
|
int localVarIndex = localVariables.indexOf("memberAccessNode.identifier"); // TODO
|
||||||
// methodVisitor.visitFieldInsn(GETFIELD, memberAccessNode.identifiers.get(0), memberAccessNode.identifiers.get(1), );
|
if (localVarIndex >= 0) { // local var object
|
||||||
} else { // Object Attribut
|
methodVisitor.visitVarInsn(ALOAD, localVarIndex);
|
||||||
|
} else { // this field
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (memberAccessNode.getTypeNode() instanceof BaseType) {
|
||||||
|
methodVisitor.visitFieldInsn(GETFIELD, memberAccessNode.identifiers.get(0), memberAccessNode.identifiers.get(1), mapper.getTypeChar((BaseType) memberAccessNode.getTypeNode()));
|
||||||
|
} else if (memberAccessNode.getTypeNode() instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitFieldInsn(GETFIELD, memberAccessNode.identifiers.get(0), memberAccessNode.identifiers.get(1), "L" + ((ReferenceType) memberAccessNode.getTypeNode()).getIdentifier() + ";");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -296,9 +305,8 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
public void visit(UnaryNode unaryNode) {
|
public void visit(UnaryNode unaryNode) {
|
||||||
if (unaryNode.thisExp != null) {
|
if (unaryNode.thisExp != null) {
|
||||||
methodVisitor.visitVarInsn(ALOAD, 0); // this
|
methodVisitor.visitVarInsn(ALOAD, 0); // this
|
||||||
} else if (unaryNode.identifier != null) {
|
|
||||||
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(unaryNode.identifier));
|
|
||||||
} else if (unaryNode.memberAccess != null) {
|
} else if (unaryNode.memberAccess != null) {
|
||||||
|
unaryNode.memberAccess.setTypeNode(unaryNode.getType());
|
||||||
unaryNode.memberAccess.accept(this);
|
unaryNode.memberAccess.accept(this);
|
||||||
} else if (unaryNode.value != null) {
|
} else if (unaryNode.value != null) {
|
||||||
unaryNode.value.accept(this);
|
unaryNode.value.accept(this);
|
||||||
@ -308,15 +316,25 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
unaryNode.statement.accept(this);
|
unaryNode.statement.accept(this);
|
||||||
} else if (unaryNode.expression != null) {
|
} else if (unaryNode.expression != null) {
|
||||||
unaryNode.expression.accept(this);
|
unaryNode.expression.accept(this);
|
||||||
|
} else if (unaryNode.identifier != null) {
|
||||||
|
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(unaryNode.identifier));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// Statements
|
// Statements
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(BlockNode blockNode) {
|
||||||
|
for (IStatementNode statementNode : blockNode.statements) {
|
||||||
|
statementNode.accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(IfElseNode ifElseNode) {
|
public void visit(IfElseNode ifElseNode) {
|
||||||
Label elseLabel = new Label();
|
Label elseLabel = new Label();
|
||||||
|
Label endLabel = new Label();
|
||||||
|
|
||||||
Label[] elseIfLabels = new Label[ifElseNode.elseIfStatements.size()];
|
Label[] elseIfLabels = new Label[ifElseNode.elseIfStatements.size()];
|
||||||
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
|
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
|
||||||
@ -331,9 +349,9 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
// else if statements
|
// else if statements
|
||||||
methodVisitor.visitJumpInsn(IFEQ, elseIfLabels[0]);
|
methodVisitor.visitJumpInsn(IFEQ, elseIfLabels[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
ifElseNode.ifStatement.block.accept(this); // accept if block
|
ifElseNode.ifStatement.block.accept(this); // accept if block
|
||||||
|
|
||||||
Label endLabel = new Label();
|
|
||||||
methodVisitor.visitJumpInsn(GOTO, endLabel);
|
methodVisitor.visitJumpInsn(GOTO, endLabel);
|
||||||
|
|
||||||
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
|
for (int i = 0; i < ifElseNode.elseIfStatements.size(); i++) {
|
||||||
@ -352,6 +370,8 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
if (ifElseNode.elseStatement != null) {
|
if (ifElseNode.elseStatement != null) {
|
||||||
methodVisitor.visitLabel(elseLabel);
|
methodVisitor.visitLabel(elseLabel);
|
||||||
ifElseNode.elseStatement.block.accept(this);
|
ifElseNode.elseStatement.block.accept(this);
|
||||||
|
} else {
|
||||||
|
methodVisitor.visitLabel(elseLabel);
|
||||||
}
|
}
|
||||||
|
|
||||||
methodVisitor.visitLabel(endLabel);
|
methodVisitor.visitLabel(endLabel);
|
||||||
@ -362,22 +382,31 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
if (localVariableDeclarationNode.expression != null) {
|
if (localVariableDeclarationNode.expression != null) {
|
||||||
// Process expression
|
// Process expression
|
||||||
localVariableDeclarationNode.expression.accept(this);
|
localVariableDeclarationNode.expression.accept(this);
|
||||||
// Store result of expression in variable
|
|
||||||
if (localVariables.contains(localVariableDeclarationNode.identifier)) {
|
if (localVariableDeclarationNode.expression instanceof UnaryNode) {
|
||||||
if (localVariableDeclarationNode.type instanceof BaseType) {
|
UnaryNode unaryNode = (UnaryNode) localVariableDeclarationNode.expression;
|
||||||
methodVisitor.visitVarInsn(ISTORE, localVariables.indexOf(localVariableDeclarationNode.identifier));
|
if (unaryNode.statement instanceof IncrementNode) {
|
||||||
} else if (localVariableDeclarationNode.type instanceof ReferenceType) {
|
IncrementNode incrementNode = (IncrementNode) unaryNode.statement;
|
||||||
methodVisitor.visitVarInsn(ASTORE, localVariables.indexOf(localVariableDeclarationNode.identifier));
|
incrementNode.assignableExpression.typeNode = unaryNode.type;
|
||||||
}
|
loadIncrement(incrementNode);
|
||||||
} else {
|
} else if (unaryNode.statement instanceof DecrementNode) {
|
||||||
localVariables.add(localVariableDeclarationNode.identifier);
|
DecrementNode decrementNode = (DecrementNode) unaryNode.statement;
|
||||||
if (localVariableDeclarationNode.type instanceof BaseType) {
|
decrementNode.assignableExpression.typeNode = unaryNode.type;
|
||||||
methodVisitor.visitVarInsn(ISTORE, localVariables.indexOf(localVariableDeclarationNode.identifier));
|
loadDecrement(decrementNode);
|
||||||
} else if (localVariableDeclarationNode.type instanceof ReferenceType) {
|
|
||||||
methodVisitor.visitVarInsn(ASTORE, localVariables.indexOf(localVariableDeclarationNode.identifier));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// add local var to list if not in list
|
||||||
|
if (!localVariables.contains(localVariableDeclarationNode.identifier)) {
|
||||||
|
localVariables.add(localVariableDeclarationNode.identifier);
|
||||||
|
}
|
||||||
|
if (localVariableDeclarationNode.type instanceof BaseType) {
|
||||||
|
methodVisitor.visitVarInsn(ISTORE, localVariables.indexOf(localVariableDeclarationNode.identifier));
|
||||||
|
} else if (localVariableDeclarationNode.type instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitVarInsn(ASTORE, localVariables.indexOf(localVariableDeclarationNode.identifier));
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
|
// Local var declaration
|
||||||
if (!localVariables.contains(localVariableDeclarationNode.identifier)) {
|
if (!localVariables.contains(localVariableDeclarationNode.identifier)) {
|
||||||
localVariables.add(localVariableDeclarationNode.identifier);
|
localVariables.add(localVariableDeclarationNode.identifier);
|
||||||
}
|
}
|
||||||
@ -386,53 +415,212 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(AssignNode assignNode) {
|
public void visit(AssignNode assignNode) {
|
||||||
// Process expression
|
if (assignNode.assignable.memberAccess != null) { // this / object
|
||||||
if (assignNode.expression instanceof IncrementNode) {
|
assignNode.assignable.memberAccess.setTypeNode(assignNode.assignable.typeNode);
|
||||||
IncrementNode incrementNode = (IncrementNode) assignNode.expression;
|
if (assignNode.expression instanceof UnaryNode) {
|
||||||
if (incrementNode.crementType.equals(CrementType.PREFIX)) { // ++i
|
UnaryNode unaryNode = (UnaryNode) assignNode.expression;
|
||||||
methodVisitor.visitIincInsn(localVariables.indexOf(incrementNode.assignableExpression.identifier), 1);
|
if (unaryNode.statement instanceof IncrementNode) {
|
||||||
assign(assignNode);
|
IncrementNode incrementNode = (IncrementNode) unaryNode.statement;
|
||||||
} else if (incrementNode.crementType.equals(CrementType.SUFFIX)) { // Suffix: i++
|
if (incrementNode.crementType.equals(CrementType.PREFIX)) { // ++i
|
||||||
assign(assignNode);
|
incrementNode.accept(this); // crement
|
||||||
methodVisitor.visitIincInsn(localVariables.indexOf(incrementNode.assignableExpression.identifier), 1);
|
fieldOrObjectVarCrementAssign(assignNode); // assign
|
||||||
|
} else { // i++
|
||||||
|
fieldOrObjectVarCrementAssign(assignNode); // assign
|
||||||
|
incrementNode.accept(this); // crement
|
||||||
|
}
|
||||||
|
} else if (unaryNode.statement instanceof DecrementNode) {
|
||||||
|
DecrementNode decrementNode = (DecrementNode) unaryNode.statement;
|
||||||
|
if (decrementNode.crementType.equals(CrementType.PREFIX)) {
|
||||||
|
decrementNode.accept(this); // crement
|
||||||
|
fieldOrObjectVarCrementAssign(assignNode); // assign
|
||||||
|
} else {
|
||||||
|
fieldOrObjectVarCrementAssign(assignNode); // assign
|
||||||
|
decrementNode.accept(this); // crement
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
assignFieldOrObjectVar(assignNode);
|
||||||
}
|
}
|
||||||
} else if (assignNode.expression instanceof DecrementNode) {
|
} else { // local var
|
||||||
DecrementNode decrementNode = (DecrementNode) assignNode.expression;
|
if (assignNode.expression instanceof UnaryNode) {
|
||||||
if (decrementNode.crementType.equals(CrementType.PREFIX)) {
|
UnaryNode unaryNode = (UnaryNode) assignNode.expression;
|
||||||
methodVisitor.visitIincInsn(localVariables.indexOf(decrementNode.assignableExpression.identifier), -1);
|
if (unaryNode.statement instanceof IncrementNode || unaryNode.statement instanceof DecrementNode) {
|
||||||
assign(assignNode);
|
localVarCrementAssign(assignNode);
|
||||||
} else if (decrementNode.crementType.equals(CrementType.SUFFIX)) {
|
}
|
||||||
assign(assignNode);
|
} else {
|
||||||
methodVisitor.visitIincInsn(localVariables.indexOf(decrementNode.assignableExpression.identifier), 1);
|
assignNode.expression.accept(this);
|
||||||
|
assignLocalVar(assignNode);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
assignNode.expression.accept(this);
|
|
||||||
assign(assignNode);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void assign(AssignNode assignNode) {
|
private void loadIncrement(IncrementNode incrementNode) {
|
||||||
if (assignNode.assignable.memberAccess.thisExpr) {
|
AssignableNode assignableNode = incrementNode.assignableExpression;
|
||||||
assignField(assignNode);
|
if (assignableNode.memberAccess != null) {
|
||||||
|
assignableNode.memberAccess.accept(this);
|
||||||
} else {
|
} else {
|
||||||
assignLocalVar(assignNode);
|
if (assignableNode.typeNode instanceof BaseType) {
|
||||||
|
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(assignableNode.identifier));
|
||||||
|
} else if (assignableNode.typeNode instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, localVariables.indexOf(assignableNode.identifier));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void loadDecrement(DecrementNode decrementNode) {
|
||||||
|
AssignableNode assignableNode = decrementNode.assignableExpression;
|
||||||
|
if (assignableNode.memberAccess != null) {
|
||||||
|
assignableNode.memberAccess.accept(this);
|
||||||
|
} else {
|
||||||
|
if (assignableNode.typeNode instanceof BaseType) {
|
||||||
|
methodVisitor.visitVarInsn(ILOAD, localVariables.indexOf(assignableNode.identifier));
|
||||||
|
} else if (assignableNode.typeNode instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, localVariables.indexOf(assignableNode.identifier));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void assignLocalVar(AssignNode assignNode) {
|
private void assignLocalVar(AssignNode assignNode) {
|
||||||
if (assignNode.expression instanceof BaseType) {
|
if (!localVariables.contains(assignNode.assignable.identifier)) {
|
||||||
|
localVariables.add(assignNode.assignable.identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (assignNode.expression.getType() instanceof BaseType) {
|
||||||
methodVisitor.visitVarInsn(ISTORE, localVariables.indexOf(assignNode.assignable.identifier));
|
methodVisitor.visitVarInsn(ISTORE, localVariables.indexOf(assignNode.assignable.identifier));
|
||||||
} else if (assignNode.expression instanceof ReferenceType) {
|
} else if (assignNode.expression.getType() instanceof ReferenceType) {
|
||||||
methodVisitor.visitVarInsn(ASTORE, localVariables.indexOf(assignNode.assignable.identifier));
|
methodVisitor.visitVarInsn(ASTORE, localVariables.indexOf(assignNode.assignable.identifier));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private void assignField(AssignNode assignNode) {
|
private void assignFieldOrObjectVar(AssignNode assignNode) {
|
||||||
if (assignNode.expression instanceof BaseType) {
|
int localVarIndex = localVariables.indexOf(assignNode.assignable.identifier);
|
||||||
|
if (localVarIndex >= 0) { // object
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, localVarIndex);
|
||||||
|
} else if (assignNode.assignable.memberAccess.thisExpr) { // this
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, 0);
|
||||||
|
} else {
|
||||||
|
localVariables.add(assignNode.assignable.identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
assignNode.expression.accept(this);
|
||||||
|
|
||||||
|
if (assignNode.expression.getType() instanceof BaseType) {
|
||||||
methodVisitor.visitFieldInsn(PUTFIELD, assignNode.assignable.memberAccess.identifiers.get(0), assignNode.assignable.memberAccess.identifiers.get(1), mapper.getTypeChar((BaseType) assignNode.expression.getType()));
|
methodVisitor.visitFieldInsn(PUTFIELD, assignNode.assignable.memberAccess.identifiers.get(0), assignNode.assignable.memberAccess.identifiers.get(1), mapper.getTypeChar((BaseType) assignNode.expression.getType()));
|
||||||
} else if (assignNode.expression instanceof ReferenceType) {
|
} else if (assignNode.expression.getType() instanceof ReferenceType) {
|
||||||
ReferenceType referenceType = (ReferenceType) assignNode.expression.getType();
|
ReferenceType referenceType = (ReferenceType) assignNode.expression.getType();
|
||||||
methodVisitor.visitFieldInsn(PUTFIELD, assignNode.assignable.memberAccess.identifiers.get(0), assignNode.assignable.memberAccess.identifiers.get(1), "L"+referenceType.getIdentifier()+";");
|
methodVisitor.visitFieldInsn(PUTFIELD, assignNode.assignable.memberAccess.identifiers.get(0), assignNode.assignable.memberAccess.identifiers.get(1), "L" + referenceType.getIdentifier() + ";");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void localVarCrementAssign(AssignNode assignNode) {
|
||||||
|
UnaryNode unaryNode = (UnaryNode) assignNode.expression;
|
||||||
|
if (unaryNode.statement instanceof IncrementNode) {
|
||||||
|
IncrementNode incrementNode = (IncrementNode) unaryNode.statement;
|
||||||
|
if (incrementNode.crementType.equals(CrementType.PREFIX)) { // ++i
|
||||||
|
incrementNode.accept(this);
|
||||||
|
incrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadIncrement(incrementNode);
|
||||||
|
assignLocalVar(assignNode);
|
||||||
|
} else { // i++
|
||||||
|
incrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadIncrement(incrementNode);
|
||||||
|
assignLocalVar(assignNode);
|
||||||
|
incrementNode.accept(this);
|
||||||
|
}
|
||||||
|
} else if (unaryNode.statement instanceof DecrementNode) {
|
||||||
|
DecrementNode decrementNode = (DecrementNode) unaryNode.statement;
|
||||||
|
if (decrementNode.crementType.equals(CrementType.PREFIX)) {
|
||||||
|
decrementNode.accept(this);
|
||||||
|
decrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadDecrement(decrementNode);
|
||||||
|
assignLocalVar(assignNode);
|
||||||
|
} else {
|
||||||
|
decrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadDecrement(decrementNode);
|
||||||
|
assignLocalVar(assignNode);
|
||||||
|
decrementNode.accept(this);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void fieldOrObjectVarCrementAssign(AssignNode assignNode) {
|
||||||
|
int localVarIndex = localVariables.indexOf(assignNode.assignable.identifier);
|
||||||
|
if (localVarIndex >= 0) { // object
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, localVarIndex);
|
||||||
|
} else if (assignNode.assignable.memberAccess.thisExpr) { // field
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, 0);
|
||||||
|
} else {
|
||||||
|
localVariables.add(assignNode.assignable.identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
UnaryNode unaryNode = (UnaryNode) assignNode.expression;
|
||||||
|
if (unaryNode.statement instanceof IncrementNode) {
|
||||||
|
IncrementNode incrementNode = (IncrementNode) unaryNode.statement;
|
||||||
|
incrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadIncrement((incrementNode));
|
||||||
|
} else if (unaryNode.statement instanceof DecrementNode) {
|
||||||
|
DecrementNode decrementNode = (DecrementNode) unaryNode.statement;
|
||||||
|
decrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadDecrement(decrementNode);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (assignNode.expression.getType() instanceof BaseType) {
|
||||||
|
methodVisitor.visitFieldInsn(PUTFIELD, assignNode.assignable.memberAccess.identifiers.get(0), assignNode.assignable.memberAccess.identifiers.get(1), mapper.getTypeChar((BaseType) assignNode.expression.getType()));
|
||||||
|
} else if (assignNode.expression.getType() instanceof ReferenceType) {
|
||||||
|
ReferenceType referenceType = (ReferenceType) assignNode.expression.getType();
|
||||||
|
methodVisitor.visitFieldInsn(PUTFIELD, assignNode.assignable.memberAccess.identifiers.get(0), assignNode.assignable.memberAccess.identifiers.get(1), "L" + referenceType.getIdentifier() + ";");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(IncrementNode incrementNode) {
|
||||||
|
if (incrementNode.assignableExpression.memberAccess != null) { // Object var / field
|
||||||
|
int localVarIndex = localVariables.indexOf(incrementNode.assignableExpression.identifier);
|
||||||
|
if (localVarIndex >= 0) { // object
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, localVarIndex);
|
||||||
|
} else { // this
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, 0);
|
||||||
|
}
|
||||||
|
if (incrementNode.assignableExpression.memberAccess.getTypeNode() instanceof BaseType) {
|
||||||
|
methodVisitor.visitFieldInsn(GETFIELD, incrementNode.assignableExpression.memberAccess.identifiers.get(0), incrementNode.assignableExpression.memberAccess.identifiers.get(1), mapper.getTypeChar((BaseType) incrementNode.assignableExpression.memberAccess.getTypeNode()));
|
||||||
|
} else if (incrementNode.assignableExpression.memberAccess.getTypeNode() instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitFieldInsn(GETFIELD, incrementNode.assignableExpression.memberAccess.identifiers.get(0), incrementNode.assignableExpression.memberAccess.identifiers.get(1), "L" + (((ReferenceType) incrementNode.assignableExpression.memberAccess.getTypeNode()).getIdentifier() + ";"));
|
||||||
|
}
|
||||||
|
methodVisitor.visitInsn(ICONST_1);
|
||||||
|
methodVisitor.visitInsn(IADD);
|
||||||
|
if (incrementNode.assignableExpression.memberAccess.getTypeNode() instanceof BaseType) {
|
||||||
|
methodVisitor.visitFieldInsn(PUTFIELD, incrementNode.assignableExpression.memberAccess.identifiers.get(0), incrementNode.assignableExpression.memberAccess.identifiers.get(1), mapper.getTypeChar((BaseType) incrementNode.assignableExpression.memberAccess.getTypeNode()));
|
||||||
|
} else if (incrementNode.assignableExpression.memberAccess.getTypeNode() instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitFieldInsn(PUTFIELD, incrementNode.assignableExpression.memberAccess.identifiers.get(0), incrementNode.assignableExpression.memberAccess.identifiers.get(1), "L" + (((ReferenceType) incrementNode.assignableExpression.memberAccess.getTypeNode()).getIdentifier() + ";"));
|
||||||
|
}
|
||||||
|
} else { // local var
|
||||||
|
methodVisitor.visitIincInsn(localVariables.indexOf(incrementNode.assignableExpression.identifier), 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void visit(DecrementNode decrementNode) {
|
||||||
|
if (decrementNode.assignableExpression.memberAccess != null) { // Object var / field
|
||||||
|
int localVarIndex = localVariables.indexOf(decrementNode.assignableExpression.identifier);
|
||||||
|
if (localVarIndex >= 0) { // object
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, localVarIndex);
|
||||||
|
} else { // this
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, 0);
|
||||||
|
}
|
||||||
|
if (decrementNode.assignableExpression.memberAccess.getTypeNode() instanceof BaseType) {
|
||||||
|
methodVisitor.visitFieldInsn(GETFIELD, decrementNode.assignableExpression.memberAccess.identifiers.get(0), decrementNode.assignableExpression.memberAccess.identifiers.get(1), mapper.getTypeChar((BaseType) decrementNode.assignableExpression.memberAccess.getTypeNode()));
|
||||||
|
} else if (decrementNode.assignableExpression.memberAccess.getTypeNode() instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitFieldInsn(GETFIELD, decrementNode.assignableExpression.memberAccess.identifiers.get(0), decrementNode.assignableExpression.memberAccess.identifiers.get(1), "L" + (((ReferenceType) decrementNode.assignableExpression.memberAccess.getTypeNode()).getIdentifier() + ";"));
|
||||||
|
}
|
||||||
|
methodVisitor.visitInsn(ICONST_1);
|
||||||
|
methodVisitor.visitInsn(ISUB);
|
||||||
|
if (decrementNode.assignableExpression.memberAccess.getTypeNode() instanceof BaseType) {
|
||||||
|
methodVisitor.visitFieldInsn(PUTFIELD, decrementNode.assignableExpression.memberAccess.identifiers.get(0), decrementNode.assignableExpression.memberAccess.identifiers.get(1), mapper.getTypeChar((BaseType) decrementNode.assignableExpression.memberAccess.getTypeNode()));
|
||||||
|
} else if (decrementNode.assignableExpression.memberAccess.getTypeNode() instanceof ReferenceType) {
|
||||||
|
methodVisitor.visitFieldInsn(PUTFIELD, decrementNode.assignableExpression.memberAccess.identifiers.get(0), decrementNode.assignableExpression.memberAccess.identifiers.get(1), "L" + (((ReferenceType) decrementNode.assignableExpression.memberAccess.getTypeNode()).getIdentifier() + ";"));
|
||||||
|
}
|
||||||
|
} else { // local var
|
||||||
|
methodVisitor.visitIincInsn(localVariables.indexOf(decrementNode.assignableExpression.identifier), -1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -445,8 +633,7 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
expressionNode.accept(this);
|
expressionNode.accept(this);
|
||||||
parameterNodes.add(new ParameterNode(expressionNode.getType(), ""));
|
parameterNodes.add(new ParameterNode(expressionNode.getType(), ""));
|
||||||
}
|
}
|
||||||
methodVisitor.visitMethodInsn(INVOKESPECIAL, newDeclarationNode.identifier, "<init>", mapper.generateMethodDescriptor(new BaseType(TypeEnum.VOID),parameterNodes), false);
|
methodVisitor.visitMethodInsn(INVOKESPECIAL, newDeclarationNode.identifier, "<init>", mapper.generateMethodDescriptor(new BaseType(TypeEnum.VOID), parameterNodes), false);
|
||||||
localVariables.add(newDeclarationNode.identifier);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -492,6 +679,21 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
} else { // Return something
|
} else { // Return something
|
||||||
// Process expression
|
// Process expression
|
||||||
returnNode.expression.accept(this);
|
returnNode.expression.accept(this);
|
||||||
|
|
||||||
|
if (returnNode.expression instanceof UnaryNode) {
|
||||||
|
UnaryNode unaryNode = (UnaryNode) returnNode.expression;
|
||||||
|
if (unaryNode.statement instanceof IncrementNode) {
|
||||||
|
IncrementNode incrementNode = (IncrementNode) unaryNode.statement;
|
||||||
|
incrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadIncrement(incrementNode);
|
||||||
|
}
|
||||||
|
if (unaryNode.statement instanceof DecrementNode) {
|
||||||
|
DecrementNode decrementNode = (DecrementNode) unaryNode.statement;
|
||||||
|
decrementNode.assignableExpression.typeNode = unaryNode.getType();
|
||||||
|
loadDecrement(decrementNode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Return result of expression
|
// Return result of expression
|
||||||
if (returnNode.expression.getType() instanceof BaseType) {
|
if (returnNode.expression.getType() instanceof BaseType) {
|
||||||
methodVisitor.visitInsn(IRETURN);
|
methodVisitor.visitInsn(IRETURN);
|
||||||
@ -518,19 +720,25 @@ public class MethodCodeGen implements bytecode.visitor.MethodVisitor {
|
|||||||
methodVisitor.visitLabel(endOfLoopLabel);
|
methodVisitor.visitLabel(endOfLoopLabel);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
|
||||||
public void visit(ChainedMethodNode chainedMethodNode) {
|
|
||||||
// TODO: Erstmal abwarten
|
|
||||||
}
|
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public void visit(MethodCallNode methodCallNode) {
|
public void visit(MethodCallNode methodCallNode) {
|
||||||
List<ParameterNode> parameterNodes = new ArrayList<>();
|
List<ParameterNode> parameterNodes = new ArrayList<>();
|
||||||
for(IExpressionNode expressionNode : methodCallNode.parameters) {
|
int localVarIndex = -1;
|
||||||
|
if (methodCallNode.target.memberAccess.identifiers.size() > 1) {
|
||||||
|
localVarIndex = localVariables.indexOf(methodCallNode.target.memberAccess.identifiers.get(1));
|
||||||
|
}
|
||||||
|
if (localVarIndex >= 0) { // local var object
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, localVarIndex);
|
||||||
|
} else { // this field
|
||||||
|
methodVisitor.visitVarInsn(ALOAD, 0);
|
||||||
|
}
|
||||||
|
for (IExpressionNode expressionNode : methodCallNode.parameters) {
|
||||||
expressionNode.accept(this);
|
expressionNode.accept(this);
|
||||||
parameterNodes.add(new ParameterNode(expressionNode.getType(), ""));
|
parameterNodes.add(new ParameterNode(expressionNode.getType(), ""));
|
||||||
}
|
}
|
||||||
// TODO: Klassenname und Returntype
|
if(methodCallNode.type == null) {
|
||||||
//methodVisitor.visitMethodInsn(INVOKEVIRTUAL, classname, methodCallNode.identifier, mapper.generateMethodDescriptor(returntype, parameterNodes), false);
|
methodCallNode.type = new BaseType(TypeEnum.INT);
|
||||||
|
}
|
||||||
|
methodVisitor.visitMethodInsn(INVOKEVIRTUAL, methodCallNode.target.memberAccess.identifiers.get(0), methodCallNode.identifier, mapper.generateMethodDescriptor(methodCallNode.type, parameterNodes), false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -5,6 +5,5 @@ import ast.members.FieldNode;
|
|||||||
|
|
||||||
public interface ClassVisitor {
|
public interface ClassVisitor {
|
||||||
void visit(ClassNode classNode);
|
void visit(ClassNode classNode);
|
||||||
|
|
||||||
void visit(FieldNode fieldNode);
|
void visit(FieldNode fieldNode);
|
||||||
}
|
}
|
||||||
|
@ -8,46 +8,58 @@ import ast.members.ConstructorNode;
|
|||||||
import ast.members.MainMethodNode;
|
import ast.members.MainMethodNode;
|
||||||
import ast.members.MethodNode;
|
import ast.members.MethodNode;
|
||||||
import ast.statementexpressions.AssignNode;
|
import ast.statementexpressions.AssignNode;
|
||||||
import ast.statementexpressions.AssignableNode;
|
|
||||||
import ast.statementexpressions.NewDeclarationNode;
|
import ast.statementexpressions.NewDeclarationNode;
|
||||||
import ast.statementexpressions.crementexpressions.DecrementNode;
|
import ast.statementexpressions.crementexpressions.DecrementNode;
|
||||||
import ast.statementexpressions.crementexpressions.IncrementNode;
|
import ast.statementexpressions.crementexpressions.IncrementNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
|
||||||
import ast.statements.*;
|
import ast.statements.*;
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
|
|
||||||
public interface MethodVisitor {
|
public interface MethodVisitor {
|
||||||
// members
|
// members
|
||||||
void visit(ConstructorNode constructorNode);
|
void visit(ConstructorNode constructorNode);
|
||||||
|
|
||||||
void visit(MethodNode methodNode);
|
void visit(MethodNode methodNode);
|
||||||
|
|
||||||
void visit(MainMethodNode mainMethodNode);
|
void visit(MainMethodNode mainMethodNode);
|
||||||
|
|
||||||
// Binary expressions
|
// Binary expressions
|
||||||
void visit(BinaryNode binaryNode);
|
void visit(BinaryNode binaryNode);
|
||||||
|
|
||||||
void visit(CalculationNode calculationNode);
|
void visit(CalculationNode calculationNode);
|
||||||
|
|
||||||
void visit(DotNode dotNode);
|
void visit(DotNode dotNode);
|
||||||
void visit(DotSubstractionNode dotSubstractionNode);
|
|
||||||
|
void visit(DotSubtractionNode dotSubtractionNode);
|
||||||
|
|
||||||
void visit(NonCalculationNode nonCalculationNode);
|
void visit(NonCalculationNode nonCalculationNode);
|
||||||
|
|
||||||
// Unary expressions
|
// Unary expressions
|
||||||
void visit(MemberAccessNode memberAccessNode);
|
void visit(MemberAccessNode memberAccessNode);
|
||||||
|
|
||||||
void visit(NotNode notExpressionNode);
|
void visit(NotNode notExpressionNode);
|
||||||
|
|
||||||
void visit(UnaryNode unaryExpressionNode);
|
void visit(UnaryNode unaryExpressionNode);
|
||||||
|
|
||||||
// statements
|
// statements
|
||||||
|
void visit(BlockNode blockNode);
|
||||||
void visit(IfElseNode ifElseNode);
|
void visit(IfElseNode ifElseNode);
|
||||||
|
|
||||||
|
void visit(IncrementNode incrementNode);
|
||||||
|
void visit(DecrementNode decrementNode);
|
||||||
|
|
||||||
void visit(LocalVariableDeclarationNode localVariableDeclarationNode);
|
void visit(LocalVariableDeclarationNode localVariableDeclarationNode);
|
||||||
|
|
||||||
void visit(ReturnNode returnNode);
|
void visit(ReturnNode returnNode);
|
||||||
|
|
||||||
void visit(WhileNode whileNode);
|
void visit(WhileNode whileNode);
|
||||||
|
|
||||||
// statement expression
|
// statement expression
|
||||||
void visit(ChainedMethodNode chainedMethodNode);
|
|
||||||
void visit(MethodCallNode methodCallNode);
|
void visit(MethodCallNode methodCallNode);
|
||||||
|
|
||||||
void visit(AssignNode assignNode);
|
void visit(AssignNode assignNode);
|
||||||
|
|
||||||
void visit(NewDeclarationNode newDeclarationNode);
|
void visit(NewDeclarationNode newDeclarationNode);
|
||||||
|
|
||||||
// type
|
// type
|
||||||
|
@ -3,5 +3,5 @@ package bytecode.visitor;
|
|||||||
import ast.ProgramNode;
|
import ast.ProgramNode;
|
||||||
|
|
||||||
public interface ProgramVisitor {
|
public interface ProgramVisitor {
|
||||||
void visit(ProgramNode programNode);
|
void visit(ProgramNode programNode);
|
||||||
}
|
}
|
||||||
|
@ -13,16 +13,16 @@ import org.antlr.v4.runtime.tree.ParseTree;
|
|||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.nio.file.Paths;
|
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> cd .\src\test\ </code>
|
||||||
* <p> <code> make clean compile-raupenpiler </code>
|
* <p> <code> make clean compile-miniCompiler </code>
|
||||||
* <p> Start Raupenpiler using jar:
|
* <p> Start miniCompiler using jar:
|
||||||
* <p> <code> java.exe -jar path_to_jar\JavaCompiler-1.0-jar-with-dependencies.jar 'path_to_input_file.java' 'path_to_output_directory' </code>
|
* <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):
|
* <p> Example (jar needs to be in the target directory, compile with make or mvn package first):
|
||||||
* <code> java.exe -jar .\target\JavaCompiler-1.0-jar-with-dependencies.jar 'src/main/resources/input/CompilerInput.java' 'src/main/resources/output' </code>
|
* <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>
|
||||||
*/
|
*/
|
||||||
public class Main {
|
public class Main {
|
||||||
public static void main(String[] args) throws Exception {
|
public static void main(String[] args) throws Exception {
|
||||||
@ -39,16 +39,14 @@ public class Main {
|
|||||||
System.err.println("Error reading the file: " + e.getMessage());
|
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 {
|
else {
|
||||||
try {
|
try {
|
||||||
CharStream codeCharStream = CharStreams.fromPath(Paths.get("src/main/resources/input/CompilerInput.java"));
|
CharStream codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/input/finalTest/Car.java"));
|
||||||
compileFile(codeCharStream);
|
compileFile(codeCharStream, "src/test/resources/input/finalTest");
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
System.err.println("Error reading the file: " + e.getMessage());
|
System.err.println("Error reading the file: " + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
*/
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -65,7 +63,7 @@ public class Main {
|
|||||||
*/
|
*/
|
||||||
static void compileFile(CharStream inputCharStream, String outputDirectoryPath) {
|
static void compileFile(CharStream inputCharStream, String outputDirectoryPath) {
|
||||||
// Initialize the logger
|
// Initialize the logger
|
||||||
new RaupenLogger();
|
new MiniCompilerLogger();
|
||||||
|
|
||||||
/* ------------------------- Scanner -> tokens ------------------------- */
|
/* ------------------------- Scanner -> tokens ------------------------- */
|
||||||
// Use the SimpleJavaLexer to tokenize the input CharStream
|
// Use the SimpleJavaLexer to tokenize the input CharStream
|
||||||
@ -73,34 +71,46 @@ public class Main {
|
|||||||
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
|
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
|
||||||
tokenStream.fill();
|
tokenStream.fill();
|
||||||
// Log the tokens
|
// Log the tokens
|
||||||
RaupenLogger.logScanner(tokenStream);
|
MiniCompilerLogger.logScanner(tokenStream);
|
||||||
|
|
||||||
/*------------------------- Parser -> Parsetree -------------------------*/
|
/*------------------------- Parser -> Parsetree -------------------------*/
|
||||||
// Use the SimpleJavaParser to parse the tokens and generate a ParseTree
|
// Use the SimpleJavaParser to parse the tokens and generate a ParseTree
|
||||||
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
|
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
|
||||||
ParseTree parseTree = parser.program(); // parse the input
|
ParseTree parseTree = parser.program(); // parse the input
|
||||||
// Log the ParseTree
|
// Log the ParseTree
|
||||||
RaupenLogger.logParser(parseTree, parser);
|
MiniCompilerLogger.logParser(parseTree, parser);
|
||||||
|
|
||||||
/*------------------------- AST builder -> AST -------------------------*/
|
/*------------------------- AST builder -> AST -------------------------*/
|
||||||
// Use the ASTBuilder to visit the ParseTree and generate an Abstract Syntax Tree (AST)
|
// Use the ASTBuilder to visit the ParseTree and generate an Abstract Syntax Tree (AST)
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
ASTBuilder astBuilder = new ASTBuilder();
|
||||||
ASTNode abstractSyntaxTree = astBuilder.visit(parseTree);
|
ASTNode abstractSyntaxTree = astBuilder.visit(parseTree);
|
||||||
// Log the AST
|
// Log the AST
|
||||||
RaupenLogger.logAST(abstractSyntaxTree);
|
MiniCompilerLogger.logAST(abstractSyntaxTree);
|
||||||
|
|
||||||
/*------------------------- Semantic Analyzer -> typed AST -------------------------*/
|
/*------------------------- Semantic Analyzer -> typed AST -------------------------*/
|
||||||
// Use the SemanticAnalyzer to generate a typed AST
|
// Use the SemanticAnalyzer to generate a typed AST
|
||||||
//ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
// Log the typed AST
|
// Log the typed AST
|
||||||
RaupenLogger.logSemanticAnalyzer(abstractSyntaxTree);
|
MiniCompilerLogger.logSemanticAnalyzer(typedAst);
|
||||||
|
|
||||||
|
if(SemanticAnalyzer.errors.isEmpty()){
|
||||||
|
/*------------------------- Bytecode Generator -> Bytecode -------------------------*/
|
||||||
|
// Use the ByteCodeGenerator to generate bytecode from the typed AST and output it to the specified directory
|
||||||
|
|
||||||
|
final boolean genJar = Optional.ofNullable(System.getProperty("genJar")).map(String::toLowerCase).map(Boolean::parseBoolean).orElse(true);
|
||||||
|
final boolean genClass = Optional.ofNullable(System.getProperty("genClass")).map(String::toLowerCase).map(Boolean::parseBoolean).orElse(true);
|
||||||
|
|
||||||
|
ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator(outputDirectoryPath, genJar, genClass);
|
||||||
|
assert typedAst != null;
|
||||||
|
byteCodeGenerator.visit((ProgramNode) typedAst);
|
||||||
|
// Log the bytecode generation
|
||||||
|
MiniCompilerLogger.logBytecodeGenerator();
|
||||||
|
} else {
|
||||||
|
for(Exception exception : SemanticAnalyzer.errors){
|
||||||
|
exception.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/*------------------------- Bytecode Generator -> Bytecode -------------------------*/
|
|
||||||
// Use the ByteCodeGenerator to generate bytecode from the typed AST and output it to the specified directory
|
|
||||||
ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator(outputDirectoryPath, true, true);
|
|
||||||
assert abstractSyntaxTree != null;
|
|
||||||
byteCodeGenerator.visit((ProgramNode) abstractSyntaxTree);
|
|
||||||
// Log the bytecode generation
|
|
||||||
RaupenLogger.logBytecodeGenerator();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -29,11 +29,15 @@ import java.util.logging.*;
|
|||||||
* <code>consoleHandler.setLevel(Level.OFF);</code>
|
* <code>consoleHandler.setLevel(Level.OFF);</code>
|
||||||
* <code>fileHandler.setLevel(Level.ALL);</code>
|
* <code>fileHandler.setLevel(Level.ALL);</code>
|
||||||
*/
|
*/
|
||||||
public class RaupenLogger {
|
|
||||||
|
|
||||||
static Logger logger = Logger.getLogger("RaupenLogs");
|
|
||||||
|
|
||||||
public RaupenLogger() {
|
|
||||||
|
|
||||||
|
public class MiniCompilerLogger {
|
||||||
|
|
||||||
|
static Logger logger = Logger.getLogger("miniCompilerLogs");
|
||||||
|
|
||||||
|
public MiniCompilerLogger() {
|
||||||
// ------------------------- Logging -------------------------
|
// ------------------------- Logging -------------------------
|
||||||
logger.setLevel(Level.ALL);
|
logger.setLevel(Level.ALL);
|
||||||
logger.getParent().getHandlers()[0].setLevel(Level.ALL);
|
logger.getParent().getHandlers()[0].setLevel(Level.ALL);
|
||||||
@ -66,14 +70,16 @@ public class RaupenLogger {
|
|||||||
logger.addHandler(consoleHandler);
|
logger.addHandler(consoleHandler);
|
||||||
|
|
||||||
// Configure file handler
|
// 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
|
// Toggle file logging on/off
|
||||||
fileHandler.setLevel(Level.ALL);
|
fileHandler.setLevel(Level.ALL);
|
||||||
fileHandler.setFormatter(new CustomFormatter());
|
fileHandler.setFormatter(new CustomFormatter());
|
||||||
logger.addHandler(fileHandler);
|
logger.addHandler(fileHandler);
|
||||||
|
|
||||||
} catch (SecurityException | IOException e) {
|
} catch (SecurityException e) {
|
||||||
e.printStackTrace();
|
e.printStackTrace();
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -102,7 +108,7 @@ public class RaupenLogger {
|
|||||||
public static void logAST(ASTNode abstractSyntaxTree) {
|
public static void logAST(ASTNode abstractSyntaxTree) {
|
||||||
// Printing the AST
|
// Printing the AST
|
||||||
logger.info("-------------------- AST builder -> AST --------------------");
|
logger.info("-------------------- AST builder -> AST --------------------");
|
||||||
// logger.info("AST: " + ast.toString());
|
logger.info("Abstract Syntax Tree generated, Startnode:");
|
||||||
logAST(abstractSyntaxTree, 0);
|
logAST(abstractSyntaxTree, 0);
|
||||||
logger.info("\n");
|
logger.info("\n");
|
||||||
}
|
}
|
||||||
@ -110,14 +116,15 @@ public class RaupenLogger {
|
|||||||
public static void logSemanticAnalyzer(ASTNode typedAst) {
|
public static void logSemanticAnalyzer(ASTNode typedAst) {
|
||||||
// Printing the typed AST
|
// Printing the typed AST
|
||||||
logger.info("-------------------- Semantic Analyzer -> typed AST --------------------");
|
logger.info("-------------------- Semantic Analyzer -> typed AST --------------------");
|
||||||
logAST(typedAst, 0);
|
// logAST(typedAst, 0);
|
||||||
|
logger.info("Typed Abstract Syntax Tree generated without errors");
|
||||||
logger.info("\n");
|
logger.info("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void logBytecodeGenerator() {
|
public static void logBytecodeGenerator() {
|
||||||
// Printing the bytecode
|
// Printing the bytecode
|
||||||
logger.info("-------------------- Bytecode Generator -> Bytecode --------------------");
|
logger.info("-------------------- Bytecode Generator -> Bytecode --------------------");
|
||||||
logger.info("Bytecode generated");
|
logger.info("Bytecode generated without errors");
|
||||||
logger.info("\n");
|
logger.info("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -164,7 +171,6 @@ public class RaupenLogger {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: Fix this method
|
|
||||||
public static void logAST(ASTNode abstractSyntaxTree, int indent) {
|
public static void logAST(ASTNode abstractSyntaxTree, int indent) {
|
||||||
if (abstractSyntaxTree == null) {
|
if (abstractSyntaxTree == null) {
|
||||||
logger.severe("AST is null !!!");
|
logger.severe("AST is null !!!");
|
||||||
@ -172,9 +178,9 @@ public class RaupenLogger {
|
|||||||
}
|
}
|
||||||
String indentString = " ".repeat(indent * 2);
|
String indentString = " ".repeat(indent * 2);
|
||||||
logger.info(indentString + abstractSyntaxTree.getClass());
|
logger.info(indentString + abstractSyntaxTree.getClass());
|
||||||
//for (ASTNode child : abstractSyntaxTree.getChildren()) {
|
// for (ASTNode child : abstractSyntaxTree.getChildren()) {
|
||||||
// logAST(child, indent + 1);
|
// logAST(child, indent + 1);
|
||||||
// }
|
// }
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -30,7 +30,18 @@ import parser.generated.*;
|
|||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
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> {
|
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
|
@Override
|
||||||
public ASTNode visitProgram(SimpleJavaParser.ProgramContext ctx) {
|
public ASTNode visitProgram(SimpleJavaParser.ProgramContext ctx) {
|
||||||
ProgramNode program = new ProgramNode();
|
ProgramNode program = new ProgramNode();
|
||||||
@ -40,6 +51,14 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return program;
|
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
|
@Override
|
||||||
public ASTNode visitClassDeclaration(SimpleJavaParser.ClassDeclarationContext ctx) {
|
public ASTNode visitClassDeclaration(SimpleJavaParser.ClassDeclarationContext ctx) {
|
||||||
ClassNode classNode;
|
ClassNode classNode;
|
||||||
@ -71,6 +90,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return classNode;
|
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
|
@Override
|
||||||
public ASTNode visitConstructorDeclaration(SimpleJavaParser.ConstructorDeclarationContext ctx) {
|
public ASTNode visitConstructorDeclaration(SimpleJavaParser.ConstructorDeclarationContext ctx) {
|
||||||
ConstructorNode constructorNode;
|
ConstructorNode constructorNode;
|
||||||
@ -88,6 +114,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return constructorNode;
|
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
|
@Override
|
||||||
public ASTNode visitMethodDeclaration(SimpleJavaParser.MethodDeclarationContext ctx) {
|
public ASTNode visitMethodDeclaration(SimpleJavaParser.MethodDeclarationContext ctx) {
|
||||||
if(ctx.MainMethodDeclaration() != null) {
|
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
|
@Override
|
||||||
public ASTNode visitFieldDeclaration(SimpleJavaParser.FieldDeclarationContext ctx) {
|
public ASTNode visitFieldDeclaration(SimpleJavaParser.FieldDeclarationContext ctx) {
|
||||||
if(ctx.AccessModifier() != null) {
|
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
|
@Override
|
||||||
public ASTNode visitParameter(SimpleJavaParser.ParameterContext ctx) {
|
public ASTNode visitParameter(SimpleJavaParser.ParameterContext ctx) {
|
||||||
return new ParameterNode(createTypeNode(ctx.type().getText()), ctx.Identifier().getText());
|
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
|
@Override
|
||||||
public ASTNode visitStatement(SimpleJavaParser.StatementContext ctx) {
|
public ASTNode visitStatement(SimpleJavaParser.StatementContext ctx) {
|
||||||
if(ctx.returnStatement() != null) {
|
if(ctx.returnStatement() != null) {
|
||||||
@ -175,11 +230,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitReturnStatement(SimpleJavaParser.ReturnStatementContext ctx) {
|
public ASTNode visitReturnStatement(SimpleJavaParser.ReturnStatementContext ctx) {
|
||||||
return new ReturnNode((IExpressionNode) visit(ctx.expression()));
|
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
|
@Override
|
||||||
public ASTNode visitLocalVariableDeclaration(SimpleJavaParser.LocalVariableDeclarationContext ctx) {
|
public ASTNode visitLocalVariableDeclaration(SimpleJavaParser.LocalVariableDeclarationContext ctx) {
|
||||||
if(ctx.Assign() != null) {
|
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
|
@Override
|
||||||
public ASTNode visitBlockStatement(SimpleJavaParser.BlockStatementContext ctx) {
|
public ASTNode visitBlockStatement(SimpleJavaParser.BlockStatementContext ctx) {
|
||||||
BlockNode blockNode = new BlockNode();
|
BlockNode blockNode = new BlockNode();
|
||||||
@ -199,11 +275,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return blockNode;
|
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
|
@Override
|
||||||
public ASTNode visitWhileStatement(SimpleJavaParser.WhileStatementContext ctx) {
|
public ASTNode visitWhileStatement(SimpleJavaParser.WhileStatementContext ctx) {
|
||||||
return new WhileNode((IExpressionNode) visit(ctx.expression()), (BlockNode) visit(ctx.blockStatement()));
|
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
|
@Override
|
||||||
public ASTNode visitDoWhileStatement(SimpleJavaParser.DoWhileStatementContext ctx) {
|
public ASTNode visitDoWhileStatement(SimpleJavaParser.DoWhileStatementContext ctx) {
|
||||||
IExpressionNode condition = (IExpressionNode) visit(ctx.expression());
|
IExpressionNode condition = (IExpressionNode) visit(ctx.expression());
|
||||||
@ -211,12 +301,19 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
|
|
||||||
WhileNode While = new WhileNode(condition, doBlock);
|
WhileNode While = new WhileNode(condition, doBlock);
|
||||||
BlockNode resultBlock = new BlockNode();
|
BlockNode resultBlock = new BlockNode();
|
||||||
resultBlock.addStatement((IStatementNode) doBlock);
|
resultBlock.addStatement(doBlock);
|
||||||
resultBlock.addStatement((IStatementNode) While);
|
resultBlock.addStatement(While);
|
||||||
|
|
||||||
return resultBlock;
|
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
|
@Override
|
||||||
public ASTNode visitForStatement(SimpleJavaParser.ForStatementContext ctx) {
|
public ASTNode visitForStatement(SimpleJavaParser.ForStatementContext ctx) {
|
||||||
List<IStatementNode> statements = new ArrayList<>();
|
List<IStatementNode> statements = new ArrayList<>();
|
||||||
@ -235,15 +332,8 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
|
|
||||||
// Inkrement
|
// Inkrement
|
||||||
IStatementExpressionNode crement = null;
|
IStatementExpressionNode crement = null;
|
||||||
boolean isPrefix = false;
|
|
||||||
if (ctx.statementExpression(i) != null) {
|
if (ctx.statementExpression(i) != null) {
|
||||||
crement = (IStatementExpressionNode) visit(ctx.statementExpression(i));
|
crement = (IStatementExpressionNode) visit(ctx.statementExpression(i));
|
||||||
|
|
||||||
if (crement instanceof IncrementNode) {
|
|
||||||
isPrefix = ((IncrementNode) crement).crementType == CrementType.PREFIX;
|
|
||||||
} else if (crement instanceof DecrementNode) {
|
|
||||||
isPrefix = ((DecrementNode) crement).crementType == CrementType.PREFIX;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
BlockNode forBlock = (BlockNode) visit(ctx.blockStatement());
|
BlockNode forBlock = (BlockNode) visit(ctx.blockStatement());
|
||||||
@ -251,19 +341,14 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
// While-Schleife
|
// While-Schleife
|
||||||
BlockNode whileBody = new BlockNode();
|
BlockNode whileBody = new BlockNode();
|
||||||
|
|
||||||
// Prä-Inkrement: Das Inkrement kommt vor dem Block
|
|
||||||
if (crement != null && isPrefix) {
|
|
||||||
whileBody.addStatement((IStatementNode) crement);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Block Statements der For-Schleife in den While-Block kopieren
|
// Block Statements der For-Schleife in den While-Block kopieren
|
||||||
for (IStatementNode statement : forBlock.statements) {
|
for (IStatementNode statement : forBlock.statements) {
|
||||||
whileBody.addStatement(statement);
|
whileBody.addStatement(statement);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Post-Inkrement: Das Inkrement kommt nach dem Block
|
// Post-Inkrement: Das Inkrement kommt nach dem Block
|
||||||
if (crement != null && !isPrefix) {
|
if (crement != null) {
|
||||||
whileBody.addStatement((IStatementNode) crement);
|
whileBody.addStatement(crement);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Bedingung der While-Schleife
|
// Bedingung der While-Schleife
|
||||||
@ -273,16 +358,28 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
|
|
||||||
BlockNode resultBlock = new BlockNode();
|
BlockNode resultBlock = new BlockNode();
|
||||||
for (IStatementNode statement : statements) {
|
for (IStatementNode statement : statements) {
|
||||||
resultBlock.addStatement((IStatementNode) statement);
|
resultBlock.addStatement(statement);
|
||||||
}
|
}
|
||||||
|
|
||||||
return resultBlock;
|
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
|
@Override
|
||||||
public ASTNode visitIfElseStatement(SimpleJavaParser.IfElseStatementContext ctx) {
|
public ASTNode visitIfElseStatement(SimpleJavaParser.IfElseStatementContext ctx) {
|
||||||
IfElseNode ifElseStatementNode = new IfElseNode((IfNode) visit(ctx.ifStatement()),
|
IfElseNode ifElseStatementNode;
|
||||||
(ElseNode) visit(ctx.elseStatement()));
|
if(ctx.elseStatement() != null) {
|
||||||
|
ifElseStatementNode = new IfElseNode((IfNode) visit(ctx.ifStatement()),
|
||||||
|
(ElseNode) visit(ctx.elseStatement()));
|
||||||
|
} else {
|
||||||
|
ifElseStatementNode = new IfElseNode((IfNode) visit(ctx.ifStatement()), null);
|
||||||
|
}
|
||||||
|
|
||||||
for (SimpleJavaParser.ElseIfStatementContext elseIf : ctx.elseIfStatement()){
|
for (SimpleJavaParser.ElseIfStatementContext elseIf : ctx.elseIfStatement()){
|
||||||
ifElseStatementNode.addElseIfStatement(((IfNode) visit(elseIf)));
|
ifElseStatementNode.addElseIfStatement(((IfNode) visit(elseIf)));
|
||||||
@ -291,21 +388,49 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return ifElseStatementNode;
|
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
|
@Override
|
||||||
public ASTNode visitIfStatement(SimpleJavaParser.IfStatementContext ctx) {
|
public ASTNode visitIfStatement(SimpleJavaParser.IfStatementContext ctx) {
|
||||||
return new IfNode((IExpressionNode) visit(ctx.expression()), (BlockNode) visit(ctx.blockStatement()));
|
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
|
@Override
|
||||||
public ASTNode visitElseIfStatement(SimpleJavaParser.ElseIfStatementContext ctx) {
|
public ASTNode visitElseIfStatement(SimpleJavaParser.ElseIfStatementContext ctx) {
|
||||||
return new IfNode((IExpressionNode) visit(ctx.expression()), (BlockNode) visit(ctx.blockStatement()));
|
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
|
@Override
|
||||||
public ASTNode visitElseStatement(SimpleJavaParser.ElseStatementContext ctx) {
|
public ASTNode visitElseStatement(SimpleJavaParser.ElseStatementContext ctx) {
|
||||||
return new ElseNode((BlockNode) visit(ctx.blockStatement()));
|
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
|
@Override
|
||||||
public ASTNode visitStatementExpression(SimpleJavaParser.StatementExpressionContext ctx) {
|
public ASTNode visitStatementExpression(SimpleJavaParser.StatementExpressionContext ctx) {
|
||||||
if(ctx.assign() != null) {
|
if(ctx.assign() != null) {
|
||||||
@ -320,6 +445,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitSwitchStatement(SimpleJavaParser.SwitchStatementContext ctx) {
|
public ASTNode visitSwitchStatement(SimpleJavaParser.SwitchStatementContext ctx) {
|
||||||
UnaryNode switchExpression = (UnaryNode) visit(ctx.expression());
|
UnaryNode switchExpression = (UnaryNode) visit(ctx.expression());
|
||||||
@ -363,11 +495,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return ifElseNode;
|
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
|
@Override
|
||||||
public ASTNode visitAssign(SimpleJavaParser.AssignContext ctx) {
|
public ASTNode visitAssign(SimpleJavaParser.AssignContext ctx) {
|
||||||
return new AssignNode((AssignableNode) visit(ctx.assignableExpression()), (IExpressionNode) visit(ctx.expression()));
|
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
|
@Override
|
||||||
public ASTNode visitNewDeclaration(SimpleJavaParser.NewDeclarationContext ctx) {
|
public ASTNode visitNewDeclaration(SimpleJavaParser.NewDeclarationContext ctx) {
|
||||||
NewDeclarationNode newDeclarationNode = new NewDeclarationNode(ctx.Identifier().getText());
|
NewDeclarationNode newDeclarationNode = new NewDeclarationNode(ctx.Identifier().getText());
|
||||||
@ -377,6 +523,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return newDeclarationNode;
|
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
|
@Override
|
||||||
public ASTNode visitMethodCall(SimpleJavaParser.MethodCallContext ctx) {
|
public ASTNode visitMethodCall(SimpleJavaParser.MethodCallContext ctx) {
|
||||||
MethodCallNode methodCallStatementExpressionNode;
|
MethodCallNode methodCallStatementExpressionNode;
|
||||||
@ -394,6 +547,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return methodCallStatementExpressionNode;
|
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
|
@Override
|
||||||
public ASTNode visitTarget(SimpleJavaParser.TargetContext ctx) {
|
public ASTNode visitTarget(SimpleJavaParser.TargetContext ctx) {
|
||||||
if(ctx.This() != null) {
|
if(ctx.This() != null) {
|
||||||
@ -408,6 +568,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitChainedMethod(SimpleJavaParser.ChainedMethodContext ctx) {
|
public ASTNode visitChainedMethod(SimpleJavaParser.ChainedMethodContext ctx) {
|
||||||
ChainedMethodNode chainedMethodNode = new ChainedMethodNode(ctx.Identifier().getText());
|
ChainedMethodNode chainedMethodNode = new ChainedMethodNode(ctx.Identifier().getText());
|
||||||
@ -417,6 +584,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return chainedMethodNode;
|
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
|
@Override
|
||||||
public ASTNode visitCrementExpression(SimpleJavaParser.CrementExpressionContext ctx) {
|
public ASTNode visitCrementExpression(SimpleJavaParser.CrementExpressionContext ctx) {
|
||||||
if(ctx.incrementExpression() != null) {
|
if(ctx.incrementExpression() != null) {
|
||||||
@ -427,6 +601,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitIncrementExpression(SimpleJavaParser.IncrementExpressionContext ctx) {
|
public ASTNode visitIncrementExpression(SimpleJavaParser.IncrementExpressionContext ctx) {
|
||||||
if(ctx.prefixIncrementExpression() != null) {
|
if(ctx.prefixIncrementExpression() != null) {
|
||||||
@ -437,16 +618,35 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitPrefixIncrementExpression(SimpleJavaParser.PrefixIncrementExpressionContext ctx) {
|
public ASTNode visitPrefixIncrementExpression(SimpleJavaParser.PrefixIncrementExpressionContext ctx) {
|
||||||
return new IncrementNode(CrementType.PREFIX, (AssignableNode) visit(ctx.assignableExpression()));
|
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
|
@Override
|
||||||
public ASTNode visitSuffixIncrementExpression(SimpleJavaParser.SuffixIncrementExpressionContext ctx) {
|
public ASTNode visitSuffixIncrementExpression(SimpleJavaParser.SuffixIncrementExpressionContext ctx) {
|
||||||
return new IncrementNode(CrementType.SUFFIX, (AssignableNode) visit(ctx.assignableExpression()));
|
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
|
@Override
|
||||||
public ASTNode visitDecrementExpression(SimpleJavaParser.DecrementExpressionContext ctx) {
|
public ASTNode visitDecrementExpression(SimpleJavaParser.DecrementExpressionContext ctx) {
|
||||||
if(ctx.prefixDecrementExpression() != null) {
|
if(ctx.prefixDecrementExpression() != null) {
|
||||||
@ -457,16 +657,35 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitPrefixDecrementExpression(SimpleJavaParser.PrefixDecrementExpressionContext ctx) {
|
public ASTNode visitPrefixDecrementExpression(SimpleJavaParser.PrefixDecrementExpressionContext ctx) {
|
||||||
return new DecrementNode(CrementType.PREFIX, (AssignableNode) visit(ctx.assignableExpression()));
|
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
|
@Override
|
||||||
public ASTNode visitSuffixDecrementExpression(SimpleJavaParser.SuffixDecrementExpressionContext ctx) {
|
public ASTNode visitSuffixDecrementExpression(SimpleJavaParser.SuffixDecrementExpressionContext ctx) {
|
||||||
return new DecrementNode(CrementType.SUFFIX, (AssignableNode) visit(ctx.assignableExpression()));
|
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
|
@Override
|
||||||
public ASTNode visitExpression(SimpleJavaParser.ExpressionContext ctx) {
|
public ASTNode visitExpression(SimpleJavaParser.ExpressionContext ctx) {
|
||||||
if(ctx.unaryExpression() != null) {
|
if(ctx.unaryExpression() != null) {
|
||||||
@ -477,6 +696,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitUnaryExpression(SimpleJavaParser.UnaryExpressionContext ctx) {
|
public ASTNode visitUnaryExpression(SimpleJavaParser.UnaryExpressionContext ctx) {
|
||||||
if(ctx.This() != null) {
|
if(ctx.This() != null) {
|
||||||
@ -497,6 +723,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitMemberAccess(SimpleJavaParser.MemberAccessContext ctx) {
|
public ASTNode visitMemberAccess(SimpleJavaParser.MemberAccessContext ctx) {
|
||||||
MemberAccessNode memberAccessNode;
|
MemberAccessNode memberAccessNode;
|
||||||
@ -511,6 +744,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return memberAccessNode;
|
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
|
@Override
|
||||||
public ASTNode visitValue(SimpleJavaParser.ValueContext ctx) {
|
public ASTNode visitValue(SimpleJavaParser.ValueContext ctx) {
|
||||||
if(ctx.IntValue() != null) {
|
if(ctx.IntValue() != null) {
|
||||||
@ -525,12 +765,25 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitNotExpression(SimpleJavaParser.NotExpressionContext ctx) {
|
public ASTNode visitNotExpression(SimpleJavaParser.NotExpressionContext ctx) {
|
||||||
return new NotNode((IExpressionNode) visitExpression(ctx.expression()));
|
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
|
@Override
|
||||||
public ASTNode visitBinaryExpression(SimpleJavaParser.BinaryExpressionContext ctx) {
|
public ASTNode visitBinaryExpression(SimpleJavaParser.BinaryExpressionContext ctx) {
|
||||||
if(ctx.calculationExpression() != null) {
|
if(ctx.calculationExpression() != null) {
|
||||||
@ -541,6 +794,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitCalculationExpression(SimpleJavaParser.CalculationExpressionContext ctx) {
|
public ASTNode visitCalculationExpression(SimpleJavaParser.CalculationExpressionContext ctx) {
|
||||||
if(ctx.calculationExpression() != null) {
|
if(ctx.calculationExpression() != null) {
|
||||||
@ -551,35 +811,69 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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
|
@Override
|
||||||
public ASTNode visitDotExpression(SimpleJavaParser.DotExpressionContext ctx) {
|
public ASTNode visitDotExpression(SimpleJavaParser.DotExpressionContext ctx) {
|
||||||
if(ctx.dotExpression() != null) {
|
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) {
|
} else if(ctx.dotSubtractionExpression() != null) {
|
||||||
return new DotNode((DotSubstractionNode) visit(ctx.dotSubtractionExpression()));
|
return new DotNode((DotSubtractionNode) visit(ctx.dotSubtractionExpression()));
|
||||||
}
|
}
|
||||||
return null;
|
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
|
||||||
|
*//**
|
||||||
|
* Creates an ITypeNode based on the type identifier.
|
||||||
|
* It handles basic types and reference types.
|
||||||
|
*
|
||||||
|
* @param identifier the type identifier
|
||||||
|
* @return the type node
|
||||||
|
*/
|
||||||
@Override
|
@Override
|
||||||
public ASTNode visitDotSubtractionExpression(SimpleJavaParser.DotSubtractionExpressionContext ctx) {
|
public ASTNode visitDotSubtractionExpression(SimpleJavaParser.DotSubtractionExpressionContext ctx) {
|
||||||
if(ctx.IntValue() != null) {
|
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) {
|
} else if(ctx.Identifier() != null) {
|
||||||
return new DotSubstractionNode(ctx.Identifier().getText());
|
return new DotSubtractionNode(ctx.Identifier().getText());
|
||||||
} else if(ctx.memberAccess() != null) {
|
} 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) {
|
} 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;
|
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
|
@Override
|
||||||
public ASTNode visitNonCalculationExpression(SimpleJavaParser.NonCalculationExpressionContext ctx) {
|
public ASTNode visitNonCalculationExpression(SimpleJavaParser.NonCalculationExpressionContext ctx) {
|
||||||
return new NonCalculationNode((UnaryNode) visit(ctx.unaryExpression()), ctx.nonCalculationOperator().getText(), (IExpressionNode) visit(ctx.expression()));
|
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
|
@Override
|
||||||
public ASTNode visitAssignableExpression(SimpleJavaParser.AssignableExpressionContext ctx) {
|
public ASTNode visitAssignableExpression(SimpleJavaParser.AssignableExpressionContext ctx) {
|
||||||
if(ctx.Identifier() != null) {
|
if(ctx.Identifier() != null) {
|
||||||
@ -590,6 +884,13 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
return null;
|
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){
|
public ITypeNode createTypeNode(String identifier){
|
||||||
return switch (identifier) {
|
return switch (identifier) {
|
||||||
case "int" -> new BaseType(TypeEnum.INT);
|
case "int" -> new BaseType(TypeEnum.INT);
|
||||||
@ -599,6 +900,4 @@ public class ASTBuilder extends SimpleJavaBaseVisitor<ASTNode> {
|
|||||||
default -> new ReferenceType(identifier);
|
default -> new ReferenceType(identifier);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
File diff suppressed because one or more lines are too long
@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/janni/Desktop/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
||||||
package parser.generated;
|
package parser.generated;
|
||||||
|
|
||||||
import org.antlr.v4.runtime.ParserRuleContext;
|
import org.antlr.v4.runtime.ParserRuleContext;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/janni/Desktop/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
||||||
package parser.generated;
|
package parser.generated;
|
||||||
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
|
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/janni/Desktop/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
||||||
package parser.generated;
|
package parser.generated;
|
||||||
import org.antlr.v4.runtime.Lexer;
|
import org.antlr.v4.runtime.Lexer;
|
||||||
import org.antlr.v4.runtime.CharStream;
|
import org.antlr.v4.runtime.CharStream;
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/janni/Desktop/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
||||||
package parser.generated;
|
package parser.generated;
|
||||||
import org.antlr.v4.runtime.tree.ParseTreeListener;
|
import org.antlr.v4.runtime.tree.ParseTreeListener;
|
||||||
|
|
||||||
|
File diff suppressed because it is too large
Load Diff
@ -1,4 +1,4 @@
|
|||||||
// Generated from C:/Users/janni/Desktop/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
// Generated from C:/Users/Maxi/Documents/DHBW/Compilerbau/NichtHaskell2.0/src/main/java/parser/grammar/SimpleJava.g4 by ANTLR 4.13.1
|
||||||
package parser.generated;
|
package parser.generated;
|
||||||
import org.antlr.v4.runtime.tree.ParseTreeVisitor;
|
import org.antlr.v4.runtime.tree.ParseTreeVisitor;
|
||||||
|
|
||||||
|
@ -1,18 +1,18 @@
|
|||||||
grammar SimpleJava;
|
grammar SimpleJava;
|
||||||
|
|
||||||
// Programm-Konstrukte
|
// Programm-Konstrukte
|
||||||
program: classDeclaration+;
|
program: classDeclaration+; // Ein Programm besteht aus einer oder mehreren Klassendeklarationen
|
||||||
|
|
||||||
classDeclaration: AccessModifier? 'class' Identifier OpenCurlyBracket memberDeclaration* ClosedCurlyBracket;
|
classDeclaration: AccessModifier? 'class' Identifier OpenCurlyBracket memberDeclaration* ClosedCurlyBracket; // Deklariert eine Klasse mit optionalem Zugriffsmodifikator und mehreren Mitgliedern
|
||||||
memberDeclaration: constructorDeclaration | fieldDeclaration | methodDeclaration;
|
memberDeclaration: constructorDeclaration | fieldDeclaration | methodDeclaration; // Ein Mitglied kann ein Konstruktor, ein Feld oder eine Methode sein
|
||||||
|
|
||||||
constructorDeclaration: AccessModifier? Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement;
|
constructorDeclaration: AccessModifier? Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement; // Deklariert einen Konstruktor
|
||||||
fieldDeclaration: AccessModifier? type Identifier (Assign expression)? Semicolon;
|
fieldDeclaration: AccessModifier? type Identifier (Assign expression)? Semicolon; // Deklariert ein Feld mit optionaler Initialisierung
|
||||||
methodDeclaration: MainMethodDeclaration blockStatement | AccessModifier? (type | Void) Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement;
|
methodDeclaration: MainMethodDeclaration blockStatement | AccessModifier? (type | Void) Identifier OpenRoundBracket parameterList? ClosedRoundBracket blockStatement; // Deklariert eine Methode
|
||||||
|
|
||||||
parameterList: parameter (Comma parameter)*;
|
parameterList: parameter (Comma parameter)*; // Parameterliste für Methoden und Konstruktoren
|
||||||
parameter: type Identifier;
|
parameter: type Identifier; // Ein einzelner Parameter mit Typ und Bezeichner
|
||||||
argumentList: (expression (Comma expression)*)?;
|
argumentList: (expression (Comma expression)*)?; // Argumentliste für Methodenaufrufe
|
||||||
|
|
||||||
// Anweisungen
|
// Anweisungen
|
||||||
statement: returnStatement Semicolon
|
statement: returnStatement Semicolon
|
||||||
@ -23,32 +23,32 @@ statement: returnStatement Semicolon
|
|||||||
| forStatement
|
| forStatement
|
||||||
| ifElseStatement
|
| ifElseStatement
|
||||||
| switchStatement
|
| switchStatement
|
||||||
| statementExpression Semicolon;
|
| statementExpression Semicolon; // Verschiedene Arten von Anweisungen
|
||||||
|
|
||||||
blockStatement: OpenCurlyBracket statement* ClosedCurlyBracket;
|
blockStatement: OpenCurlyBracket statement* ClosedCurlyBracket; // Ein Block von Anweisungen
|
||||||
|
|
||||||
returnStatement: Return (expression)?;
|
returnStatement: Return (expression)?; // Rückgabe-Anweisung
|
||||||
localVariableDeclaration: type Identifier (Assign expression)?;
|
localVariableDeclaration: type Identifier (Assign expression)?; // Deklaration einer lokalen Variable
|
||||||
|
|
||||||
whileStatement: While OpenRoundBracket expression ClosedRoundBracket blockStatement;
|
whileStatement: While OpenRoundBracket expression ClosedRoundBracket blockStatement; // While-Schleife
|
||||||
doWhileStatement: Do blockStatement While OpenRoundBracket expression ClosedRoundBracket Semicolon;
|
doWhileStatement: Do blockStatement While OpenRoundBracket expression ClosedRoundBracket Semicolon; // Do-While-Schleife
|
||||||
forStatement: For OpenRoundBracket (statementExpression | localVariableDeclaration) Semicolon (expression)? Semicolon (statementExpression)? ClosedRoundBracket blockStatement;
|
forStatement: For OpenRoundBracket (statementExpression | localVariableDeclaration) Semicolon (expression)? Semicolon (statementExpression)? ClosedRoundBracket blockStatement; // For-Schleife
|
||||||
|
|
||||||
ifElseStatement: ifStatement elseIfStatement* elseStatement?;
|
ifElseStatement: ifStatement elseIfStatement* elseStatement?; // If-Else-Bedingung
|
||||||
ifStatement: If OpenRoundBracket expression ClosedRoundBracket blockStatement;
|
ifStatement: If OpenRoundBracket expression ClosedRoundBracket blockStatement; // If-Teil der Bedingung
|
||||||
elseIfStatement: Else If OpenRoundBracket expression ClosedRoundBracket blockStatement;
|
elseIfStatement: Else If OpenRoundBracket expression ClosedRoundBracket blockStatement; // Else-If-Teil der Bedingung
|
||||||
elseStatement: Else blockStatement;
|
elseStatement: Else blockStatement; // Else-Teil der Bedingung
|
||||||
|
|
||||||
switchStatement: Switch OpenRoundBracket expression ClosedRoundBracket OpenCurlyBracket caseStatement+ defaultStatement? ClosedCurlyBracket;
|
switchStatement: Switch OpenRoundBracket expression ClosedRoundBracket OpenCurlyBracket caseStatement+ defaultStatement? ClosedCurlyBracket; // Switch-Anweisung
|
||||||
caseStatement: Case value Colon statement*;
|
caseStatement: Case value Colon statement*; // Ein Case-Teil einer Switch-Anweisung
|
||||||
defaultStatement: Default Colon statement*;
|
defaultStatement: Default Colon statement*; // Default-Teil einer Switch-Anweisung
|
||||||
|
|
||||||
statementExpression: assign | newDeclaration | methodCall | crementExpression;
|
statementExpression: assign | newDeclaration | methodCall | crementExpression; // Ausdruck innerhalb einer Anweisung
|
||||||
assign: assignableExpression Assign expression;
|
assign: assignableExpression Assign expression; // Zuweisung
|
||||||
newDeclaration: New Identifier OpenRoundBracket argumentList ClosedRoundBracket;
|
newDeclaration: New Identifier OpenRoundBracket argumentList ClosedRoundBracket; // Instanziierung eines neuen Objekts
|
||||||
|
|
||||||
// Ausdrücke
|
// Ausdrücke
|
||||||
expression: unaryExpression | binaryExpression;
|
expression: unaryExpression | binaryExpression; // Ein Ausdruck kann unär oder binär sein
|
||||||
|
|
||||||
unaryExpression: This
|
unaryExpression: This
|
||||||
| Identifier
|
| Identifier
|
||||||
@ -56,97 +56,97 @@ unaryExpression: This
|
|||||||
| value
|
| value
|
||||||
| notExpression
|
| notExpression
|
||||||
| statementExpression
|
| 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;
|
incrementExpression: prefixIncrementExpression | suffixIncrementExpression;
|
||||||
prefixIncrementExpression: '++' assignableExpression;
|
prefixIncrementExpression: '++' assignableExpression; // Präfix-Inkrement
|
||||||
suffixIncrementExpression: assignableExpression '++';
|
suffixIncrementExpression: assignableExpression '++'; // Suffix-Inkrement
|
||||||
|
|
||||||
decrementExpression: prefixDecrementExpression | suffixDecrementExpression;
|
decrementExpression: prefixDecrementExpression | suffixDecrementExpression; // Dekrement-Ausdrücke
|
||||||
prefixDecrementExpression: '--' assignableExpression;
|
prefixDecrementExpression: '--' assignableExpression; // Präfix-Dekrement
|
||||||
suffixDecrementExpression: assignableExpression '--';
|
suffixDecrementExpression: assignableExpression '--'; // Suffix-Dekrement
|
||||||
|
|
||||||
assignableExpression: Identifier | memberAccess;
|
assignableExpression: Identifier | memberAccess; // Zuweisbarer Ausdruck
|
||||||
|
|
||||||
memberAccess: This Dot Identifier
|
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
|
calculationExpression: calculationExpression LineOperator dotExpression
|
||||||
| dotExpression;
|
| dotExpression; // Berechnungsausdrücke
|
||||||
|
|
||||||
dotExpression: dotExpression DotOperator dotSubtractionExpression
|
dotExpression: dotExpression DotOperator dotSubtractionExpression
|
||||||
| dotSubtractionExpression;
|
| dotSubtractionExpression; // Punktoperationen
|
||||||
|
|
||||||
dotSubtractionExpression: IntValue
|
dotSubtractionExpression: IntValue
|
||||||
| Identifier
|
| Identifier
|
||||||
| memberAccess
|
| memberAccess
|
||||||
| methodCall OpenRoundBracket calculationExpression ClosedRoundBracket;
|
| methodCall OpenRoundBracket calculationExpression ClosedRoundBracket; // Punkt-Subtraktionsausdrücke
|
||||||
|
|
||||||
nonCalculationExpression: unaryExpression nonCalculationOperator expression;
|
nonCalculationExpression: unaryExpression nonCalculationOperator expression; // Nicht-Berechnungsausdrücke
|
||||||
|
|
||||||
// Methodenaufrufe
|
// Methodenaufrufe
|
||||||
methodCall: target? chainedMethod* Identifier OpenRoundBracket argumentList ClosedRoundBracket;
|
methodCall: target? chainedMethod* Identifier OpenRoundBracket argumentList ClosedRoundBracket; // Methodenaufruf
|
||||||
target: (This | memberAccess | newDeclaration | Identifier) Dot;
|
target: (This | memberAccess | newDeclaration | Identifier) Dot; // Ziel eines Methodenaufrufs
|
||||||
chainedMethod: Identifier OpenRoundBracket argumentList ClosedRoundBracket Dot;
|
chainedMethod: Identifier OpenRoundBracket argumentList ClosedRoundBracket Dot; // Verkettete Methode
|
||||||
|
|
||||||
// Typen
|
// Typen
|
||||||
type: Int
|
type: Int
|
||||||
| Boolean
|
| Boolean
|
||||||
| Char
|
| Char
|
||||||
| Identifier;
|
| Identifier; // Datentypen
|
||||||
|
|
||||||
Void: 'void';
|
Void: 'void'; // Void-Typ
|
||||||
Boolean: 'boolean';
|
Boolean: 'boolean'; // Boolean-Typ
|
||||||
Char: 'char';
|
Char: 'char'; // Char-Typ
|
||||||
Int: 'int';
|
Int: 'int'; // Integer-Typ
|
||||||
|
|
||||||
value: IntValue
|
value: IntValue
|
||||||
| BooleanValue
|
| BooleanValue
|
||||||
| CharValue
|
| CharValue
|
||||||
| NullValue;
|
| NullValue; // Werte
|
||||||
|
|
||||||
// Zugriffsmodifikatoren
|
// Zugriffsmodifikatoren
|
||||||
AccessModifier: 'public' | 'private' | 'public static' | 'private static';
|
AccessModifier: 'public' | 'private' | 'public static' | 'private static'; // Zugriffsmodifikatoren
|
||||||
MainMethodDeclaration: 'public static void main(String[] args)';
|
MainMethodDeclaration: 'public static void main(String[] args)'; // Hauptmethoden-Deklaration
|
||||||
|
|
||||||
// Operatoren
|
// Operatoren
|
||||||
nonCalculationOperator: LogicalOperator | ComparisonOperator;
|
nonCalculationOperator: LogicalOperator | ComparisonOperator; // Nicht-Berechnungsoperatoren
|
||||||
|
|
||||||
DotOperator: Mult | Div | Modulo;
|
DotOperator: Mult | Div | Modulo; // Punktoperatoren
|
||||||
LineOperator: Plus | Minus;
|
LineOperator: Plus | Minus; // Linienoperatoren
|
||||||
ComparisonOperator: Greater | Less | GreaterEqual | LessEqual | Equal | NotEqual;
|
ComparisonOperator: Greater | Less | GreaterEqual | LessEqual | Equal | NotEqual; // Vergleichsoperatoren
|
||||||
LogicalOperator: And | Or;
|
LogicalOperator: And | Or; // Logische Operatoren
|
||||||
|
|
||||||
Assign: '=';
|
Assign: '='; // Zuweisungsoperator
|
||||||
Plus: '+';
|
Plus: '+'; // Plus-Operator
|
||||||
Minus: '-';
|
Minus: '-'; // Minus-Operator
|
||||||
Mult: '*';
|
Mult: '*'; // Multiplikationsoperator
|
||||||
Modulo: '%';
|
Modulo: '%'; // Modulo-Operator
|
||||||
Div: '/';
|
Div: '/'; // Divisionsoperator
|
||||||
Greater: '>';
|
Greater: '>'; // Größer-Operator
|
||||||
Less: '<';
|
Less: '<'; // Kleiner-Operator
|
||||||
GreaterEqual: '>=';
|
GreaterEqual: '>='; // Größer-Gleich-Operator
|
||||||
LessEqual: '<=';
|
LessEqual: '<='; // Kleiner-Gleich-Operator
|
||||||
Equal: '==';
|
Equal: '=='; // Gleichheitsoperator
|
||||||
NotEqual: '!=';
|
NotEqual: '!='; // Ungleichheitsoperator
|
||||||
Not: '!';
|
Not: '!'; // Nicht-Operator
|
||||||
And: '&&';
|
And: '&&'; // Und-Operator
|
||||||
Or: '||';
|
Or: '||'; // Oder-Operator
|
||||||
|
|
||||||
// Symbole
|
// Symbole
|
||||||
Dot: '.';
|
Dot: '.'; // Punkt-Symbol
|
||||||
OpenRoundBracket: '(';
|
OpenRoundBracket: '('; // Öffnende runde Klammer
|
||||||
ClosedRoundBracket: ')';
|
ClosedRoundBracket: ')'; // Schließende runde Klammer
|
||||||
OpenCurlyBracket: '{';
|
OpenCurlyBracket: '{'; // Öffnende geschweifte Klammer
|
||||||
ClosedCurlyBracket: '}';
|
ClosedCurlyBracket: '}'; // Schließende geschweifte Klammer
|
||||||
Semicolon: ';';
|
Semicolon: ';'; // Semikolon
|
||||||
Comma: ',';
|
Comma: ','; // Komma
|
||||||
|
|
||||||
// Schlüsselwörter
|
// Schlüsselwörter
|
||||||
Class: 'class';
|
Class: 'class';
|
||||||
@ -161,21 +161,21 @@ New: 'new';
|
|||||||
Switch: 'switch';
|
Switch: 'switch';
|
||||||
Case: 'case';
|
Case: 'case';
|
||||||
Default: 'default';
|
Default: 'default';
|
||||||
Colon: ':';
|
Colon: ':'; // Doppelpunkt
|
||||||
|
|
||||||
// Werte
|
// Werte
|
||||||
CharValue: '\'' ~[\r\n]* '\'';
|
CharValue: '\'' ~[\r\n]* '\''; // Zeichenwert
|
||||||
IntValue: Minus? Numeric+;
|
IntValue: Minus? Numeric+; // Ganzzahlwert
|
||||||
BooleanValue: 'true' | 'false';
|
BooleanValue: 'true' | 'false'; // Boolean-Wert
|
||||||
NullValue: 'null';
|
NullValue: 'null'; // Null-Wert
|
||||||
|
|
||||||
// Bezeichner
|
// Bezeichner
|
||||||
fragment Alphabetic: [a-zA-Z];
|
fragment Alphabetic: [a-zA-Z];
|
||||||
fragment Numeric: [0-9];
|
fragment Numeric: [0-9];
|
||||||
fragment ValidIdentSymbols: Alphabetic | Numeric | '$' | '_';
|
fragment ValidIdentSymbols: Alphabetic | Numeric | '$' | '_';
|
||||||
Identifier: Alphabetic ValidIdentSymbols*;
|
Identifier: Alphabetic ValidIdentSymbols*; // Bezeichner
|
||||||
|
|
||||||
// Whitespaces und Kommentare ignorieren
|
// Whitespaces und Kommentare ignorieren
|
||||||
WS: [ \t\r\n]+ -> skip;
|
WS: [ \t\r\n]+ -> skip; // Leerzeichen ignorieren
|
||||||
InlineComment: '//' ~[\r\n]* -> skip;
|
InlineComment: '//' ~[\r\n]* -> skip; // Einzeilige Kommentare ignorieren
|
||||||
MultilineComment: '/*' .*? '*/' -> skip;
|
MultilineComment: '/*' .*? '*/' -> skip; // Mehrzeilige Kommentare ignorieren
|
||||||
|
0
src/main/java/parser/parser_pp.md
Normal file
0
src/main/java/parser/parser_pp.md
Normal file
@ -8,7 +8,7 @@ import java.util.Stack;
|
|||||||
|
|
||||||
public class Scope {
|
public class Scope {
|
||||||
|
|
||||||
private Stack<HashMap<String, ITypeNode>> localVars;
|
private final Stack<HashMap<String, ITypeNode>> localVars;
|
||||||
|
|
||||||
public Scope() {
|
public Scope() {
|
||||||
localVars = new Stack<HashMap<String, ITypeNode>>();
|
localVars = new Stack<HashMap<String, ITypeNode>>();
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
package semantic;
|
package semantic;
|
||||||
|
|
||||||
|
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
@ -21,17 +20,15 @@ import ast.statementexpressions.AssignableNode;
|
|||||||
import ast.statementexpressions.NewDeclarationNode;
|
import ast.statementexpressions.NewDeclarationNode;
|
||||||
import ast.statementexpressions.crementexpressions.DecrementNode;
|
import ast.statementexpressions.crementexpressions.DecrementNode;
|
||||||
import ast.statementexpressions.crementexpressions.IncrementNode;
|
import ast.statementexpressions.crementexpressions.IncrementNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.ChainedMethodNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
||||||
import ast.statements.*;
|
import ast.statements.*;
|
||||||
import ast.type.AccessModifierNode;
|
|
||||||
import ast.type.EnumAccessModifierNode;
|
import ast.type.EnumAccessModifierNode;
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
import ast.type.type.*;
|
import ast.type.type.*;
|
||||||
import com.sun.jdi.IntegerType;
|
|
||||||
import semantic.context.Context;
|
import semantic.context.Context;
|
||||||
import semantic.exceptions.*;
|
import semantic.exceptions.*;
|
||||||
import typechecker.TypeCheckResult;
|
|
||||||
|
|
||||||
public class SemanticAnalyzer implements SemanticVisitor {
|
public class SemanticAnalyzer implements SemanticVisitor {
|
||||||
|
|
||||||
@ -112,10 +109,6 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(MethodNode methodNode) {
|
public TypeCheckResult analyze(MethodNode methodNode) {
|
||||||
if (methodNode instanceof ConstructorNode) {
|
|
||||||
return new TypeCheckResult(true, new BaseType(TypeEnum.VOID));
|
|
||||||
} else {
|
|
||||||
|
|
||||||
var valid = true;
|
var valid = true;
|
||||||
|
|
||||||
for (var otherMethod : currentClass.getMethods()) {
|
for (var otherMethod : currentClass.getMethods()) {
|
||||||
@ -157,12 +150,15 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return new TypeCheckResult(valid, resultType);
|
return new TypeCheckResult(valid, resultType);
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(FieldNode toCheck) {
|
public TypeCheckResult analyze(FieldNode toCheck) {
|
||||||
|
if (toCheck.type instanceof ReferenceType referenceType) {
|
||||||
|
if (!context.containsClass(referenceType.getIdentifier())) {
|
||||||
|
errors.add(new NotDeclaredException(referenceType.getIdentifier() + " not declared"));
|
||||||
|
}
|
||||||
|
}
|
||||||
if (currentFields.get(toCheck.identifier) != null) {
|
if (currentFields.get(toCheck.identifier) != null) {
|
||||||
errors.add(new AlreadyDeclaredException("Already declared " + toCheck.identifier));
|
errors.add(new AlreadyDeclaredException("Already declared " + toCheck.identifier));
|
||||||
return new TypeCheckResult(false, null);
|
return new TypeCheckResult(false, null);
|
||||||
@ -224,7 +220,7 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
}
|
}
|
||||||
for (IStatementNode statementNode : blockNode.statements) {
|
for (IStatementNode statementNode : blockNode.statements) {
|
||||||
var result = statementNode.accept(this);
|
var result = statementNode.accept(this);
|
||||||
if(!(statementNode instanceof IncrementNode) && !(statementNode instanceof DecrementNode)){
|
if (!(statementNode instanceof IncrementNode) && !(statementNode instanceof DecrementNode)) {
|
||||||
if (result.getType() != null) {
|
if (result.getType() != null) {
|
||||||
if (blockReturnType == null) {
|
if (blockReturnType == null) {
|
||||||
blockReturnType = result.getType();
|
blockReturnType = result.getType();
|
||||||
@ -244,21 +240,25 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
if (toCheck.memberAccess != null) {
|
if (toCheck.memberAccess != null) {
|
||||||
var result = toCheck.memberAccess.accept(this);
|
var result = toCheck.memberAccess.accept(this);
|
||||||
|
toCheck.identifier = toCheck.memberAccess.identifiers.getLast();
|
||||||
toCheck.setTypeNode(result.getType());
|
toCheck.setTypeNode(result.getType());
|
||||||
return result;
|
return result;
|
||||||
} else {
|
} else {
|
||||||
if (currentFields.get(toCheck.identifier) != null) {
|
if (currentFields.get(toCheck.identifier) != null) {
|
||||||
var type = currentFields.get(toCheck.identifier);
|
var type = currentFields.get(toCheck.identifier);
|
||||||
|
MemberAccessNode memberAccessNode = new MemberAccessNode(false);
|
||||||
|
memberAccessNode.identifiers.add(currentClass.identifier);
|
||||||
|
memberAccessNode.identifiers.add(toCheck.identifier);
|
||||||
|
toCheck.memberAccess = memberAccessNode;
|
||||||
toCheck.setTypeNode(type);
|
toCheck.setTypeNode(type);
|
||||||
return new TypeCheckResult(true, type);
|
return new TypeCheckResult(true, type);
|
||||||
} else if (currentScope.getLocalVar(toCheck.identifier) != null) {
|
} else if (currentScope.getLocalVar(toCheck.identifier) != null) {
|
||||||
var type = currentScope.getLocalVar(toCheck.identifier);
|
var type = currentScope.getLocalVar(toCheck.identifier);
|
||||||
|
toCheck.setTypeNode(type);
|
||||||
return new TypeCheckResult(true, type);
|
return new TypeCheckResult(true, type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new TypeCheckResult(true, null);
|
return new TypeCheckResult(true, null);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -275,13 +275,6 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
currentNullType = oldNullType;
|
currentNullType = oldNullType;
|
||||||
var valid = true;
|
var valid = true;
|
||||||
|
|
||||||
// This check currently handles things like :
|
|
||||||
/**
|
|
||||||
* private int i;
|
|
||||||
* void foo(int i){
|
|
||||||
* i = i;
|
|
||||||
* }
|
|
||||||
*/
|
|
||||||
if (assignable.equals(rExpression)) {
|
if (assignable.equals(rExpression)) {
|
||||||
errors.add(new TypeMismatchException("Cannot assign to self"));
|
errors.add(new TypeMismatchException("Cannot assign to self"));
|
||||||
valid = false;
|
valid = false;
|
||||||
@ -310,41 +303,97 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(IfElseNode toCheck) {
|
public TypeCheckResult analyze(IfElseNode toCheck) {
|
||||||
var resultIf = toCheck.ifStatement.accept(this);
|
var resultIf = toCheck.ifStatement.accept(this);
|
||||||
var resultElse = toCheck.elseStatement.accept(this);
|
var validElseIf = true;
|
||||||
|
|
||||||
return new TypeCheckResult(resultIf.isValid() && resultElse.isValid(), new BaseType(TypeEnum.VOID));
|
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() && validElseIf, new BaseType(TypeEnum.VOID));
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
return new TypeCheckResult(resultIf.isValid(), new BaseType(TypeEnum.VOID));
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(MethodCallNode toCheck) {
|
public TypeCheckResult analyze(MethodCallNode toCheck) {
|
||||||
|
|
||||||
if (toCheck.target.identifier != null) {
|
if (toCheck.target != null) {
|
||||||
var targetType = currentScope.getLocalVar(toCheck.target.identifier);
|
if(toCheck.target.memberAccess == null){
|
||||||
if (targetType == null) {
|
MemberAccessNode memberAccessNode = new MemberAccessNode(false);
|
||||||
targetType = currentFields.get(toCheck.target.identifier);
|
memberAccessNode.identifiers.add(currentClass.identifier);
|
||||||
|
memberAccessNode.identifiers.add(toCheck.target.identifier);
|
||||||
|
toCheck.target.memberAccess = memberAccessNode;
|
||||||
}
|
}
|
||||||
if (targetType instanceof ReferenceType reference) {
|
if (toCheck.target.identifier != null) {
|
||||||
var type = getTypeFromMethod(toCheck, reference);
|
var targetType = currentScope.getLocalVar(toCheck.target.identifier);
|
||||||
if (type != null) {
|
if (targetType == null) {
|
||||||
return new TypeCheckResult(true, type);
|
targetType = currentFields.get(toCheck.target.identifier);
|
||||||
} else {
|
|
||||||
return new TypeCheckResult(false, null);
|
|
||||||
}
|
}
|
||||||
|
if (targetType instanceof ReferenceType reference) {
|
||||||
|
if (!toCheck.chainedMethods.isEmpty()) {
|
||||||
|
for (ChainedMethodNode chainedMethod : toCheck.chainedMethods) {
|
||||||
|
var type = getTypeFromMethod(chainedMethod, reference);
|
||||||
|
if (type instanceof ReferenceType referenceType)
|
||||||
|
reference = referenceType;
|
||||||
|
else
|
||||||
|
errors.add(new TypeMismatchException("Ein Basetyp hat keine funktionen"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var type = getTypeFromMethod(toCheck, reference);
|
||||||
|
if (type != null) {
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
|
} else {
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
if (toCheck.target.thisTar) {
|
|
||||||
var type = getTypeFromMethod(toCheck, new ReferenceType(currentClass.identifier));
|
|
||||||
if (type != null) {
|
|
||||||
return new TypeCheckResult(true, type);
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
var result = toCheck.target.accept(this);
|
if (toCheck.target.thisTar != null) {
|
||||||
if (result.getType() instanceof ReferenceType reference) {
|
if (toCheck.target.thisTar) {
|
||||||
return new TypeCheckResult(true, getTypeFromMethod(toCheck, reference));
|
var type = getTypeFromMethod(toCheck, new ReferenceType(currentClass.identifier));
|
||||||
|
if (type != null) {
|
||||||
|
toCheck.type = type;
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var result = toCheck.target.accept(this);
|
||||||
|
if (result.getType() instanceof ReferenceType reference) {
|
||||||
|
return new TypeCheckResult(true, getTypeFromMethod(toCheck, reference));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
if(toCheck.identifier != null) {
|
||||||
|
toCheck.target = new TargetNode(new MemberAccessNode(false));
|
||||||
|
toCheck.target.memberAccess.identifiers.add(currentClass.identifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
ReferenceType reference = new ReferenceType(currentClass.identifier);
|
||||||
|
if (!toCheck.chainedMethods.isEmpty()) {
|
||||||
|
for (ChainedMethodNode chainedMethod : toCheck.chainedMethods) {
|
||||||
|
var type = getTypeFromMethod(chainedMethod, reference);
|
||||||
|
if (type instanceof ReferenceType referenceType)
|
||||||
|
reference = referenceType;
|
||||||
|
else
|
||||||
|
errors.add(new TypeMismatchException("Ein Basetyp hat keine funktionen"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var type = getTypeFromMethod(toCheck, reference);
|
||||||
|
if (type != null) {
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
|
} else {
|
||||||
|
return new TypeCheckResult(false, null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new TypeCheckResult(false, null);
|
return new TypeCheckResult(false, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -380,12 +429,14 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(NewDeclarationNode toCheck) {
|
public TypeCheckResult analyze(NewDeclarationNode toCheck) {
|
||||||
|
|
||||||
if (context.containsClass(toCheck.identifier)) {
|
if (context.containsClass(toCheck.identifier)) {
|
||||||
|
for(var t : toCheck.expressions) {
|
||||||
|
t.accept(this);
|
||||||
|
}
|
||||||
return new TypeCheckResult(true, new ReferenceType(toCheck.identifier));
|
return new TypeCheckResult(true, new ReferenceType(toCheck.identifier));
|
||||||
|
} else {
|
||||||
|
throw new RuntimeException("Cannot find class " + toCheck.identifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
@ -409,6 +460,7 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
case PLUS, MINUS:
|
case PLUS, MINUS:
|
||||||
if (calcRes.getType() instanceof BaseType calcType && dotRes.getType() instanceof BaseType dotType &&
|
if (calcRes.getType() instanceof BaseType calcType && dotRes.getType() instanceof BaseType dotType &&
|
||||||
calcType.getTypeEnum().equals(TypeEnum.INT) && dotType.getTypeEnum().equals(TypeEnum.INT)) {
|
calcType.getTypeEnum().equals(TypeEnum.INT) && dotType.getTypeEnum().equals(TypeEnum.INT)) {
|
||||||
|
calcNode.setType(new BaseType(TypeEnum.INT));
|
||||||
return new TypeCheckResult(true, new BaseType(TypeEnum.INT));
|
return new TypeCheckResult(true, new BaseType(TypeEnum.INT));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@ -416,10 +468,12 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
calcNode.setType(calcNode.getType());
|
||||||
return new TypeCheckResult(calcRes.isValid(), calcRes.getType());
|
return new TypeCheckResult(calcRes.isValid(), calcRes.getType());
|
||||||
}
|
}
|
||||||
} else if (calcNode.dotExpression != null) {
|
} else if (calcNode.dotExpression != null) {
|
||||||
var dotRes = calcNode.dotExpression.accept(this);
|
var dotRes = calcNode.dotExpression.accept(this);
|
||||||
|
calcNode.setType(dotRes.getType());
|
||||||
return new TypeCheckResult(dotRes.isValid(), dotRes.getType());
|
return new TypeCheckResult(dotRes.isValid(), dotRes.getType());
|
||||||
}
|
}
|
||||||
return new TypeCheckResult(false, null);
|
return new TypeCheckResult(false, null);
|
||||||
@ -427,28 +481,46 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(DotNode toCheck) {
|
public TypeCheckResult analyze(DotNode toCheck) {
|
||||||
if (toCheck.dotSubstractionExpression != null) {
|
if (toCheck.dotSubtractionExpression != null) {
|
||||||
return toCheck.dotSubstractionExpression.accept(this);
|
var result = toCheck.dotSubtractionExpression.accept(this);
|
||||||
|
toCheck.setType(result.getType());
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
return new TypeCheckResult(false, null);
|
return new TypeCheckResult(false, null);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public TypeCheckResult analyze(DotSubstractionNode toCheck) {
|
public TypeCheckResult analyze(DotSubtractionNode toCheck) {
|
||||||
if (toCheck.value != null) {
|
if (toCheck.value != null) {
|
||||||
return toCheck.value.accept(this);
|
var result = toCheck.value.accept(this);
|
||||||
|
toCheck.setType(result.getType());
|
||||||
|
return result;
|
||||||
} else if (toCheck.memberAccess != null) {
|
} else if (toCheck.memberAccess != null) {
|
||||||
return toCheck.memberAccess.accept(this);
|
var result = toCheck.memberAccess.accept(this);
|
||||||
|
toCheck.setType(result.getType());
|
||||||
|
return result;
|
||||||
} else if (toCheck.methodCall != null) {
|
} else if (toCheck.methodCall != null) {
|
||||||
return toCheck.methodCall.accept(this);
|
var result = toCheck.methodCall.accept(this);
|
||||||
|
toCheck.setType(result.getType());
|
||||||
|
return result;
|
||||||
} else if (toCheck.identifier != null) {
|
} else if (toCheck.identifier != null) {
|
||||||
if (currentScope.contains(toCheck.identifier)) {
|
if (currentScope.contains(toCheck.identifier)) {
|
||||||
return new TypeCheckResult(true, currentScope.getLocalVar(toCheck.identifier));
|
var type = currentScope.getLocalVar(toCheck.identifier);
|
||||||
|
toCheck.setType(type);
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
} else if (currentFields.get(toCheck.identifier) != null) {
|
} else if (currentFields.get(toCheck.identifier) != null) {
|
||||||
return new TypeCheckResult(true, currentFields.get(toCheck.identifier));
|
var type = currentFields.get(toCheck.identifier);
|
||||||
|
toCheck.setType(type);
|
||||||
|
MemberAccessNode memberAccessNode = new MemberAccessNode(false);
|
||||||
|
memberAccessNode.identifiers.add(currentClass.identifier);
|
||||||
|
memberAccessNode.identifiers.add(toCheck.identifier);
|
||||||
|
toCheck.memberAccess = memberAccessNode;
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
}
|
}
|
||||||
} else if (toCheck.calculationExpression != null) {
|
} else if (toCheck.calculationExpression != null) {
|
||||||
return toCheck.calculationExpression.accept(this);
|
var result = toCheck.calculationExpression.accept(this);
|
||||||
|
toCheck.setType(result.getType());
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -462,15 +534,19 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
case LESS, LESS_EQUAL, GREATER, GREATER_EQUAL:
|
case LESS, LESS_EQUAL, GREATER, GREATER_EQUAL:
|
||||||
if (expResult.getType() instanceof BaseType expResultType && expResultType.getTypeEnum().equals(TypeEnum.INT) &&
|
if (expResult.getType() instanceof BaseType expResultType && expResultType.getTypeEnum().equals(TypeEnum.INT) &&
|
||||||
unaryResult.getType() instanceof BaseType unaryResultType && unaryResultType.getTypeEnum().equals(TypeEnum.INT)) {
|
unaryResult.getType() instanceof BaseType unaryResultType && unaryResultType.getTypeEnum().equals(TypeEnum.INT)) {
|
||||||
return new TypeCheckResult(true, new BaseType(TypeEnum.BOOL));
|
ITypeNode type = new BaseType(TypeEnum.BOOL);
|
||||||
|
nonCalculationNode.setType(type);
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
} else {
|
} else {
|
||||||
errors.add(new TypeMismatchException("Both types must be Integer"));
|
errors.add(new TypeMismatchException("Both types must be Integer"));
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case OR, AND:
|
case OR, AND:
|
||||||
if (expResult.getType() instanceof BaseType expResultType && expResultType.getTypeEnum().equals(TypeEnum.INT) &&
|
if (expResult.getType() instanceof BaseType expResultType && expResultType.getTypeEnum().equals(TypeEnum.BOOL) &&
|
||||||
unaryResult.getType() instanceof BaseType unaryResultType && unaryResultType.getTypeEnum().equals(TypeEnum.INT)) {
|
unaryResult.getType() instanceof BaseType unaryResultType && unaryResultType.getTypeEnum().equals(TypeEnum.BOOL)) {
|
||||||
return new TypeCheckResult(true, new BaseType(TypeEnum.BOOL));
|
ITypeNode type = new BaseType(TypeEnum.BOOL);
|
||||||
|
nonCalculationNode.setType(type);
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
} else {
|
} else {
|
||||||
errors.add(new TypeMismatchException("Both types must be Boolean"));
|
errors.add(new TypeMismatchException("Both types must be Boolean"));
|
||||||
}
|
}
|
||||||
@ -478,7 +554,9 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
case EQUAL, NOT_EQUAL:
|
case EQUAL, NOT_EQUAL:
|
||||||
if (expResult.getType() instanceof BaseType expResultType && unaryResult.getType() instanceof BaseType unaryResultType
|
if (expResult.getType() instanceof BaseType expResultType && unaryResult.getType() instanceof BaseType unaryResultType
|
||||||
&& Objects.equals(expResultType, unaryResultType)) {
|
&& Objects.equals(expResultType, unaryResultType)) {
|
||||||
return new TypeCheckResult(true, new BaseType(TypeEnum.BOOL));
|
ITypeNode type = new BaseType(TypeEnum.BOOL);
|
||||||
|
nonCalculationNode.setType(type);
|
||||||
|
return new TypeCheckResult(true, type);
|
||||||
} else {
|
} else {
|
||||||
errors.add(new TypeMismatchException("Both types must be the same"));
|
errors.add(new TypeMismatchException("Both types must be the same"));
|
||||||
}
|
}
|
||||||
@ -493,9 +571,21 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
if (unary.identifier != null) {
|
if (unary.identifier != null) {
|
||||||
if (currentScope.contains(unary.identifier)) {
|
if (currentScope.contains(unary.identifier)) {
|
||||||
return new TypeCheckResult(valid, currentScope.getLocalVar(unary.identifier));
|
var type = currentScope.getLocalVar(unary.identifier);
|
||||||
|
unary.setType(type);
|
||||||
|
return new TypeCheckResult(valid, type);
|
||||||
} else if (currentFields.get(unary.identifier) != null) {
|
} else if (currentFields.get(unary.identifier) != null) {
|
||||||
return new TypeCheckResult(valid, currentFields.get(unary.identifier));
|
MemberAccessNode memberAccessNode = new MemberAccessNode(false);
|
||||||
|
memberAccessNode.identifiers.add(currentClass.identifier);
|
||||||
|
memberAccessNode.identifiers.add(unary.identifier);
|
||||||
|
unary.memberAccess = memberAccessNode;
|
||||||
|
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) {
|
} else if (unary.statement != null) {
|
||||||
var result = unary.statement.accept(this);
|
var result = unary.statement.accept(this);
|
||||||
unary.setType(result.getType());
|
unary.setType(result.getType());
|
||||||
@ -505,15 +595,19 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
}
|
}
|
||||||
} else if (unary.statement != null) {
|
} else if (unary.statement != null) {
|
||||||
var result = unary.statement.accept(this);
|
var result = unary.statement.accept(this);
|
||||||
|
unary.setType(result.getType());
|
||||||
return new TypeCheckResult(result.isValid(), result.getType());
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
} else if (unary.value != null) {
|
} else if (unary.value != null) {
|
||||||
var result = unary.value.accept(this);
|
var result = unary.value.accept(this);
|
||||||
|
unary.setType(result.getType());
|
||||||
return new TypeCheckResult(result.isValid(), result.getType());
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
} else if (unary.memberAccess != null) {
|
} else if (unary.memberAccess != null) {
|
||||||
var result = unary.memberAccess.accept(this);
|
var result = unary.memberAccess.accept(this);
|
||||||
|
unary.setType(result.getType());
|
||||||
return new TypeCheckResult(result.isValid(), result.getType());
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
} else if (unary.expression != null) {
|
} else if (unary.expression != null) {
|
||||||
var result = unary.expression.accept(this);
|
var result = unary.expression.accept(this);
|
||||||
|
unary.setType(result.getType());
|
||||||
return new TypeCheckResult(result.isValid(), result.getType());
|
return new TypeCheckResult(result.isValid(), result.getType());
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -524,12 +618,23 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
public TypeCheckResult analyze(MemberAccessNode memberAccessNode) {
|
public TypeCheckResult analyze(MemberAccessNode memberAccessNode) {
|
||||||
|
|
||||||
ITypeNode currentType = null;
|
ITypeNode currentType = null;
|
||||||
|
int start = 0;
|
||||||
|
if(!memberAccessNode.identifiers.isEmpty()){
|
||||||
|
if(currentFields.get(memberAccessNode.identifiers.getFirst()) != null){
|
||||||
|
memberAccessNode.identifiers.addFirst(currentClass.identifier);
|
||||||
|
start++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if(context.getClasses().get(memberAccessNode.identifiers.getFirst()) == null){
|
||||||
|
memberAccessNode.identifiers.addFirst(currentClass.identifier);
|
||||||
|
start++;
|
||||||
|
}
|
||||||
|
for (int i = start; i < memberAccessNode.identifiers.size(); i++) {
|
||||||
|
|
||||||
for (String s : memberAccessNode.identifiers) {
|
String s = memberAccessNode.identifiers.get(i);
|
||||||
if (currentType == null) {
|
if (currentType == null) {
|
||||||
if (currentScope.getLocalVar(s) != null) {
|
if (currentScope.getLocalVar(s) != null) {
|
||||||
currentType = currentScope.getLocalVar(s);
|
currentType = currentScope.getLocalVar(s);
|
||||||
|
|
||||||
} else if (currentFields.get(s) != null) {
|
} else if (currentFields.get(s) != null) {
|
||||||
currentType = currentFields.get(s);
|
currentType = currentFields.get(s);
|
||||||
} else {
|
} else {
|
||||||
@ -540,7 +645,8 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
} else {
|
} else {
|
||||||
if (currentType instanceof ReferenceType reference) {
|
if (currentType instanceof ReferenceType reference) {
|
||||||
var currentTypeClass = context.getClass(reference.getIdentifier());
|
var currentTypeClass = context.getClass(reference.getIdentifier());
|
||||||
|
memberAccessNode.identifiers.add(i, reference.getIdentifier());
|
||||||
|
i++;
|
||||||
var currentField = currentTypeClass.getField(s);
|
var currentField = currentTypeClass.getField(s);
|
||||||
if (currentField.getAccessModifier().accessType == EnumAccessModifierNode.PUBLIC) {
|
if (currentField.getAccessModifier().accessType == EnumAccessModifierNode.PUBLIC) {
|
||||||
currentType = currentField.getType();
|
currentType = currentField.getType();
|
||||||
@ -552,7 +658,7 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
memberAccessNode.setTypeNode(currentType);
|
||||||
return new TypeCheckResult(true, currentType);
|
return new TypeCheckResult(true, currentType);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -561,6 +667,11 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
|
|
||||||
if (targetNode.memberAccess != null) {
|
if (targetNode.memberAccess != null) {
|
||||||
return targetNode.memberAccess.accept(this);
|
return targetNode.memberAccess.accept(this);
|
||||||
|
} else if(targetNode.identifier != null) {
|
||||||
|
MemberAccessNode memberAccessNode = new MemberAccessNode(false);
|
||||||
|
memberAccessNode.identifiers.add(currentClass.identifier);
|
||||||
|
memberAccessNode.identifiers.add(targetNode.identifier);
|
||||||
|
targetNode.memberAccess = memberAccessNode;
|
||||||
}
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@ -573,6 +684,7 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
return new TypeCheckResult(true, new BaseType(TypeEnum.INT));
|
return new TypeCheckResult(true, new BaseType(TypeEnum.INT));
|
||||||
}
|
}
|
||||||
case CHAR_VALUE -> {
|
case CHAR_VALUE -> {
|
||||||
|
valueNode.value = valueNode.value.replace("'", "");
|
||||||
return new TypeCheckResult(true, new BaseType(TypeEnum.CHAR));
|
return new TypeCheckResult(true, new BaseType(TypeEnum.CHAR));
|
||||||
}
|
}
|
||||||
case BOOLEAN_VALUE -> {
|
case BOOLEAN_VALUE -> {
|
||||||
@ -620,4 +732,37 @@ public class SemanticAnalyzer implements SemanticVisitor {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ITypeNode getTypeFromMethod(ChainedMethodNode toCheck, ReferenceType reference) {
|
||||||
|
var classContext = context.getClass(reference.getIdentifier());
|
||||||
|
|
||||||
|
var methods = classContext.getMethods();
|
||||||
|
for (var method : methods) {
|
||||||
|
if (toCheck.identifier.equals(method.getIdentifier())) {
|
||||||
|
if (method.getParameters().size() == toCheck.expressions.size() && !(method instanceof ConstructorNode)) {
|
||||||
|
boolean same = true;
|
||||||
|
for (int i = 0; i < method.getParameters().size(); i++) {
|
||||||
|
var result1 = method.getParameters().get(i).accept(this);
|
||||||
|
var result2 = toCheck.expressions.get(i).accept(this);
|
||||||
|
if (!Objects.equals(result1.getType(), result2.getType())) {
|
||||||
|
same = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (same) {
|
||||||
|
if (method.accesModifier.accessType == EnumAccessModifierNode.PUBLIC) {
|
||||||
|
if (method.getType() == null) {
|
||||||
|
return new BaseType(TypeEnum.VOID);
|
||||||
|
}
|
||||||
|
return method.getType();
|
||||||
|
} else {
|
||||||
|
errors.add(new NotVisibleException("This Method is not Visible"));
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
@ -15,7 +15,6 @@ import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
|||||||
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
||||||
import ast.statements.*;
|
import ast.statements.*;
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
import typechecker.TypeCheckResult;
|
|
||||||
|
|
||||||
public interface SemanticVisitor {
|
public interface SemanticVisitor {
|
||||||
|
|
||||||
@ -61,7 +60,7 @@ public interface SemanticVisitor {
|
|||||||
|
|
||||||
TypeCheckResult analyze(DotNode toCheck);
|
TypeCheckResult analyze(DotNode toCheck);
|
||||||
|
|
||||||
TypeCheckResult analyze(DotSubstractionNode toCheck);
|
TypeCheckResult analyze(DotSubtractionNode toCheck);
|
||||||
|
|
||||||
TypeCheckResult analyze(NonCalculationNode toCheck);
|
TypeCheckResult analyze(NonCalculationNode toCheck);
|
||||||
|
|
||||||
|
@ -1,12 +1,12 @@
|
|||||||
package typechecker;
|
package semantic;
|
||||||
|
|
||||||
|
|
||||||
import ast.type.type.ITypeNode;
|
import ast.type.type.ITypeNode;
|
||||||
|
|
||||||
public class TypeCheckResult {
|
public class TypeCheckResult {
|
||||||
|
|
||||||
private boolean valid;
|
private final boolean valid;
|
||||||
private ITypeNode type;
|
private final ITypeNode type;
|
||||||
|
|
||||||
public TypeCheckResult(boolean valid, ITypeNode type) {
|
public TypeCheckResult(boolean valid, ITypeNode type) {
|
||||||
this.valid = valid;
|
this.valid = valid;
|
@ -9,8 +9,8 @@ import java.util.HashMap;
|
|||||||
|
|
||||||
public class ClassContext {
|
public class ClassContext {
|
||||||
|
|
||||||
private HashMap<String, FieldContext> fields;
|
private final HashMap<String, FieldContext> fields;
|
||||||
private ArrayList<MethodNode> methods = new ArrayList<>();
|
private final ArrayList<MethodNode> methods = new ArrayList<>();
|
||||||
|
|
||||||
public ClassContext(ClassNode classNode) {
|
public ClassContext(ClassNode classNode) {
|
||||||
|
|
||||||
|
@ -5,7 +5,7 @@ import java.util.HashMap;
|
|||||||
|
|
||||||
public class Context {
|
public class Context {
|
||||||
|
|
||||||
private HashMap<String, ClassContext> classes;
|
private final HashMap<String, ClassContext> classes;
|
||||||
|
|
||||||
public Context(ProgramNode programNode) {
|
public Context(ProgramNode programNode) {
|
||||||
classes = new HashMap<>();
|
classes = new HashMap<>();
|
||||||
@ -21,6 +21,10 @@ public class Context {
|
|||||||
return classes.get(identifier);
|
return classes.get(identifier);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public HashMap<String, ClassContext> getClasses() {
|
||||||
|
return classes;
|
||||||
|
}
|
||||||
|
|
||||||
public boolean containsClass(String identifier) {
|
public boolean containsClass(String identifier) {
|
||||||
return classes.containsKey(identifier);
|
return classes.containsKey(identifier);
|
||||||
}
|
}
|
||||||
|
@ -6,8 +6,8 @@ import ast.type.type.*;
|
|||||||
|
|
||||||
public class FieldContext {
|
public class FieldContext {
|
||||||
|
|
||||||
private AccessModifierNode accessModifier;
|
private final AccessModifierNode accessModifier;
|
||||||
private ITypeNode type;
|
private final ITypeNode type;
|
||||||
|
|
||||||
public FieldContext(FieldNode field) {
|
public FieldContext(FieldNode field) {
|
||||||
accessModifier = field.accessTypeNode;
|
accessModifier = field.accessTypeNode;
|
||||||
|
@ -4,7 +4,7 @@ import bytecode.visitor.ClassVisitor;
|
|||||||
import bytecode.visitor.MethodVisitor;
|
import bytecode.visitor.MethodVisitor;
|
||||||
import bytecode.visitor.ProgramVisitor;
|
import bytecode.visitor.ProgramVisitor;
|
||||||
import semantic.SemanticVisitor;
|
import semantic.SemanticVisitor;
|
||||||
import typechecker.TypeCheckResult;
|
import semantic.TypeCheckResult;
|
||||||
|
|
||||||
public interface Visitable {
|
public interface Visitable {
|
||||||
default void accept(ProgramVisitor programVisitor) {
|
default void accept(ProgramVisitor programVisitor) {
|
||||||
|
3
src/main/resources/META-INF/MANIFEST.MF
Normal file
3
src/main/resources/META-INF/MANIFEST.MF
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
Manifest-Version: 1.0
|
||||||
|
Main-Class: main.Main
|
||||||
|
|
@ -1,16 +1,63 @@
|
|||||||
public class Compiler {
|
public class CompilerInput {
|
||||||
public int add(int i, int j) {
|
public int ps;
|
||||||
return i+j;
|
public char brand;
|
||||||
|
public int tires;
|
||||||
|
public int drivenKilometers;
|
||||||
|
|
||||||
|
public CompilerInput(int horsePower) {
|
||||||
|
this.ps = horsePower;
|
||||||
|
this.tires = 4;
|
||||||
}
|
}
|
||||||
public static void main(String[] args) {
|
|
||||||
int a = 1;
|
public int getTires() {
|
||||||
|
return this.tires;
|
||||||
|
}
|
||||||
|
|
||||||
|
public boolean isSuperCar() {
|
||||||
|
if(this.ps > 300) {
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void tune(int horsePower) {
|
||||||
|
this.ps = this.ps + horsePower;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void tune() {
|
||||||
|
this.ps = this.ps + 50;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void driveCircels(int circels) {
|
||||||
|
for(int i = 0; i < circels; i++) {
|
||||||
|
this.drivenKilometers = this.drivenKilometers + 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void isTunable(boolean hasEngine, boolean hasTires) {
|
||||||
|
if(hasEngine && hasTires) {
|
||||||
|
this.tune(5);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public char race() {
|
||||||
|
int enemyHorsePower = 200;
|
||||||
|
char win = 'W';
|
||||||
|
char lose = 'L';
|
||||||
|
CompilerInput enemy = new CompilerInput(ps);
|
||||||
|
if(this.ps > enemyHorsePower) {
|
||||||
|
return win;
|
||||||
|
} else {
|
||||||
|
return lose;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public int refuel(int currentTank, int maxTank){
|
||||||
|
int tank = currentTank;
|
||||||
|
do{
|
||||||
|
tank++;
|
||||||
|
}while(tank<maxTank);
|
||||||
|
return tank;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public class Node {
|
|
||||||
public void main() {
|
|
||||||
Compiler compiler = new Compiler();
|
|
||||||
int i = compiler.add(5, 8);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
809
src/main/resources/logs/miniCompiler.log
Normal file
809
src/main/resources/logs/miniCompiler.log
Normal file
File diff suppressed because one or more lines are too long
BIN
src/main/resources/output/CompilerInput.class
Normal file
BIN
src/main/resources/output/CompilerInput.class
Normal file
Binary file not shown.
Binary file not shown.
@ -2,42 +2,30 @@
|
|||||||
### IntelliJs play buttons do not work. Run in "src/test" folder with "make" command to run all
|
### 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.
|
### Or run only parts with "make compile-javac", "make clean" etc.
|
||||||
|
|
||||||
all: compile-javac compile-raupenpiler
|
all: compile-javac compile-miniCompiler
|
||||||
|
|
||||||
compile-javac:
|
compile-javac:
|
||||||
javac -d .\resources\output\javac .\resources\input\CompilerInput.java
|
javac -d .\resources\output\javac ..\main\resources\input\CompilerInput.java
|
||||||
|
|
||||||
compile-raupenpiler:
|
compile-miniCompiler:
|
||||||
cd ../.. ; mvn -DskipTests install
|
cd ../.. ; mvn -DskipTests install
|
||||||
cd ../.. ; mvn exec:java -Dexec.mainClass="main.Main" -Dexec.args="'src/main/resources/input/CompilerInput.java' 'src/main/resources/output' "
|
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 .\resources\output\miniCompiler
|
||||||
|
|
||||||
test: compile-javac compile-raupenpiler test-javac test-raupenpiler
|
|
||||||
|
|
||||||
test-javac:
|
|
||||||
# gleich wie bei raupenpiler, kann ich ohne funktionierenden Compiler nicht testen
|
|
||||||
|
|
||||||
|
|
||||||
test-raupenpiler:
|
|
||||||
# move the compiled class to the test/main folder
|
|
||||||
mv ../main/resources/output/CompilerInput.class .java/main/
|
|
||||||
# compile the test class
|
|
||||||
javac .java/main.EndToEndTester.java
|
|
||||||
# run the test class
|
|
||||||
java .java/main.EndToEndTester
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
clean:
|
clean:
|
||||||
# clean output folders
|
# clean main output folders
|
||||||
rm -f ../main/resources/output/*.class
|
rm -f ../main/resources/output/*.class
|
||||||
rm -f ../main/resources/output/*.jar
|
rm -f ../main/resources/output/*.jar
|
||||||
|
# clean resources output folders
|
||||||
rm -f ./resources/output/javac/*.class
|
rm -f ./resources/output/javac/*.class
|
||||||
rm -f ./resources/output/raupenpiler/*.class
|
rm -f ./resources/output/miniCompiler/*.class
|
||||||
|
rm -f ./resources/output/miniCompiler/*.jar
|
||||||
# clean logs
|
# clean logs
|
||||||
rm -f ../main/resources/logs/*.log
|
rm -f ../main/resources/logs/*
|
||||||
# clean test/main folders from .class files for End-to-End tests
|
# clean test/java/main folders from .class files for End-to-End tests
|
||||||
rm -f ./java/main/*.class
|
rm -f ./java/main/*.class
|
||||||
# clean javac output from featureTests
|
# clean javac output from every folder
|
||||||
rm -f ./resources/input/featureTests/*.class
|
rm -f ./resources/input/*/*.class
|
||||||
|
# clean test results from maven surefire plugin
|
||||||
|
rm -f ../../target/surefire-reports/*.txt
|
||||||
|
|
||||||
|
@ -1,93 +0,0 @@
|
|||||||
# Scanner
|
|
||||||
|
|
||||||
## Scanner Input
|
|
||||||
|
|
||||||
### Beispiel 1: Empty Class
|
|
||||||
|
|
||||||
String empty class = "public class Name {}";
|
|
||||||
|
|
||||||
### Beispiel 2: Filled Class
|
|
||||||
|
|
||||||
String filled class =
|
|
||||||
"class javaFileInput.Example {" +
|
|
||||||
"if (x < 5) {" +
|
|
||||||
"for (int i = 0; i < 10; i++) {" +
|
|
||||||
"while (true) {" +
|
|
||||||
"x = 5;" +
|
|
||||||
"}"
|
|
||||||
|
|
||||||
## Scanner Output
|
|
||||||
|
|
||||||
CommonTokenStream
|
|
||||||
|
|
||||||
### Beispiel 1: Empty Class
|
|
||||||
|
|
||||||
Token Type; Token Text
|
|
||||||
Type gibts nur bei Terminalen, Text bei allen
|
|
||||||
|
|
||||||
[null "public", null "class", IDENTIFIER "Name", null "{", null "}", EOF "<EOF>"]
|
|
||||||
|
|
||||||
Bsp von Ihm mal:
|
|
||||||
[TokPublic,TokClass,TokIdentifier "Name",TokLeftBrace,TokRightBrace]
|
|
||||||
|
|
||||||
# Parser
|
|
||||||
|
|
||||||
## Parser Input
|
|
||||||
|
|
||||||
CommonTokenStream
|
|
||||||
(Scanner Output)
|
|
||||||
|
|
||||||
## Parser Output (AST)
|
|
||||||
|
|
||||||
(program (classDeclaration (accessType public) class Name { }))
|
|
||||||
|
|
||||||
ParseTree
|
|
||||||
|
|
||||||
### Beispiel 1: Empty Class
|
|
||||||
|
|
||||||
# Semantische Analyse / Typcheck
|
|
||||||
|
|
||||||
## Typcheck Input
|
|
||||||
|
|
||||||
(Parser Output = AST)
|
|
||||||
|
|
||||||
## Typcheck Output
|
|
||||||
|
|
||||||
### Beispiel 1: Empty Class
|
|
||||||
|
|
||||||
# Bytecodegenerierung
|
|
||||||
|
|
||||||
## Bytecodegenerierung Input
|
|
||||||
|
|
||||||
(Typcheck Output = vom Typcheck eventuell manipulierter AST)
|
|
||||||
|
|
||||||
## Bytecodegenerierung Output
|
|
||||||
|
|
||||||
### Beispiel 1: Empty Class
|
|
||||||
|
|
||||||
Compiled Classfile
|
|
||||||
|
|
||||||
public class javaFileInput.Example {
|
|
||||||
}
|
|
||||||
|
|
||||||
## E2E Tests:
|
|
||||||
|
|
||||||
- Testdatei mit Main ausführen/kompilieren
|
|
||||||
- Testdatei mit "javac -d output .\CompilerInput.java" kompilieren
|
|
||||||
- -> Dateien mit javap vergleichen
|
|
||||||
|
|
||||||
wenn beides erfolgreich
|
|
||||||
|
|
||||||
- Ergebnis vom eigenen Compiler mithilfe von main.EndToEndTester ausführen
|
|
||||||
- (Ergebnis von javac mithilfe von main.EndToEndTester ausführen)
|
|
||||||
|
|
||||||
### Andis Tipps:
|
|
||||||
|
|
||||||
- cp mitgeben
|
|
||||||
- makefile
|
|
||||||
- java -jar pfadtocompiler.jar EmptyClass.java
|
|
||||||
- mvn package
|
|
||||||
- javac tester // tester compilen
|
|
||||||
- java tester // tester ausführen
|
|
||||||
- -> tester ist in unserem Fall main.EndToEndTester.java
|
|
||||||
- -> Hab ich alles umgesetzt
|
|
@ -1,177 +1,209 @@
|
|||||||
package main;
|
package main;
|
||||||
|
|
||||||
import ast.ASTNode;
|
import java.io.IOException;
|
||||||
import ast.ProgramNode;
|
import java.lang.reflect.Constructor;
|
||||||
import bytecode.ByteCodeGenerator;
|
import java.lang.reflect.Field;
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import org.antlr.v4.runtime.CharStream;
|
|
||||||
import org.antlr.v4.runtime.CommonTokenStream;
|
|
||||||
import org.antlr.v4.runtime.tree.ParseTree;
|
|
||||||
import parser.astBuilder.ASTBuilder;
|
|
||||||
import parser.generated.SimpleJavaLexer;
|
|
||||||
import parser.generated.SimpleJavaParser;
|
|
||||||
import semantic.SemanticAnalyzer;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
import static org.mockito.Mockito.*;
|
|
||||||
|
|
||||||
import java.lang.reflect.Method;
|
import java.lang.reflect.Method;
|
||||||
import java.util.ArrayList;
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.nio.file.StandardCopyOption;
|
||||||
|
import javax.tools.JavaCompiler;
|
||||||
|
import javax.tools.ToolProvider;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Disabled;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
public class E2EReflectionsTest {
|
public class E2EReflectionsTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
private CharStream mockInputCharStream;
|
public void CharTest() {
|
||||||
private String outputDirectoryPath;
|
runTest("Char");
|
||||||
private SimpleJavaLexer mockLexer;
|
|
||||||
private CommonTokenStream mockTokenStream;
|
|
||||||
private SimpleJavaParser mockParser;
|
|
||||||
private ParseTree mockParseTree;
|
|
||||||
private ASTBuilder mockASTBuilder;
|
|
||||||
private ASTNode mockASTNode;
|
|
||||||
private SemanticAnalyzer mockSemanticAnalyzer;
|
|
||||||
private ASTNode mockTypedAST;
|
|
||||||
private ByteCodeGenerator mockByteCodeGenerator;
|
|
||||||
|
|
||||||
@BeforeEach
|
|
||||||
public void setUp() {
|
|
||||||
mockInputCharStream = mock(CharStream.class);
|
|
||||||
outputDirectoryPath = "path/to/output";
|
|
||||||
mockLexer = mock(SimpleJavaLexer.class);
|
|
||||||
mockTokenStream = mock(CommonTokenStream.class);
|
|
||||||
mockParser = mock(SimpleJavaParser.class);
|
|
||||||
mockParseTree = mock(ParseTree.class);
|
|
||||||
mockASTBuilder = mock(ASTBuilder.class);
|
|
||||||
mockASTNode = mock(ASTNode.class);
|
|
||||||
mockSemanticAnalyzer = mock(SemanticAnalyzer.class);
|
|
||||||
mockTypedAST = mock(ASTNode.class);
|
|
||||||
mockByteCodeGenerator = mock(ByteCodeGenerator.class);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCompileFile() throws Exception {
|
public void CommentsTest() {
|
||||||
// Mock the dependencies
|
runTest("Comments");
|
||||||
SimpleJavaLexer mockLexer = mock(SimpleJavaLexer.class);
|
|
||||||
CommonTokenStream mockTokenStream = mock(CommonTokenStream.class);
|
|
||||||
SimpleJavaParser mockParser = mock(SimpleJavaParser.class);
|
|
||||||
ParseTree mockParseTree = mock(ParseTree.class);
|
|
||||||
ASTBuilder mockASTBuilder = mock(ASTBuilder.class);
|
|
||||||
ASTNode mockASTNode = mock(ASTNode.class);
|
|
||||||
SemanticAnalyzer mockSemanticAnalyzer = mock(SemanticAnalyzer.class);
|
|
||||||
ASTNode mockTypedAST = mock(ASTNode.class);
|
|
||||||
ByteCodeGenerator mockByteCodeGenerator = mock(ByteCodeGenerator.class);
|
|
||||||
|
|
||||||
// Mock the behavior
|
|
||||||
when(mockLexer.nextToken()).thenReturn(null);
|
|
||||||
when(mockTokenStream.getTokens()).thenReturn(new ArrayList<>());
|
|
||||||
when(mockParser.program()).thenReturn((SimpleJavaParser.ProgramContext) mockParseTree);
|
|
||||||
when(mockASTBuilder.visit(mockParseTree)).thenReturn(mockASTNode);
|
|
||||||
when(SemanticAnalyzer.generateTast(mockASTNode)).thenReturn(mockTypedAST);
|
|
||||||
|
|
||||||
// Use reflection to invoke the compileFile method
|
|
||||||
Method compileFileMethod = main.Main.class.getDeclaredMethod("compileFile", CharStream.class, String.class);
|
|
||||||
compileFileMethod.setAccessible(true);
|
|
||||||
|
|
||||||
compileFileMethod.invoke(null, mockInputCharStream, outputDirectoryPath);
|
|
||||||
|
|
||||||
// Verify each step
|
|
||||||
verify(mockLexer, times(1)).nextToken();
|
|
||||||
verify(mockTokenStream, times(1)).getTokens();
|
|
||||||
verify(mockParser, times(1)).program();
|
|
||||||
verify(mockASTBuilder, times(1)).visit(mockParseTree);
|
|
||||||
verify(mockSemanticAnalyzer, times(1)).generateTast(mockASTNode);
|
|
||||||
verify(mockByteCodeGenerator, times(1)).visit((ProgramNode) mockTypedAST);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testCompileFile2() throws Exception {
|
public void ConstructorMethodCallTest() {
|
||||||
// Mock the behavior
|
runTest("ConstructorMethodCall");
|
||||||
when(mockLexer.nextToken()).thenReturn(null);
|
|
||||||
when(mockTokenStream.getTokens()).thenReturn(new ArrayList<>());
|
|
||||||
when(mockParser.program()).thenReturn((SimpleJavaParser.ProgramContext) mockParseTree);
|
|
||||||
when(mockASTBuilder.visit(mockParseTree)).thenReturn(mockASTNode);
|
|
||||||
when(SemanticAnalyzer.generateTast(mockASTNode)).thenReturn(mockTypedAST);
|
|
||||||
|
|
||||||
// Use reflection to invoke the compileFile method
|
|
||||||
Method compileFileMethod = main.Main.class.getDeclaredMethod("compileFile", CharStream.class, String.class);
|
|
||||||
compileFileMethod.setAccessible(true);
|
|
||||||
|
|
||||||
compileFileMethod.invoke(null, mockInputCharStream, outputDirectoryPath);
|
|
||||||
|
|
||||||
// Verify each step
|
|
||||||
verify(mockLexer, times(1)).nextToken();
|
|
||||||
verify(mockTokenStream, times(1)).getTokens();
|
|
||||||
verify(mockParser, times(1)).program();
|
|
||||||
verify(mockASTBuilder, times(1)).visit(mockParseTree);
|
|
||||||
verify(mockSemanticAnalyzer, times(1)).generateTast(mockASTNode);
|
|
||||||
verify(mockByteCodeGenerator, times(1)).visit((ProgramNode) mockTypedAST);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void testLexer() {
|
|
||||||
// Mock the behavior
|
|
||||||
when(mockLexer.nextToken()).thenReturn(null);
|
|
||||||
|
|
||||||
// Test the lexer
|
|
||||||
SimpleJavaLexer lexer = new SimpleJavaLexer(mockInputCharStream);
|
|
||||||
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
|
|
||||||
tokenStream.fill();
|
|
||||||
|
|
||||||
assertNotNull(tokenStream.getTokens());
|
|
||||||
verify(mockLexer, atLeastOnce()).nextToken();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testParser() {
|
public void ConstructorMethodCallParametersTest() {
|
||||||
// Mock the behavior
|
runTest("ConstructorMethodCallParameters");
|
||||||
when(mockParser.program()).thenReturn((SimpleJavaParser.ProgramContext) mockParseTree);
|
|
||||||
|
|
||||||
// Test the parser
|
|
||||||
SimpleJavaParser parser = new SimpleJavaParser(mockTokenStream);
|
|
||||||
ParseTree parseTree = parser.program();
|
|
||||||
|
|
||||||
assertNotNull(parseTree);
|
|
||||||
verify(mockParser, times(1)).program();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testASTBuilder() {
|
public void ConstructorParameterTest() {
|
||||||
// Mock the behavior
|
runTest("ConstructorParameter");
|
||||||
when(mockASTBuilder.visit(mockParseTree)).thenReturn(mockASTNode);
|
|
||||||
|
|
||||||
// Test the AST builder
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ASTNode abstractSyntaxTree = astBuilder.visit(mockParseTree);
|
|
||||||
|
|
||||||
assertNotNull(abstractSyntaxTree);
|
|
||||||
verify(mockASTBuilder, times(1)).visit(mockParseTree);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testSemanticAnalyzer() {
|
public void ConstructorThisDotTest() {
|
||||||
// Mock the behavior
|
runTest("ConstructorThisDot");
|
||||||
when(SemanticAnalyzer.generateTast(mockASTNode)).thenReturn(mockTypedAST);
|
|
||||||
|
|
||||||
// Test the semantic analyzer
|
|
||||||
ASTNode typedAst = SemanticAnalyzer.generateTast(mockASTNode);
|
|
||||||
|
|
||||||
assertNotNull(typedAst);
|
|
||||||
verify(mockSemanticAnalyzer, times(1)).generateTast(mockASTNode);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void testByteCodeGenerator() {
|
public void DoWhileTest() {
|
||||||
// Test the bytecode generator
|
runTest("DoWhile");
|
||||||
ByteCodeGenerator byteCodeGenerator = new ByteCodeGenerator(outputDirectoryPath, true, true);
|
}
|
||||||
byteCodeGenerator.visit((ProgramNode) mockTypedAST);
|
|
||||||
|
|
||||||
verify(mockByteCodeGenerator, times(1)).visit((ProgramNode) mockTypedAST);
|
@Test
|
||||||
|
public void EmptyClassTest() {
|
||||||
|
runTest("EmptyClass");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void EmptyClassWithConstructorTest() {
|
||||||
|
runTest("EmptyClassWithConstructor");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void FieldTest() {
|
||||||
|
runTest("Field");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void FieldWithAccessModifierTest() {
|
||||||
|
runTest("FieldWithAccessModifier");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ForTest() {
|
||||||
|
runTest("For");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void IfTest() {
|
||||||
|
runTest("If");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void IfElseTest() {
|
||||||
|
runTest("IfElse");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void IfElseIfElseTest() {
|
||||||
|
runTest("IfElseIfElse");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void IncrementTest() {
|
||||||
|
runTest("Increment");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void MainMethodTest() {
|
||||||
|
runTest("MainMethod");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void MultipleClassesTest() {
|
||||||
|
runTest("MultipleClasses");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ThisDotTest() {
|
||||||
|
runTest("ThisDot");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void VariableCalculationTest() {
|
||||||
|
runTest("VariableCalculation");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void VariableCompareTest() {
|
||||||
|
runTest("VariableCompare");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void VoidMethodTest() {
|
||||||
|
runTest("VoidMethod");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void WhileTest() {
|
||||||
|
runTest("While");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper method to eliminate redundancy
|
||||||
|
private void runTest(String fileName) {
|
||||||
|
try {
|
||||||
|
// compile with miniCompiler
|
||||||
|
Main.main(new String[]{"src/test/resources/input/singleFeatureTests/" + fileName + ".java", "src/test/resources/output/miniCompiler"});
|
||||||
|
// Get the system Java compiler
|
||||||
|
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
||||||
|
// Assert that the compiler is available
|
||||||
|
assertNotNull(javac, "Java Compiler is not available");
|
||||||
|
// compile with javac
|
||||||
|
javac.run(null, null, null, "src/test/resources/input/singleFeatureTests/" + fileName + ".java");
|
||||||
|
moveFile("src/test/resources/input/singleFeatureTests/" + fileName + ".class", "src/test/resources/output/javac/" + fileName + ".class");
|
||||||
|
|
||||||
|
// Load the javac class
|
||||||
|
Path javacClassPath = Paths.get("src/test/resources/output/javac");
|
||||||
|
ClassLoader javacClassLoader = new java.net.URLClassLoader(new java.net.URL[]{javacClassPath.toUri().toURL()});
|
||||||
|
Class<?> javacLoadedClass = javacClassLoader.loadClass(fileName);
|
||||||
|
|
||||||
|
// Load the miniCompiler class
|
||||||
|
Path miniCompilerClassPath = Paths.get("src/test/resources/output/miniCompiler");
|
||||||
|
ClassLoader miniCompilerClassLoader = new java.net.URLClassLoader(new java.net.URL[]{miniCompilerClassPath.toUri().toURL()});
|
||||||
|
Class<?> miniCompilerLoadedClass = miniCompilerClassLoader.loadClass(fileName);
|
||||||
|
|
||||||
|
// Class Name
|
||||||
|
assertEquals(fileName, javacLoadedClass.getName());
|
||||||
|
assertEquals(fileName, miniCompilerLoadedClass.getName());
|
||||||
|
|
||||||
|
// Constructors
|
||||||
|
Constructor<?>[] javacConstructors = javacLoadedClass.getDeclaredConstructors();
|
||||||
|
Constructor<?>[] miniCompilerConstructors = miniCompilerLoadedClass.getDeclaredConstructors();
|
||||||
|
assertEquals(javacConstructors.length, miniCompilerConstructors.length);
|
||||||
|
for (Constructor<?> c : javacConstructors) {
|
||||||
|
for (Constructor<?> miniCompilerConstructor : miniCompilerConstructors) {
|
||||||
|
assertEquals(c.getParameterCount(), miniCompilerConstructor.getParameterCount());
|
||||||
|
if (c.getParameterCount() == miniCompilerConstructor.getParameterCount()) {
|
||||||
|
assertEquals(c.getName(), miniCompilerConstructor.getName());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Methods
|
||||||
|
Method[] javacMethods = javacLoadedClass.getDeclaredMethods();
|
||||||
|
Method[] miniCompilerMethods = miniCompilerLoadedClass.getDeclaredMethods();
|
||||||
|
assertEquals(javacMethods.length, miniCompilerMethods.length);
|
||||||
|
for (int i = 0; i < javacMethods.length; i++) {
|
||||||
|
assertEquals(javacMethods[i].getName(), miniCompilerMethods[i].getName());
|
||||||
|
assertEquals(javacMethods[i].getReturnType(), miniCompilerMethods[i].getReturnType());
|
||||||
|
assertEquals(javacMethods[i].getParameterCount(), miniCompilerMethods[i].getParameterCount());
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fields
|
||||||
|
Field[] javacLoadedClassDeclaredFields = javacLoadedClass.getDeclaredFields();
|
||||||
|
Field[] miniCompilerLoadedClassDeclaredFields = miniCompilerLoadedClass.getDeclaredFields();
|
||||||
|
assertEquals(javacLoadedClassDeclaredFields.length, miniCompilerLoadedClassDeclaredFields.length);
|
||||||
|
for (Field field : javacLoadedClassDeclaredFields) {
|
||||||
|
for (Field miniCompilerField : miniCompilerLoadedClassDeclaredFields) {
|
||||||
|
if (field.getName().equals(miniCompilerField.getName())) {
|
||||||
|
assertEquals(field.getType(), miniCompilerField.getType());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (ClassNotFoundException | NoSuchFieldException | NoSuchMethodException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper method to move file
|
||||||
|
public static void moveFile(String sourceFilePath, String destinationFilePath) throws IOException {
|
||||||
|
Path sourcePath = Paths.get(sourceFilePath);
|
||||||
|
Path destinationPath = Paths.get(destinationFilePath);
|
||||||
|
Files.move(sourcePath, destinationPath, StandardCopyOption.REPLACE_EXISTING);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,45 +0,0 @@
|
|||||||
package main;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* This class is used to test the output of the compiler.
|
|
||||||
*
|
|
||||||
* <p>Im gleichen Ordner wie diese Datei (EndToEndTester.java) muss die selbst kompilierte CompilerInput.class Datei sein.
|
|
||||||
* <br><strong>Hinweis:</strong> Diese muss man also vom Ordner <code> main/resources/output </code> in diesen Ordner hier (test/java/main) rein kopieren. (bis es eine bessere Lösung gibt -> bin grad in der Make dran das alles hier automatisch zu machen)</p>
|
|
||||||
*
|
|
||||||
* <p>Die selbst kompilierte .class Datei wird dann hier drin geladen und eine Instanz von ihr erstellt, es können auch Methoden aufgerufen werden.
|
|
||||||
* <p>Diese EndToEndTester.java Datei wird dann in <code> \src\test\java> </code> mit <code>javac .\main.EndToEndTester.java</code> kompiliert und mit <code>java main.EndToEndTester</code> ausgeführt.
|
|
||||||
* 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) {
|
|
||||||
try {
|
|
||||||
// Try to load the class named "CompilerInput"
|
|
||||||
Class<?> cls = Class.forName("CompilerInput");
|
|
||||||
// Print a success message if the class is loaded successfully
|
|
||||||
System.out.println("Class loaded successfully: " + cls.getName());
|
|
||||||
|
|
||||||
// Try to create an instance of the loaded class
|
|
||||||
Object instance = cls.getDeclaredConstructor().newInstance();
|
|
||||||
// Print a success message if the instance is created successfully
|
|
||||||
System.out.println("Instance created: " + instance);
|
|
||||||
|
|
||||||
|
|
||||||
// If the class has a main method, you can invoke it
|
|
||||||
// cls.getMethod("main", String[].class).invoke(null, (Object) new String[]{});
|
|
||||||
|
|
||||||
// If the class has other methods, you can invoke them as well
|
|
||||||
// Example: cls.getMethod("someMethod").invoke(instance);
|
|
||||||
|
|
||||||
} catch (ClassNotFoundException e) {
|
|
||||||
// Print an error message if the class is not found
|
|
||||||
System.err.println("Class not found: " + e.getMessage());
|
|
||||||
} catch (Exception e) {
|
|
||||||
// Print an error message if any other exception occurs during class loading or instance creation
|
|
||||||
System.err.println("Error during class loading or execution: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,48 +0,0 @@
|
|||||||
package main;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import javax.tools.JavaCompiler;
|
|
||||||
import javax.tools.ToolProvider;
|
|
||||||
import java.io.File;
|
|
||||||
|
|
||||||
public class FailureTest {
|
|
||||||
/**
|
|
||||||
* This test method checks if invalid Java files fail to compile as expected.
|
|
||||||
* It uses the JavaCompiler from the ToolProvider to compile the files.
|
|
||||||
* The test passes if all the files fail to compile.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void areTestFilesActuallyFailTest() {
|
|
||||||
// Get the system Java compiler
|
|
||||||
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
|
||||||
// Assert that the compiler is available
|
|
||||||
assertNotNull(javac, "Java Compiler is not available");
|
|
||||||
|
|
||||||
String directoryPath = "src/test/resources/input/failureTests";
|
|
||||||
File folder = new File(directoryPath);
|
|
||||||
|
|
||||||
if (folder.isDirectory()) {
|
|
||||||
File[] files = folder.listFiles((dir, name) -> name.endsWith(".java"));
|
|
||||||
|
|
||||||
if (files != null) {
|
|
||||||
for (File file : files) {
|
|
||||||
// Try to compile the file and get the result
|
|
||||||
// The run method returns 0 if the compilation was successful, and non-zero otherwise
|
|
||||||
int result = javac.run(null, null, null, file.getPath());
|
|
||||||
|
|
||||||
// Assert that the compilation failed (i.e., the result is non-zero)
|
|
||||||
assertTrue(result != 0, "Expected compilation failure for " + file.getName());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
System.out.println("No files found in the directory.");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
System.out.println("The provided path is not a directory.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,46 +0,0 @@
|
|||||||
package main;
|
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
|
|
||||||
import javax.tools.JavaCompiler;
|
|
||||||
import javax.tools.ToolProvider;
|
|
||||||
import java.io.File;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
|
||||||
|
|
||||||
public class FeatureTest {
|
|
||||||
/**
|
|
||||||
* This test method checks if valid Java files compile successfully.
|
|
||||||
* It uses the JavaCompiler from the ToolProvider to compile the files.
|
|
||||||
* The test passes if all the files compile without errors.
|
|
||||||
*/
|
|
||||||
@Test
|
|
||||||
public void areTestFilesActuallyValid() {
|
|
||||||
// Get the system Java compiler
|
|
||||||
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
|
||||||
// Assert that the compiler is available
|
|
||||||
assertNotNull(javac, "Java Compiler is not available");
|
|
||||||
|
|
||||||
String directoryPath = "src/test/resources/input/featureTests";
|
|
||||||
File folder = new File(directoryPath);
|
|
||||||
|
|
||||||
if (folder.isDirectory()) {
|
|
||||||
File[] files = folder.listFiles((dir, name) -> name.endsWith(".java"));
|
|
||||||
|
|
||||||
if (files != null) {
|
|
||||||
for (File file : files) {
|
|
||||||
// Try to compile the file and get the result
|
|
||||||
// The run method returns 0 if the compilation was successful, and non-zero otherwise
|
|
||||||
int result = javac.run(null, null, null, file.getPath());
|
|
||||||
|
|
||||||
// Assert that the compilation succeeded (i.e., the result is zero)
|
|
||||||
assertEquals(0, result, "Expected compilation success for " + file.getName());
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
System.out.println("No files found in the directory.");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
System.out.println("The provided path is not a directory.");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
160
src/test/java/main/InputFilesTest.java
Normal file
160
src/test/java/main/InputFilesTest.java
Normal file
@ -0,0 +1,160 @@
|
|||||||
|
package main;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import javax.tools.JavaCompiler;
|
||||||
|
import javax.tools.ToolProvider;
|
||||||
|
import java.io.File;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
public class InputFilesTest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This test method checks if valid Java files compile successfully.
|
||||||
|
* It uses the JavaCompiler from the ToolProvider to compile the files.
|
||||||
|
* The test passes if all the files compile without errors.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void areTestFilesActuallyValid() throws IOException {
|
||||||
|
// Get the system Java compiler
|
||||||
|
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
||||||
|
// Assert that the compiler is available
|
||||||
|
assertNotNull(javac, "Java Compiler is not available");
|
||||||
|
|
||||||
|
File combinedFeatureTests = new File("src/test/resources/input/combinedFeatureTests");
|
||||||
|
File endabgabeTests = new File("src/test/resources/input/endabgabeTests");
|
||||||
|
File singleFeatureSemanticTests = new File("src/test/resources/input/singleFeatureSemanticTests");
|
||||||
|
File singleFeatureTests = new File("src/test/resources/input/singleFeatureTests");
|
||||||
|
File typedAstFeatureTests = new File("src/test/resources/input/typedAstFeatureTests");
|
||||||
|
File finalTest = new File("src/test/resources/input/finalTest");
|
||||||
|
|
||||||
|
List<File> files = getJavaFilesFromDirectory(combinedFeatureTests);
|
||||||
|
// files.addAll(getJavaFilesFromDirectory(endabgabeTests));
|
||||||
|
// files.addAll(getJavaFilesFromDirectory(singleFeatureSemanticTests));
|
||||||
|
files.addAll(getJavaFilesFromDirectory(singleFeatureTests));
|
||||||
|
// files.addAll(getJavaFilesFromDirectory(typedAstFeatureTests));
|
||||||
|
//files.addAll(getJavaFilesFromDirectory(finalTest));
|
||||||
|
|
||||||
|
if (!files.isEmpty()) {
|
||||||
|
for (File file : files) {
|
||||||
|
// Try to compile the file and get the result
|
||||||
|
int result = javac.run(null, null, null, file.getPath());
|
||||||
|
|
||||||
|
// Assert that the compilation succeeded (i.e., the result is zero)
|
||||||
|
assertEquals(0, result, "Expected compilation success for " + file.getName());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("No files found in the directories.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void areCombinedFeatureTestsValid() throws IOException {
|
||||||
|
// Get the system Java compiler
|
||||||
|
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
||||||
|
// Assert that the compiler is available
|
||||||
|
assertNotNull(javac, "Java Compiler is not available");
|
||||||
|
|
||||||
|
File combinedFeatureTests = new File("src/test/resources/input/combinedFeatureTests");
|
||||||
|
|
||||||
|
List<File> files = getJavaFilesFromDirectory(combinedFeatureTests);
|
||||||
|
|
||||||
|
if (!files.isEmpty()) {
|
||||||
|
for (File file : files) {
|
||||||
|
// Try to compile the file and get the result
|
||||||
|
int result = javac.run(null, null, null, file.getPath());
|
||||||
|
|
||||||
|
// Assert that the compilation succeeded (i.e., the result is zero)
|
||||||
|
assertEquals(0, result, "Expected compilation success for " + file.getName());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("No files found in the directories.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void areSingleFeatureTestsActuallyValid() throws IOException {
|
||||||
|
// Get the system Java compiler
|
||||||
|
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
||||||
|
// Assert that the compiler is available
|
||||||
|
assertNotNull(javac, "Java Compiler is not available");
|
||||||
|
|
||||||
|
File singleFeatureTests = new File("src/test/resources/input/singleFeatureTests");
|
||||||
|
|
||||||
|
List<File> files = getJavaFilesFromDirectory(singleFeatureTests);
|
||||||
|
|
||||||
|
if (!files.isEmpty()) {
|
||||||
|
for (File file : files) {
|
||||||
|
// Try to compile the file and get the result
|
||||||
|
int result = javac.run(null, null, null, file.getPath());
|
||||||
|
|
||||||
|
// Assert that the compilation succeeded (i.e., the result is zero)
|
||||||
|
assertEquals(0, result, "Expected compilation success for " + file.getName());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("No files found in the directories.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This test method checks if invalid Java files fail to compile as expected.
|
||||||
|
* It uses the JavaCompiler from the ToolProvider to compile the files.
|
||||||
|
* The test passes if all the files fail to compile.
|
||||||
|
*/
|
||||||
|
@Test
|
||||||
|
public void areTestFilesActuallyFails() throws IOException {
|
||||||
|
// Get the system Java compiler
|
||||||
|
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
|
||||||
|
// Assert that the compiler is available
|
||||||
|
assertNotNull(javac, "Java Compiler is not available");
|
||||||
|
|
||||||
|
|
||||||
|
File folder1 = new File("src/test/resources/input/failureTests");
|
||||||
|
File folder2 = new File("src/test/resources/input/typedAstExceptionsTest");
|
||||||
|
|
||||||
|
List<File> files = getJavaFilesFromDirectory(folder1);
|
||||||
|
files.addAll(getJavaFilesFromDirectory(folder2));
|
||||||
|
|
||||||
|
|
||||||
|
if (!files.isEmpty()) {
|
||||||
|
for (File file : files) {
|
||||||
|
// Try to compile the file and get the result
|
||||||
|
// The run method returns 0 if the compilation was successful, and non-zero otherwise
|
||||||
|
int result = javac.run(null, null, null, file.getPath());
|
||||||
|
|
||||||
|
// Assert that the compilation failed (i.e., the result is non-zero)
|
||||||
|
assertTrue(result != 0, "Expected compilation failure for " + file.getName());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
System.out.println("No files found in the directory.");
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to get all .java files from a directory.
|
||||||
|
*
|
||||||
|
* @param directory the directory to search for .java files
|
||||||
|
* @return a list of .java files
|
||||||
|
* @throws IOException if an I/O error occurs
|
||||||
|
*/
|
||||||
|
private List<File> getJavaFilesFromDirectory(File directory) throws IOException {
|
||||||
|
if (directory.isDirectory()) {
|
||||||
|
return Files.list(directory.toPath())
|
||||||
|
.filter(path -> path.toString().endsWith(".java"))
|
||||||
|
.map(java.nio.file.Path::toFile)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
} else {
|
||||||
|
System.out.println("The provided path is not a directory: " + directory.getPath());
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,28 +1,18 @@
|
|||||||
package main;
|
package main;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.runner.RunWith;
|
||||||
import org.antlr.v4.runtime.CharStream;
|
import org.junit.runners.Suite;
|
||||||
import org.antlr.v4.runtime.CharStreams;
|
import semantic.EndToTypedAstTest;
|
||||||
|
import semantic.SemanticTest;
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* run every test: mvn test
|
* This class is a test suite that runs all the test classes in the project.
|
||||||
* Nutzen dieser Klasse: Eigentlich nicht vorhanden, in der Main gibts nichts zu testen
|
* <p> run: <code> mvn test </code>
|
||||||
|
* <p> check results in console or <code> target/surefire-reports </code>
|
||||||
*/
|
*/
|
||||||
|
@RunWith(Suite.class)
|
||||||
|
@Suite.SuiteClasses({
|
||||||
|
})
|
||||||
public class MainTest {
|
public class MainTest {
|
||||||
@Test
|
// This class remains empty, it is used only as a holder for the above annotations
|
||||||
void test() {
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/main/test/resources/CompilerInput.java"));
|
|
||||||
Main.compileFile(codeCharStream, "src/main/test/resources/output");
|
|
||||||
} catch (IOException e) {
|
|
||||||
System.err.println("Error reading the file: " + e.getMessage());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -6,7 +6,7 @@ import ast.ProgramNode;
|
|||||||
import ast.expressions.IExpressionNode;
|
import ast.expressions.IExpressionNode;
|
||||||
import ast.expressions.binaryexpressions.CalculationNode;
|
import ast.expressions.binaryexpressions.CalculationNode;
|
||||||
import ast.expressions.binaryexpressions.DotNode;
|
import ast.expressions.binaryexpressions.DotNode;
|
||||||
import ast.expressions.binaryexpressions.DotSubstractionNode;
|
import ast.expressions.binaryexpressions.DotSubtractionNode;
|
||||||
import ast.expressions.binaryexpressions.NonCalculationNode;
|
import ast.expressions.binaryexpressions.NonCalculationNode;
|
||||||
import ast.expressions.unaryexpressions.MemberAccessNode;
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
import ast.expressions.unaryexpressions.UnaryNode;
|
import ast.expressions.unaryexpressions.UnaryNode;
|
||||||
@ -14,23 +14,19 @@ import ast.members.*;
|
|||||||
import ast.parameters.ParameterNode;
|
import ast.parameters.ParameterNode;
|
||||||
import ast.statementexpressions.AssignNode;
|
import ast.statementexpressions.AssignNode;
|
||||||
import ast.statementexpressions.AssignableNode;
|
import ast.statementexpressions.AssignableNode;
|
||||||
|
import ast.statementexpressions.NewDeclarationNode;
|
||||||
import ast.statementexpressions.crementexpressions.CrementType;
|
import ast.statementexpressions.crementexpressions.CrementType;
|
||||||
import ast.statementexpressions.crementexpressions.DecrementNode;
|
import ast.statementexpressions.crementexpressions.DecrementNode;
|
||||||
import ast.statementexpressions.crementexpressions.IncrementNode;
|
import ast.statementexpressions.crementexpressions.IncrementNode;
|
||||||
import ast.statementexpressions.NewDeclarationNode;
|
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
import ast.statements.*;
|
|
||||||
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
import ast.statementexpressions.methodcallstatementnexpressions.TargetNode;
|
||||||
import ast.statements.BlockNode;
|
import ast.statements.*;
|
||||||
import ast.statements.LocalVariableDeclarationNode;
|
|
||||||
import ast.statements.ReturnNode;
|
|
||||||
import ast.type.AccessModifierNode;
|
import ast.type.AccessModifierNode;
|
||||||
import ast.type.EnumValueNode;
|
import ast.type.EnumValueNode;
|
||||||
import ast.type.ValueNode;
|
import ast.type.ValueNode;
|
||||||
import ast.type.type.BaseType;
|
import ast.type.type.BaseType;
|
||||||
import ast.type.type.ReferenceType;
|
import ast.type.type.ReferenceType;
|
||||||
import ast.type.type.TypeEnum;
|
import ast.type.type.TypeEnum;
|
||||||
|
|
||||||
import org.junit.jupiter.api.DisplayName;
|
import org.junit.jupiter.api.DisplayName;
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
@ -39,104 +35,106 @@ import static org.assertj.core.api.Assertions.assertThat;
|
|||||||
@DisplayName("Untyped Abstract Syntax Tree")
|
@DisplayName("Untyped Abstract Syntax Tree")
|
||||||
class AstBuilderTest {
|
class AstBuilderTest {
|
||||||
|
|
||||||
|
private final static String directoryPath = "src/test/resources/input/singleFeatureTests/";
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Empty Class Test")
|
@DisplayName("Empty Class Test")
|
||||||
public void emptyClassTest(){
|
public void emptyClassTest() {
|
||||||
ClassNode emptyClass = Helper.generateEmptyClass("TestClass");
|
ClassNode emptyClass = Helper.generateEmptyClass("EmptyClass");
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(emptyClass);
|
expected.addClass(emptyClass);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/EmptyClass.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "EmptyClass.java");
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Multiple Empty Classes Test")
|
@DisplayName("Multiple Empty Classes Test")
|
||||||
public void multipleEmptyClassesTest() {
|
public void multipleEmptyClassesTest() {
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass1");
|
ClassNode class1 = Helper.generateEmptyClass("MultipleClasses");
|
||||||
ClassNode class2 = Helper.generateEmptyClass("TestClass2");
|
ClassNode class2 = Helper.generateEmptyClass("TestClass2");
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
expected.addClass(class2);
|
expected.addClass(class2);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/MultipleClasses.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "MultipleClasses.java");
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Empty Class Test with Constructor")
|
@DisplayName("Empty Class Test with Constructor")
|
||||||
public void emptyClassWithConstructorTest() {
|
public void emptyClassWithConstructorTest() {
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("EmptyClassWithConstructor");
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/EmptyClassWithConstructor.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "EmptyClassWithConstructor.java");
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Field Test")
|
@DisplayName("Field Test")
|
||||||
public void fieldTest() {
|
public void fieldTest() {
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("Field");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/Field.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "Field.java");
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Field Test with Accessmodifier")
|
@DisplayName("Field Test with Accessmodifier")
|
||||||
public void fieldTestWithModifier() {
|
public void fieldTestWithModifier() {
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("FieldWithAccessModifier");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/FieldWithAccessModifier.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "FieldWithAccessModifier.java");
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Commments Ignore Test")
|
@DisplayName("Comments Ignore Test")
|
||||||
public void commmentsIgnoreTest(){
|
public void commentsIgnoreTest() {
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("Comments");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("private"), new BaseType(TypeEnum.INT), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("private"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/Comments.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "Comments.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Constructor Paramerter Test")
|
@DisplayName("Constructor Parameter Test")
|
||||||
public void constructorParameterTest(){
|
public void constructorParameterTest() {
|
||||||
BlockNode block = new BlockNode();
|
BlockNode block = new BlockNode();
|
||||||
block.addStatement(new ReturnNode(null));
|
block.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", block);
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorParameter", block);
|
||||||
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "ConstructorParameter");
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/ConstructorParameter.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorParameter.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("This Dot Test")
|
@DisplayName("This Dot Test")
|
||||||
public void thisDotTest(){
|
public void thisDotTest() {
|
||||||
BlockNode block = new BlockNode();
|
BlockNode block = new BlockNode();
|
||||||
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
memberAccess.addIdentifier("a");
|
memberAccess.addIdentifier("a");
|
||||||
@ -148,23 +146,23 @@ class AstBuilderTest {
|
|||||||
|
|
||||||
block.addStatement(new AssignNode(assignable, expression));
|
block.addStatement(new AssignNode(assignable, expression));
|
||||||
block.addStatement(new ReturnNode(null));
|
block.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", block);
|
ConstructorNode constructor = new ConstructorNode("public", "ThisDot", block);
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "ThisDot");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/ThisDot.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "ThisDot.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Constructor This Dot Test")
|
@DisplayName("Constructor This Dot Test")
|
||||||
public void constructorThisDotTest(){
|
public void constructorThisDotTest() {
|
||||||
BlockNode block = new BlockNode();
|
BlockNode block = new BlockNode();
|
||||||
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
memberAccess.addIdentifier("a");
|
memberAccess.addIdentifier("a");
|
||||||
@ -175,25 +173,25 @@ class AstBuilderTest {
|
|||||||
|
|
||||||
block.addStatement(new AssignNode(assignable, expression));
|
block.addStatement(new AssignNode(assignable, expression));
|
||||||
block.addStatement(new ReturnNode(null));
|
block.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", block);
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorThisDot", block);
|
||||||
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "ConstructorThisDot");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("private"), new BaseType(TypeEnum.INT), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("private"), new BaseType(TypeEnum.INT), "a"));
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/ConstructorThisDot.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorThisDot.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Void Methoden Test")
|
@DisplayName("Void Methoden Test")
|
||||||
public void voidMethodenTest(){
|
public void voidMethodenTest() {
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("VoidMethod");
|
||||||
BlockNode block = new BlockNode();
|
BlockNode block = new BlockNode();
|
||||||
block.addStatement(new ReturnNode(null));
|
block.addStatement(new ReturnNode(null));
|
||||||
class1.addMember(new MethodNode("public", null, true, "test", block));
|
class1.addMember(new MethodNode("public", null, true, "test", block));
|
||||||
@ -201,14 +199,14 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/VoidMethod.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "VoidMethod.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Constructor Method call Test")
|
@DisplayName("Constructor Method call Test")
|
||||||
public void constructorMethodCallTest(){
|
public void constructorMethodCallTest() {
|
||||||
BlockNode blockCon = new BlockNode();
|
BlockNode blockCon = new BlockNode();
|
||||||
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
memberAccess.addIdentifier("a");
|
memberAccess.addIdentifier("a");
|
||||||
@ -219,13 +217,13 @@ class AstBuilderTest {
|
|||||||
|
|
||||||
blockCon.addStatement(new AssignNode(assignable, expression));
|
blockCon.addStatement(new AssignNode(assignable, expression));
|
||||||
blockCon.addStatement(new ReturnNode(null));
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", blockCon);
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorMethodCall", blockCon);
|
||||||
|
|
||||||
BlockNode blockMethod = new BlockNode();
|
BlockNode blockMethod = new BlockNode();
|
||||||
blockMethod.addStatement(new ReturnNode(new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "1"))));
|
blockMethod.addStatement(new ReturnNode(new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "1"))));
|
||||||
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod", blockMethod);
|
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod", blockMethod);
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "ConstructorMethodCall");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
class1.addMember(method);
|
class1.addMember(method);
|
||||||
@ -233,14 +231,14 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/ConstructorMethodCall.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorMethodCall.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Constructor Method call Parameters Test")
|
@DisplayName("Constructor Method call Parameters Test")
|
||||||
public void constructorMethodCallParametersTest(){
|
public void constructorMethodCallParametersTest() {
|
||||||
BlockNode blockCon = new BlockNode();
|
BlockNode blockCon = new BlockNode();
|
||||||
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
memberAccess.addIdentifier("a");
|
memberAccess.addIdentifier("a");
|
||||||
@ -253,7 +251,7 @@ class AstBuilderTest {
|
|||||||
|
|
||||||
blockCon.addStatement(new AssignNode(assignable, expression));
|
blockCon.addStatement(new AssignNode(assignable, expression));
|
||||||
blockCon.addStatement(new ReturnNode(null));
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", blockCon);
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorMethodCallParameters", blockCon);
|
||||||
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
BlockNode blockMethod = new BlockNode();
|
BlockNode blockMethod = new BlockNode();
|
||||||
@ -261,7 +259,7 @@ class AstBuilderTest {
|
|||||||
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod", blockMethod);
|
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod", blockMethod);
|
||||||
method.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
method.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "ConstructorMethodCallParameters");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
class1.addMember(method);
|
class1.addMember(method);
|
||||||
@ -269,14 +267,14 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/ConstructorMethodCallParameters.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "ConstructorMethodCallParameters.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Char Test")
|
@DisplayName("Char Test")
|
||||||
public void charTest(){
|
public void charTest() {
|
||||||
BlockNode blockCon = new BlockNode();
|
BlockNode blockCon = new BlockNode();
|
||||||
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
memberAccess.addIdentifier("a");
|
memberAccess.addIdentifier("a");
|
||||||
@ -289,7 +287,7 @@ class AstBuilderTest {
|
|||||||
|
|
||||||
blockCon.addStatement(new AssignNode(assignable, expression));
|
blockCon.addStatement(new AssignNode(assignable, expression));
|
||||||
blockCon.addStatement(new ReturnNode(null));
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", blockCon);
|
ConstructorNode constructor = new ConstructorNode("public", "Char", blockCon);
|
||||||
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.CHAR), "a"));
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.CHAR), "a"));
|
||||||
|
|
||||||
BlockNode blockMethod = new BlockNode();
|
BlockNode blockMethod = new BlockNode();
|
||||||
@ -297,7 +295,7 @@ class AstBuilderTest {
|
|||||||
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.CHAR), false, "testMethod", blockMethod);
|
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.CHAR), false, "testMethod", blockMethod);
|
||||||
method.addParameter(new ParameterNode(new BaseType(TypeEnum.CHAR), "a"));
|
method.addParameter(new ParameterNode(new BaseType(TypeEnum.CHAR), "a"));
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "Char");
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.CHAR), "a"));
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.CHAR), "a"));
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
class1.addMember(method);
|
class1.addMember(method);
|
||||||
@ -305,32 +303,93 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/Char.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "Char.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@DisplayName("Null Test")
|
@DisplayName("If Test")
|
||||||
public void nullTest(){
|
public void ifTest() {
|
||||||
BlockNode blockCon = new BlockNode();
|
BlockNode block = new BlockNode();
|
||||||
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
block.addStatement(new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "intValue", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "5"))));
|
||||||
memberAccess.addIdentifier("a");
|
|
||||||
|
|
||||||
AssignableNode assignable = new AssignableNode(memberAccess);
|
BlockNode ifBlock = new BlockNode();
|
||||||
|
ifBlock.addStatement(new DecrementNode(CrementType.SUFFIX, new AssignableNode("intValue")));
|
||||||
|
block.addStatement(new IfElseNode(new IfNode(new NonCalculationNode(new UnaryNode("intValue"), "==", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "5"))), ifBlock), null));
|
||||||
|
|
||||||
blockCon.addStatement(new AssignNode(assignable, new UnaryNode(new ValueNode(EnumValueNode.NULL_VALUE, "null"))));
|
block.addStatement(new ReturnNode(null));
|
||||||
blockCon.addStatement(new ReturnNode(null));
|
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", blockCon);
|
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ConstructorNode constructor = new ConstructorNode("public", "If", block);
|
||||||
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "If");
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/Null.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "If.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("If Else Test")
|
||||||
|
public void ifElseTest() {
|
||||||
|
BlockNode block = new BlockNode();
|
||||||
|
block.addStatement(new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "intValue", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "5"))));
|
||||||
|
|
||||||
|
BlockNode ifBlock = new BlockNode();
|
||||||
|
ifBlock.addStatement(new DecrementNode(CrementType.SUFFIX, new AssignableNode("intValue")));
|
||||||
|
BlockNode elseBlock = new BlockNode();
|
||||||
|
elseBlock.addStatement(new IncrementNode(CrementType.SUFFIX, new AssignableNode("intValue")));
|
||||||
|
block.addStatement(new IfElseNode(new IfNode(new NonCalculationNode(new UnaryNode("intValue"), "==", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "5"))), ifBlock), new ElseNode(elseBlock)));
|
||||||
|
|
||||||
|
block.addStatement(new ReturnNode(null));
|
||||||
|
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "IfElse", block);
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "IfElse");
|
||||||
|
class1.addMember(constructor);
|
||||||
|
|
||||||
|
ProgramNode expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "IfElse.java");
|
||||||
|
|
||||||
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("If Else If ElseTest")
|
||||||
|
public void ifElseIfElseTest() {
|
||||||
|
BlockNode block = new BlockNode();
|
||||||
|
block.addStatement(new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "intValue", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "5"))));
|
||||||
|
|
||||||
|
BlockNode ifBlock = new BlockNode();
|
||||||
|
ifBlock.addStatement(new DecrementNode(CrementType.SUFFIX, new AssignableNode("intValue")));
|
||||||
|
BlockNode elseBlock = new BlockNode();
|
||||||
|
elseBlock.addStatement(new IncrementNode(CrementType.SUFFIX, new AssignableNode("intValue")));
|
||||||
|
|
||||||
|
IfElseNode ifElseStatement = new IfElseNode(new IfNode(new NonCalculationNode(new UnaryNode("intValue"), "==", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "5"))), ifBlock), new ElseNode(elseBlock));
|
||||||
|
|
||||||
|
BlockNode ifElseBlock = new BlockNode();
|
||||||
|
ifElseBlock.addStatement(new IncrementNode(CrementType.SUFFIX, new AssignableNode("intValue")));
|
||||||
|
ifElseStatement.addElseIfStatement(new IfNode(new NonCalculationNode(new UnaryNode("intValue"), "==", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "4"))), ifElseBlock));
|
||||||
|
|
||||||
|
block.addStatement(ifElseStatement);
|
||||||
|
|
||||||
|
block.addStatement(new ReturnNode(null));
|
||||||
|
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "IfElseIfElse", block);
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "IfElseIfElse");
|
||||||
|
class1.addMember(constructor);
|
||||||
|
|
||||||
|
ProgramNode expected = new ProgramNode();
|
||||||
|
expected.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode actual = Helper.generateAST(directoryPath + "IfElseIfElse.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
@ -339,12 +398,12 @@ class AstBuilderTest {
|
|||||||
@DisplayName("Self Reference Test")
|
@DisplayName("Self Reference Test")
|
||||||
public void selfReferneceTest(){
|
public void selfReferneceTest(){
|
||||||
|
|
||||||
ClassNode testClass = Helper.generateEmptyClass("TestClass");
|
ClassNode testClass = Helper.generateEmptyClass("SelfReference");
|
||||||
|
|
||||||
MemberNode testClassObject = new FieldNode(new AccessModifierNode("public"), new ReferenceType("TestClass"),"testClass");
|
MemberNode testClassObject = new FieldNode(new AccessModifierNode("public"), new ReferenceType("SelfReference"),"selfReference");
|
||||||
|
|
||||||
BlockNode testMethod1Block = new BlockNode();
|
BlockNode testMethod1Block = new BlockNode();
|
||||||
testMethod1Block.addStatement(new ReturnNode(new UnaryNode(new MethodCallNode(new TargetNode(true), "testMethod2"))));
|
testMethod1Block.addStatement(new ReturnNode(new UnaryNode(new MethodCallNode(null, "testMethod2"))));
|
||||||
MethodNode testMethod1 = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod1", testMethod1Block);
|
MethodNode testMethod1 = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod1", testMethod1Block);
|
||||||
|
|
||||||
BlockNode testMethod2Block = new BlockNode();
|
BlockNode testMethod2Block = new BlockNode();
|
||||||
@ -352,11 +411,9 @@ class AstBuilderTest {
|
|||||||
MethodNode testMethod2 = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod2", testMethod2Block);
|
MethodNode testMethod2 = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod2", testMethod2Block);
|
||||||
|
|
||||||
BlockNode testMethod3Block = new BlockNode();
|
BlockNode testMethod3Block = new BlockNode();
|
||||||
testMethod3Block.addStatement(new LocalVariableDeclarationNode(new ReferenceType("TestClass"),"testClass1", "=", new UnaryNode(new NewDeclarationNode("TestClass")))); // Assing einfach "=" ?
|
testMethod3Block.addStatement(new LocalVariableDeclarationNode(new ReferenceType("SelfReference"),"selfReference1", "=", new UnaryNode(new NewDeclarationNode("SelfReference")))); // Assing einfach "=" ?
|
||||||
MemberAccessNode methodAccess = new MemberAccessNode(false);
|
MemberAccessNode methodAccess = new MemberAccessNode(false);
|
||||||
methodAccess.addIdentifier("testClass1");
|
TargetNode methodTarget = new TargetNode("selfReference1");
|
||||||
methodAccess.addIdentifier("testClass");
|
|
||||||
TargetNode methodTarget = new TargetNode(methodAccess);
|
|
||||||
testMethod3Block.addStatement(new ReturnNode(new UnaryNode(new MethodCallNode(methodTarget,"testMethod1"))));
|
testMethod3Block.addStatement(new ReturnNode(new UnaryNode(new MethodCallNode(methodTarget,"testMethod1"))));
|
||||||
MethodNode testMethod3 = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod3", testMethod3Block);
|
MethodNode testMethod3 = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod3", testMethod3Block);
|
||||||
|
|
||||||
@ -368,7 +425,7 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(testClass);
|
expected.addClass(testClass);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/SelfReference.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "SelfReference.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
@ -376,7 +433,7 @@ class AstBuilderTest {
|
|||||||
@Test
|
@Test
|
||||||
@DisplayName("Variable Compare Test")
|
@DisplayName("Variable Compare Test")
|
||||||
public void variableCompareTest(){
|
public void variableCompareTest(){
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("VariableCompare");
|
||||||
UnaryNode trueValue = new UnaryNode(new ValueNode(EnumValueNode.BOOLEAN_VALUE,"true"));
|
UnaryNode trueValue = new UnaryNode(new ValueNode(EnumValueNode.BOOLEAN_VALUE,"true"));
|
||||||
UnaryNode falseValue = new UnaryNode(new ValueNode(EnumValueNode.BOOLEAN_VALUE,"false"));
|
UnaryNode falseValue = new UnaryNode(new ValueNode(EnumValueNode.BOOLEAN_VALUE,"false"));
|
||||||
|
|
||||||
@ -419,7 +476,7 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/variableCompare.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "VariableCompare.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
@ -427,34 +484,34 @@ class AstBuilderTest {
|
|||||||
@Test
|
@Test
|
||||||
@DisplayName("Variable Calculation Test")
|
@DisplayName("Variable Calculation Test")
|
||||||
public void variableCalculationTest(){
|
public void variableCalculationTest(){
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("VariableCalculation");
|
||||||
|
|
||||||
BlockNode aPlusBBlock = new BlockNode();
|
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);
|
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), "a"));
|
||||||
aPlusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
aPlusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
||||||
|
|
||||||
BlockNode aMinusBBlock = new BlockNode();
|
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);
|
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), "a"));
|
||||||
aMinusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
aMinusBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
||||||
|
|
||||||
BlockNode aTimeBBlock = new BlockNode();
|
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);
|
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), "a"));
|
||||||
aTimeBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
aTimeBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
||||||
|
|
||||||
BlockNode aDivBBlock = new BlockNode();
|
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);
|
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), "a"));
|
||||||
aDivBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
aDivBMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
||||||
|
|
||||||
BlockNode complexCalcBlock = new BlockNode();
|
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);
|
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), "a"));
|
||||||
complexCalcMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
complexCalcMethod.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
||||||
@ -489,7 +546,7 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/variableCalculation.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "VariableCalculation.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
@ -497,7 +554,7 @@ class AstBuilderTest {
|
|||||||
@Test
|
@Test
|
||||||
@DisplayName("Main Method Test")
|
@DisplayName("Main Method Test")
|
||||||
public void mainMethodTest(){
|
public void mainMethodTest(){
|
||||||
ClassNode class1 = Helper.generateEmptyClass("TestClass");
|
ClassNode class1 = Helper.generateEmptyClass("MainMethod");
|
||||||
|
|
||||||
BlockNode block = new BlockNode();
|
BlockNode block = new BlockNode();
|
||||||
block.addStatement(new ReturnNode(null));
|
block.addStatement(new ReturnNode(null));
|
||||||
@ -507,7 +564,7 @@ class AstBuilderTest {
|
|||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/MainMethod.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "MainMethod.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
@ -526,15 +583,15 @@ class AstBuilderTest {
|
|||||||
blockCon.addStatement(new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "i", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "10"))));
|
blockCon.addStatement(new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "i", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "10"))));
|
||||||
blockCon.addStatement(whileStatement);
|
blockCon.addStatement(whileStatement);
|
||||||
blockCon.addStatement(new ReturnNode(null));
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", blockCon);
|
ConstructorNode constructor = new ConstructorNode("public", "While", blockCon);
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "While");
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/While.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "While.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
@ -557,15 +614,15 @@ class AstBuilderTest {
|
|||||||
blockCon.addStatement(new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "i", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "0"))));
|
blockCon.addStatement(new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "i", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "0"))));
|
||||||
blockCon.addStatement(blockDoWhile);
|
blockCon.addStatement(blockDoWhile);
|
||||||
blockCon.addStatement(new ReturnNode(null));
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", blockCon);
|
ConstructorNode constructor = new ConstructorNode("public", "DoWhile", blockCon);
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "DoWhile");
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/DoWhile.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "DoWhile.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
@ -576,7 +633,7 @@ class AstBuilderTest {
|
|||||||
LocalVariableDeclarationNode forDeclaration = new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "i", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "0")));
|
LocalVariableDeclarationNode forDeclaration = new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "i", "=", new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "0")));
|
||||||
|
|
||||||
AssignableNode assignable = new AssignableNode("i");
|
AssignableNode assignable = new AssignableNode("i");
|
||||||
IncrementNode increment = new IncrementNode(CrementType.SUFFIX, assignable);
|
IncrementNode increment = new IncrementNode(CrementType.PREFIX, assignable);
|
||||||
|
|
||||||
LocalVariableDeclarationNode declaration = new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "a", null, null);
|
LocalVariableDeclarationNode declaration = new LocalVariableDeclarationNode(new BaseType(TypeEnum.INT), "a", null, null);
|
||||||
|
|
||||||
@ -593,15 +650,15 @@ class AstBuilderTest {
|
|||||||
BlockNode blockCon = new BlockNode();
|
BlockNode blockCon = new BlockNode();
|
||||||
blockCon.addStatement(forStatement);
|
blockCon.addStatement(forStatement);
|
||||||
blockCon.addStatement(new ReturnNode(null));
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
ConstructorNode constructor = new ConstructorNode("public", "TestClass", blockCon);
|
ConstructorNode constructor = new ConstructorNode("public", "For", blockCon);
|
||||||
|
|
||||||
ClassNode class1 = new ClassNode("public", "TestClass");
|
ClassNode class1 = new ClassNode("public", "For");
|
||||||
class1.addMember(constructor);
|
class1.addMember(constructor);
|
||||||
|
|
||||||
ProgramNode expected = new ProgramNode();
|
ProgramNode expected = new ProgramNode();
|
||||||
expected.addClass(class1);
|
expected.addClass(class1);
|
||||||
|
|
||||||
ASTNode actual = Helper.generateAST("src/test/resources/input/javaCases/For.java");
|
ASTNode actual = Helper.generateAST(directoryPath + "For.java");
|
||||||
|
|
||||||
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
assertThat(actual).isEqualToComparingFieldByFieldRecursively(expected);
|
||||||
}
|
}
|
||||||
|
@ -2,12 +2,10 @@ package parser;
|
|||||||
|
|
||||||
import ast.ASTNode;
|
import ast.ASTNode;
|
||||||
import ast.ClassNode;
|
import ast.ClassNode;
|
||||||
import ast.ProgramNode;
|
|
||||||
import ast.members.ConstructorNode;
|
import ast.members.ConstructorNode;
|
||||||
import ast.members.MemberNode;
|
import ast.members.MemberNode;
|
||||||
import ast.statements.BlockNode;
|
import ast.statements.BlockNode;
|
||||||
import ast.statements.ReturnNode;
|
import ast.statements.ReturnNode;
|
||||||
import ast.type.AccessModifierNode;
|
|
||||||
import org.antlr.v4.runtime.CharStream;
|
import org.antlr.v4.runtime.CharStream;
|
||||||
import org.antlr.v4.runtime.CharStreams;
|
import org.antlr.v4.runtime.CharStreams;
|
||||||
import org.antlr.v4.runtime.CommonTokenStream;
|
import org.antlr.v4.runtime.CommonTokenStream;
|
||||||
@ -39,7 +37,7 @@ public class Helper {
|
|||||||
public static ClassNode generateEmptyClass(String className) {
|
public static ClassNode generateEmptyClass(String className) {
|
||||||
BlockNode blockNode = new BlockNode();
|
BlockNode blockNode = new BlockNode();
|
||||||
blockNode.addStatement(new ReturnNode(null));
|
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 classNode = new ClassNode("public", className);
|
||||||
classNode.addMember(constructor);
|
classNode.addMember(constructor);
|
||||||
return classNode;
|
return classNode;
|
||||||
|
@ -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;
|
|
||||||
}
|
|
||||||
}
|
|
@ -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()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,45 +0,0 @@
|
|||||||
package semantic;
|
|
||||||
|
|
||||||
import ast.ProgramNode;
|
|
||||||
import org.antlr.v4.runtime.CharStream;
|
|
||||||
import org.antlr.v4.runtime.CharStreams;
|
|
||||||
import org.antlr.v4.runtime.CommonTokenStream;
|
|
||||||
import org.antlr.v4.runtime.tree.ParseTree;
|
|
||||||
import org.junit.jupiter.api.Test;
|
|
||||||
import parser.astBuilder.ASTBuilder;
|
|
||||||
import parser.generated.SimpleJavaLexer;
|
|
||||||
import parser.generated.SimpleJavaParser;
|
|
||||||
|
|
||||||
import java.io.IOException;
|
|
||||||
import java.nio.file.Paths;
|
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
|
||||||
|
|
||||||
public class BeginnToTAST {
|
|
||||||
|
|
||||||
@Test
|
|
||||||
public void FieldTests() {
|
|
||||||
SemanticAnalyzer.clearAnalyzer();
|
|
||||||
|
|
||||||
CharStream codeCharStream = null;
|
|
||||||
try {
|
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/input/johnsTests/FieldTests.java"));
|
|
||||||
} catch (IOException e) {
|
|
||||||
throw new RuntimeException(e);
|
|
||||||
}
|
|
||||||
SimpleJavaLexer lexer = new SimpleJavaLexer(codeCharStream);
|
|
||||||
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
|
|
||||||
|
|
||||||
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
|
|
||||||
ParseTree parseTree = parser.program(); // parse the input
|
|
||||||
|
|
||||||
/* ------------------------- AST builder -> AST ------------------------- */
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
|
||||||
|
|
||||||
var result = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
|
||||||
|
|
||||||
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
@ -26,6 +26,8 @@ import java.util.regex.Matcher;
|
|||||||
import java.util.regex.Pattern;
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
import org.junit.jupiter.api.Test;
|
import org.junit.jupiter.api.Test;
|
||||||
|
import semantic.exceptions.*;
|
||||||
|
import semantic.exceptions.NotDeclaredException;
|
||||||
|
|
||||||
import static org.junit.jupiter.api.Assertions.*;
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
@ -38,17 +40,14 @@ public class EndToTypedAstTest {
|
|||||||
|
|
||||||
CharStream codeCharStream = null;
|
CharStream codeCharStream = null;
|
||||||
try {
|
try {
|
||||||
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/input/typedAstFeaturesTests/CorrectTest.java"));
|
codeCharStream = CharStreams.fromPath(Paths.get("src/test/resources/input/typedAstFeatureTests/CorrectTest.java"));
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
SimpleJavaLexer lexer = new SimpleJavaLexer(codeCharStream);
|
SimpleJavaLexer lexer = new SimpleJavaLexer(codeCharStream);
|
||||||
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
|
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
|
||||||
|
|
||||||
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
|
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
|
||||||
ParseTree parseTree = parser.program(); // parse the input
|
ParseTree parseTree = parser.program();
|
||||||
|
|
||||||
/* ------------------------- AST builder -> AST ------------------------- */
|
|
||||||
ASTBuilder astBuilder = new ASTBuilder();
|
ASTBuilder astBuilder = new ASTBuilder();
|
||||||
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
ProgramNode abstractSyntaxTree = (ProgramNode) astBuilder.visit(parseTree);
|
||||||
|
|
||||||
@ -115,7 +114,7 @@ public class EndToTypedAstTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
public void featureTest() {
|
public void featureTest() {
|
||||||
String directoryPath = "src/test/resources/input/typedAstFeaturesTests";
|
String directoryPath = "src/test/resources/input/typedAstFeatureTests";
|
||||||
File folder = new File(directoryPath);
|
File folder = new File(directoryPath);
|
||||||
if (folder.isDirectory()) {
|
if (folder.isDirectory()) {
|
||||||
File[] files = folder.listFiles((_, name) -> name.endsWith(".java"));
|
File[] files = folder.listFiles((_, name) -> name.endsWith(".java"));
|
||||||
@ -155,6 +154,200 @@ public class EndToTypedAstTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
@Test
|
||||||
|
public void notDeclared() {
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/johnsTests/NotDeclared.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof NotDeclaredException));
|
||||||
|
}*/
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void typeMismatchTest() {
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/TypeMismatchIntBool.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof TypeMismatchException));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void parameterAlreadyDecleared() {
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/ParameterAlreadyDecleared.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof AlreadyDeclaredException));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void fieldAlreadyDecleared(){
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/FieldAlreadyDecleared.java");
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof AlreadyDeclaredException));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void typeMismatchRefType(){
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/TypeMismatchRefType.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof TypeMismatchException));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void correctRetType(){
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/CorrectRetType.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void retTypeMismatch(){
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/RetTypeMismatch.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof TypeMismatchException));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void multipleRetType(){
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/MultipleRetTypes.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof MultipleReturnTypes));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void BothTypesMustBeSameGreaterSmallerEqual(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/BothTypesMustBeSame.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof TypeMismatchException));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void NoSuchType(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/ClassNotDeclared.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof NotDeclaredException));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void FieldIsNotVisible(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/FieldIsNotVisible.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertTrue(SemanticAnalyzer.errors.stream().anyMatch(c -> c instanceof NotVisibleException));
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void ChainedMethods(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/ChainedMethods.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void VariableCompare(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/VariableCompare.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void IfExpressionInt(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/IfExpressionInt.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertInstanceOf(TypeMismatchException.class, SemanticAnalyzer.errors.getFirst());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void SelectWrongMethodCauseParameter(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/SelectWrongMethodCauseParameter.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertFalse(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertInstanceOf(TypeMismatchException.class, SemanticAnalyzer.errors.getFirst());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void SelectRightMethodCauseParameter(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/SelectRightMethodCauseParameter.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void VariableCalculation(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/VariableCalculation.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void Expression(){
|
||||||
|
|
||||||
|
ASTNode tast = SemanticHelper.generateTypedASTFrom("src/test/resources/input/singleFeatureSemanticTests/Expression.java");
|
||||||
|
|
||||||
|
SemanticAnalyzer.generateTast(tast);
|
||||||
|
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
// ------------------ Helpers ------------------
|
// ------------------ Helpers ------------------
|
||||||
|
|
||||||
|
35
src/test/java/semantic/SemanticHelper.java
Normal file
35
src/test/java/semantic/SemanticHelper.java
Normal file
@ -0,0 +1,35 @@
|
|||||||
|
package semantic;
|
||||||
|
|
||||||
|
import ast.ASTNode;
|
||||||
|
import ast.ProgramNode;
|
||||||
|
import org.antlr.v4.runtime.CharStream;
|
||||||
|
import org.antlr.v4.runtime.CharStreams;
|
||||||
|
import org.antlr.v4.runtime.CommonTokenStream;
|
||||||
|
import org.antlr.v4.runtime.tree.ParseTree;
|
||||||
|
import parser.astBuilder.ASTBuilder;
|
||||||
|
import parser.generated.SimpleJavaLexer;
|
||||||
|
import parser.generated.SimpleJavaParser;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
|
||||||
|
public class SemanticHelper {
|
||||||
|
public static ASTNode generateTypedASTFrom(String filePath) {
|
||||||
|
|
||||||
|
SemanticAnalyzer.clearAnalyzer();
|
||||||
|
|
||||||
|
CharStream testFile = null;
|
||||||
|
try {
|
||||||
|
testFile = CharStreams.fromFileName(filePath);
|
||||||
|
} catch (IOException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
|
SimpleJavaLexer lexer = new SimpleJavaLexer(testFile);
|
||||||
|
CommonTokenStream tokenStream = new CommonTokenStream(lexer);
|
||||||
|
tokenStream.fill();
|
||||||
|
SimpleJavaParser parser = new SimpleJavaParser(tokenStream);
|
||||||
|
ParseTree parseTree = parser.program();
|
||||||
|
ASTBuilder astBuilder = new ASTBuilder();
|
||||||
|
|
||||||
|
return astBuilder.visit(parseTree);
|
||||||
|
}
|
||||||
|
}
|
@ -1,113 +1,413 @@
|
|||||||
package semantic;
|
package semantic;
|
||||||
|
|
||||||
|
import ast.ASTNode;
|
||||||
|
import ast.ClassNode;
|
||||||
|
import ast.ProgramNode;
|
||||||
|
import ast.expressions.IExpressionNode;
|
||||||
|
import ast.expressions.unaryexpressions.MemberAccessNode;
|
||||||
|
import ast.expressions.unaryexpressions.UnaryNode;
|
||||||
|
import ast.members.ConstructorNode;
|
||||||
|
import ast.members.FieldNode;
|
||||||
|
import ast.members.MethodNode;
|
||||||
|
import ast.parameters.ParameterNode;
|
||||||
|
import ast.statementexpressions.AssignNode;
|
||||||
|
import ast.statementexpressions.AssignableNode;
|
||||||
|
import ast.statementexpressions.methodcallstatementnexpressions.MethodCallNode;
|
||||||
|
import ast.statements.BlockNode;
|
||||||
|
import ast.statements.ReturnNode;
|
||||||
|
import ast.type.AccessModifierNode;
|
||||||
|
import ast.type.EnumValueNode;
|
||||||
|
import ast.type.ValueNode;
|
||||||
|
import ast.type.type.BaseType;
|
||||||
|
import ast.type.type.TypeEnum;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import parser.Helper;
|
||||||
|
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||||
|
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||||
|
|
||||||
public class SemanticTest {
|
public class SemanticTest {
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
public void setUp() {
|
||||||
|
SemanticAnalyzer.clearAnalyzer();
|
||||||
|
}
|
||||||
|
|
||||||
public void test(){
|
@Test
|
||||||
|
@DisplayName("Empty Class Test")
|
||||||
|
public void emptyClassTest() {
|
||||||
|
ClassNode emptyClass = Helper.generateEmptyClass("EmptyClass");
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(emptyClass);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Multiple Empty Classes Test")
|
||||||
|
public void multipleEmptyClassesTest() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("MultipleClasses");
|
||||||
|
ClassNode class2 = Helper.generateEmptyClass("TestClass2");
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
abstractSyntaxTree.addClass(class2);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Empty Class Test with Constructor")
|
||||||
|
public void emptyClassWithConstructorTest() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("EmptyClassWithConstructor");
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Field Test")
|
||||||
|
public void fieldTest() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("Field");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Field Test with Accessmodifier")
|
||||||
|
public void fieldTestWithModifier() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("FieldWithAccessModifier");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Comments Ignore Test")
|
||||||
|
public void commentsIgnoreTest() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("Comments");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("private"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Constructor Parameter Test")
|
||||||
|
public void constructorParameterTest() {
|
||||||
|
BlockNode block = new BlockNode();
|
||||||
|
block.addStatement(new ReturnNode(null));
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorParameter", block);
|
||||||
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "b"));
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "ConstructorParameter");
|
||||||
|
class1.addMember(constructor);
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("This Dot Test")
|
||||||
|
public void thisDotTest() {
|
||||||
|
BlockNode block = new BlockNode();
|
||||||
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
|
memberAccess.addIdentifier("a");
|
||||||
|
|
||||||
|
AssignableNode assignable = new AssignableNode(memberAccess);
|
||||||
|
|
||||||
|
ValueNode value = new ValueNode(EnumValueNode.INT_VALUE, "1");
|
||||||
|
IExpressionNode expression = new UnaryNode(value);
|
||||||
|
|
||||||
|
block.addStatement(new AssignNode(assignable, expression));
|
||||||
|
block.addStatement(new ReturnNode(null));
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "ThisDot", block);
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "ThisDot");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
class1.addMember(constructor);
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Constructor This Dot Test")
|
||||||
|
public void constructorThisDotTest() {
|
||||||
|
BlockNode block = new BlockNode();
|
||||||
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
|
memberAccess.addIdentifier("a");
|
||||||
|
|
||||||
|
AssignableNode assignable = new AssignableNode(memberAccess);
|
||||||
|
|
||||||
|
IExpressionNode expression = new UnaryNode("a");
|
||||||
|
|
||||||
|
block.addStatement(new AssignNode(assignable, expression));
|
||||||
|
block.addStatement(new ReturnNode(null));
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorThisDot", block);
|
||||||
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "ConstructorThisDot");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("private"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
class1.addMember(constructor);
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Void Methoden Test")
|
||||||
|
public void voidMethodenTest() {
|
||||||
|
ClassNode class1 = Helper.generateEmptyClass("VoidMethod");
|
||||||
|
BlockNode block = new BlockNode();
|
||||||
|
block.addStatement(new ReturnNode(null));
|
||||||
|
class1.addMember(new MethodNode("public", null, true, "test", block));
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Constructor Method call Test")
|
||||||
|
public void constructorMethodCallTest() {
|
||||||
|
BlockNode blockCon = new BlockNode();
|
||||||
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
|
memberAccess.addIdentifier("a");
|
||||||
|
|
||||||
|
AssignableNode assignable = new AssignableNode(memberAccess);
|
||||||
|
|
||||||
|
IExpressionNode expression = new UnaryNode(new MethodCallNode(null, "testMethod"));
|
||||||
|
|
||||||
|
blockCon.addStatement(new AssignNode(assignable, expression));
|
||||||
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorMethodCall", blockCon);
|
||||||
|
|
||||||
|
BlockNode blockMethod = new BlockNode();
|
||||||
|
blockMethod.addStatement(new ReturnNode(new UnaryNode(new ValueNode(EnumValueNode.INT_VALUE, "1"))));
|
||||||
|
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod", blockMethod);
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "ConstructorMethodCall");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
class1.addMember(constructor);
|
||||||
|
class1.addMember(method);
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Constructor Method call Parameters Test")
|
||||||
|
public void constructorMethodCallParametersTest() {
|
||||||
|
BlockNode blockCon = new BlockNode();
|
||||||
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
|
memberAccess.addIdentifier("a");
|
||||||
|
|
||||||
|
AssignableNode assignable = new AssignableNode(memberAccess);
|
||||||
|
|
||||||
|
MethodCallNode methodCall = new MethodCallNode(null, "testMethod");
|
||||||
|
methodCall.addExpression(new UnaryNode("a"));
|
||||||
|
IExpressionNode expression = new UnaryNode(methodCall);
|
||||||
|
|
||||||
|
blockCon.addStatement(new AssignNode(assignable, expression));
|
||||||
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "ConstructorMethodCallParameters", blockCon);
|
||||||
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
|
BlockNode blockMethod = new BlockNode();
|
||||||
|
blockMethod.addStatement(new ReturnNode(new UnaryNode("a")));
|
||||||
|
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.INT), false, "testMethod", blockMethod);
|
||||||
|
method.addParameter(new ParameterNode(new BaseType(TypeEnum.INT), "a"));
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "ConstructorMethodCallParameters");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
|
class1.addMember(constructor);
|
||||||
|
class1.addMember(method);
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Char Test")
|
||||||
|
public void charTest() {
|
||||||
|
BlockNode blockCon = new BlockNode();
|
||||||
|
MemberAccessNode memberAccess = new MemberAccessNode(true);
|
||||||
|
memberAccess.addIdentifier("a");
|
||||||
|
|
||||||
|
AssignableNode assignable = new AssignableNode(memberAccess);
|
||||||
|
|
||||||
|
MethodCallNode methodCall = new MethodCallNode(null, "testMethod");
|
||||||
|
methodCall.addExpression(new UnaryNode("a"));
|
||||||
|
IExpressionNode expression = new UnaryNode(methodCall);
|
||||||
|
|
||||||
|
blockCon.addStatement(new AssignNode(assignable, expression));
|
||||||
|
blockCon.addStatement(new ReturnNode(null));
|
||||||
|
ConstructorNode constructor = new ConstructorNode("public", "Char", blockCon);
|
||||||
|
constructor.addParameter(new ParameterNode(new BaseType(TypeEnum.CHAR), "a"));
|
||||||
|
|
||||||
|
BlockNode blockMethod = new BlockNode();
|
||||||
|
blockMethod.addStatement(new ReturnNode(new UnaryNode("a")));
|
||||||
|
MethodNode method = new MethodNode("public", new BaseType(TypeEnum.CHAR), false, "testMethod", blockMethod);
|
||||||
|
method.addParameter(new ParameterNode(new BaseType(TypeEnum.CHAR), "a"));
|
||||||
|
|
||||||
|
ClassNode class1 = new ClassNode("public", "Char");
|
||||||
|
class1.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.CHAR), "a"));
|
||||||
|
class1.addMember(constructor);
|
||||||
|
class1.addMember(method);
|
||||||
|
|
||||||
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
|
abstractSyntaxTree.addClass(class1);
|
||||||
|
|
||||||
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
|
runtimeException.printStackTrace();
|
||||||
|
}
|
||||||
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
|
assertNotNull(typedAst);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("Self Reference Test")
|
||||||
|
public void selfReferenceTest() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void test(int a, boolean b){
|
@Test
|
||||||
|
@DisplayName("Variable Compare Test")
|
||||||
|
public void variableCompareTest() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void test(boolean b, int a){
|
@Test
|
||||||
|
@DisplayName("Variable Calculation Test")
|
||||||
|
public void variableCalculationTest() {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// @Test
|
@Test
|
||||||
// public void alreadyDeclaredLocalFieldVar() {
|
@DisplayName("Main Method Test")
|
||||||
// ProgramNode programNode = new ProgramNode();
|
public void mainMethodTest() {
|
||||||
// List<ClassNode> classList = new ArrayList<>();
|
|
||||||
// AccessTypeNode accessTypeNode = new AccessTypeNode(EnumAccessTypeNode.PUBLIC);
|
}
|
||||||
// ClassNode classNode = new ClassNode(accessTypeNode, "testClass");
|
|
||||||
//
|
@Test
|
||||||
// SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer();
|
@DisplayName("While Test")
|
||||||
// ASTNode tast = semanticAnalyzer.generateTast(ast);
|
public void whileTest() {
|
||||||
//
|
|
||||||
// MemberNode memberNode2 = new FieldNode(accessTypeNode, new BaseTypeNode(EnumTypeNode.INT), "testVar");
|
}
|
||||||
// classNode.members.add(memberNode2);
|
|
||||||
//
|
@Test
|
||||||
// classList.add(classNode);
|
@DisplayName("Do While Test")
|
||||||
// programNode.classes = classList;
|
public void doWhileTest() {
|
||||||
//
|
|
||||||
// ASTNode typedAst = SemanticAnalyzer.generateTast(programNode);
|
}
|
||||||
//
|
|
||||||
// assertEquals(1, SemanticAnalyzer.errors.size());
|
@Test
|
||||||
// assertInstanceOf(AlreadyDeclaredException.class, SemanticAnalyzer.errors.getFirst());
|
@DisplayName("For Test")
|
||||||
// assertNull(typedAst);
|
public void forTest() {
|
||||||
// }
|
|
||||||
//
|
}
|
||||||
// @Test
|
|
||||||
// public void shouldWorkWithNoError() {
|
@Test
|
||||||
// ProgramNode programNode = new ProgramNode();
|
@DisplayName("Increment Test")
|
||||||
// List<ClassNode> classList = new ArrayList<>();
|
public void incrementTest() {
|
||||||
// AccessTypeNode accessTypeNode = new AccessTypeNode(EnumAccessTypeNode.PUBLIC);
|
ClassNode classNode = Helper.generateEmptyClass("Increment");
|
||||||
// ClassNode classNode = new ClassNode(accessTypeNode, "testClass");
|
classNode.addMember(new FieldNode(new AccessModifierNode("public"), new BaseType(TypeEnum.INT), "a"));
|
||||||
//
|
|
||||||
// SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer();
|
ProgramNode abstractSyntaxTree = new ProgramNode();
|
||||||
// ASTNode tast = semanticAnalyzer.generateTast(ast);
|
abstractSyntaxTree.addClass(classNode);
|
||||||
//
|
|
||||||
// assertEquals(semanticAnalyzer.errors.size(), 0);
|
ASTNode typedAst = SemanticAnalyzer.generateTast(abstractSyntaxTree);
|
||||||
// assertNotNull(tast);
|
for (Exception runtimeException : SemanticAnalyzer.errors) {
|
||||||
//
|
runtimeException.printStackTrace();
|
||||||
// MemberNode memberNode3 = getMemberNode(accessTypeNode);
|
}
|
||||||
// classNode.members.add(memberNode3);
|
assertTrue(SemanticAnalyzer.errors.isEmpty());
|
||||||
//
|
assertNotNull(typedAst);
|
||||||
// classList.add(classNode);
|
}
|
||||||
// programNode.classes = classList;
|
|
||||||
//
|
|
||||||
// ASTNode typedAst = SemanticAnalyzer.generateTast(programNode);
|
|
||||||
//
|
|
||||||
// assertEquals(0, SemanticAnalyzer.errors.size());
|
|
||||||
// assertEquals(programNode, typedAst);
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * This method is used to create a MemberNode representing a method.
|
|
||||||
// * It first creates a list of ParameterNodes and adds a ParameterNode to it.
|
|
||||||
// * Then, it creates a ParameterListNode using the list of ParameterNodes.
|
|
||||||
// * After that, it creates a list of StatementNodes and adds a StatementNode to it by calling the getStatementNode method.
|
|
||||||
// * Finally, it creates a MethodNode using the provided AccessTypeNode, a BaseTypeNode representing the return type of the method,
|
|
||||||
// * the method name, the ParameterListNode, and the list of StatementNodes, and returns this MethodNode.
|
|
||||||
// *
|
|
||||||
// * @param accessTypeNode The AccessTypeNode representing the access type of the method.
|
|
||||||
// * @return The created MemberNode representing the method.
|
|
||||||
// */
|
|
||||||
//private static MemberNode getMemberNode(AccessTypeNode accessTypeNode) {
|
|
||||||
// List<ParameterNode> parameterNodeList = new ArrayList<>();
|
|
||||||
// ParameterNode parameterNode1 = new ParameterNode(new BaseTypeNode(EnumTypeNode.INT), "param1");
|
|
||||||
// parameterNodeList.add(parameterNode1);
|
|
||||||
// ParameterListNode parameterListNode = new ParameterListNode(parameterNodeList);
|
|
||||||
//
|
|
||||||
// List<StatementNode> statementNodeList = new ArrayList<>();
|
|
||||||
//
|
|
||||||
// StatementNode statementNode1 = getStatementNode();
|
|
||||||
// statementNodeList.add(statementNode1);
|
|
||||||
//
|
|
||||||
// return new MethodNode(accessTypeNode, new BaseTypeNode(EnumTypeNode.INT), "testVar2", parameterListNode, statementNodeList);
|
|
||||||
//}
|
|
||||||
//
|
|
||||||
// /**
|
|
||||||
// * This method is used to create a StatementNode for an assignment operation.
|
|
||||||
// * It first creates two IdentifierExpressionNodes for 'this' and 'objectVar'.
|
|
||||||
// * Then, it creates a BinaryExpressionNode to represent the operation 'this.objectVar'.
|
|
||||||
// * After that, it creates a LiteralNode to represent the integer value 1.
|
|
||||||
// * Finally, it creates another BinaryExpressionNode to represent the assignment operation 'this.objectVar = 1',
|
|
||||||
// * and wraps this expression in an AssignmentStatementNode.
|
|
||||||
// *
|
|
||||||
// * @return The created AssignmentStatementNode representing the assignment operation 'this.objectVar = 1'.
|
|
||||||
// */
|
|
||||||
//private static StatementNode getStatementNode() {
|
|
||||||
// ExpressionNode expressionNodeObjectVariableLeft = new IdentifierExpressionNode("this");
|
|
||||||
// ExpressionNode expressionNodeObjectVariableRight = new IdentifierExpressionNode("objectVar");
|
|
||||||
//
|
|
||||||
// ExpressionNode expressionNodeLeft = new BinaryExpressionNode(expressionNodeObjectVariableLeft, expressionNodeObjectVariableRight, ExpresssionOperator.DOT);
|
|
||||||
//
|
|
||||||
// ExpressionNode expressionNodeRight = new LiteralNode(1);
|
|
||||||
//
|
|
||||||
// BinaryExpressionNode expressionNode = new BinaryExpressionNode(expressionNodeLeft, expressionNodeRight, ExpresssionOperator.ASSIGNMENT);
|
|
||||||
//
|
|
||||||
// return new AssignmentStatementNode(expressionNode);
|
|
||||||
//}
|
|
||||||
}
|
}
|
@ -1,23 +0,0 @@
|
|||||||
public class CombinedExample {
|
|
||||||
int number;
|
|
||||||
boolean flag;
|
|
||||||
char letter;
|
|
||||||
|
|
||||||
public CombinedExample(int number, boolean flag, char letter) {
|
|
||||||
this.number = number;
|
|
||||||
this.flag = flag;
|
|
||||||
this.letter = letter;
|
|
||||||
}
|
|
||||||
|
|
||||||
public void displayValues() {
|
|
||||||
System.out.println("Number: " + number);
|
|
||||||
System.out.println("Flag: " + flag);
|
|
||||||
System.out.println("Letter: " + letter);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static void main(String[] args) {
|
|
||||||
CombinedExample obj = new CombinedExample(10, true, 'X');
|
|
||||||
obj.displayValues();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user